Android Create an AlertDialog Builder

In my previous tutorial ‘Android Get Location in Google Map with GPS and LocationManager – Tutorial‘ you learned how to get location from GPS and show marker on google map. In this tutorial you will learn how to show AlertDialog if gps is not enabled.

Dialog

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

AlertDialog

Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);

Step 1:  Open your previously saved project

My project was ‘Android Get Location in Google Map with GPS and LocationManager – Tutorial‘  , so i opened this project.

Step 2: Open GpsTracker.java file and add a new Class file to check GPS is enabled or not.

// Class to check GPS/Location is enabled or not //
public  void chkGPSorNetworkEnabled(){

    locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

    // Getting GPS Status
    isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
    //Getting Network Status
    isNetworkEnabled = locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

    String gpsMsg = "Please Enable your GPS/Location Service";
    String netMsg = "Please Enable your Network Service";

    if(!isGPSEnabled){
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setMessage(gpsMsg);

        dialog.setPositiveButton("GPS Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                context.startActivity(gpsIntent);
            }
        });
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();
    }else if(!isNetworkEnabled){
        AlertDialog.Builder dialog = new AlertDialog.Builder(context);
        dialog.setMessage(netMsg);

        dialog.setPositiveButton("Network Settings", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Intent gpsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
                context.startActivity(gpsIntent);
            }
        });
        dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });
        dialog.show();
    }else{
        getLocation();
    }

}

Step 3:  Write code onCreate() method to allow permission on runtime

// Checking permission is allowed or not
int Permission_All = 1;

String[] Permissions = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
if(!hasPermissions(this, Permissions)){
    ActivityCompat.requestPermissions(this, Permissions, Permission_All);
}

Step 4:  Create a new hasPermission() method.

public static boolean hasPermissions(Context context, String... permissions){

    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && context!=null && permissions!=null){
        for(String permission: permissions){
            if(ActivityCompat.checkSelfPermission(context, permission)!= PackageManager.PERMISSION_GRANTED){
                return  false;
            }
        }
    }
    return true;
}

Step 5: Call newly created method in GpsTracker.java file named chkGPSorNetworkEnabled()

gpsTracker.chkGPSorNetworkEnabled();

Full Source Code:

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.suraj.androidgpstracker" >

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="@string/google_maps_key" />

        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

GPSTracker.java

package com.example.suraj.androidgpstracker;

import android.*;
import android.Manifest;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.audiofx.BassBoost;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.support.v4.content.ContextCompat;

import java.security.Permission;

/**
 * Created by Suraj on 03/02/2017.
 */

public class GPSTracker extends Service implements LocationListener {


    private final Context context;

    boolean isGPSEnabled =false;
    boolean isNetworkEnabled =false;
    boolean canGetLocation = false;

    Location location;
    protected LocationManager locationManager;

    public GPSTracker(Context context){
        this.context=context;
    }

    // Class to check GPS/Location is enabled or not //
    public  void chkGPSorNetworkEnabled(){

        locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);

        // Getting GPS Status
        isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
        //Getting Network Status
        isNetworkEnabled = locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);

        String gpsMsg = "Please Enable your GPS/Location Service";
        String netMsg = "Please Enable your Network Service";

        if(!isGPSEnabled){
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
            dialog.setMessage(gpsMsg);

            dialog.setPositiveButton("GPS Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent gpsIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                    context.startActivity(gpsIntent);
                }
            });
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            dialog.show();
        }else if(!isNetworkEnabled){
            AlertDialog.Builder dialog = new AlertDialog.Builder(context);
            dialog.setMessage(netMsg);

            dialog.setPositiveButton("Network Settings", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    Intent gpsIntent = new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS);
                    context.startActivity(gpsIntent);
                }
            });
            dialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialogInterface, int i) {

                }
            });
            dialog.show();
        }else{
            getLocation();
        }

    }


    //Create a GetLocation Method //
    public  Location getLocation(){
        try{

            locationManager = (LocationManager) context.getSystemService(LOCATION_SERVICE);
            isGPSEnabled = locationManager.isProviderEnabled(locationManager.GPS_PROVIDER);
            isNetworkEnabled=locationManager.isProviderEnabled(locationManager.NETWORK_PROVIDER);
            //chkGPSorNetworkEnabled();
            if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                    || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED ){

                if(isGPSEnabled){
                    if(location==null){
                        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 10000,10,this);
                        if(locationManager!=null){
                            location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        }
                    }
                }
                // if lcoation is not found from GPS than it will found from network //
                if(location==null){
                    if(isNetworkEnabled){

                            locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 10000,10,this);
                            if(locationManager!=null){
                                location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                            }

                    }
                }

            }

        }catch(Exception ex){

        }
        return  location;
    }

    // followings are the default method if we imlement LocationListener //
    public void onLocationChanged(Location location){

    }

    public void onStatusChanged(String Provider, int status, Bundle extras){

    }
    public void onProviderEnabled(String Provider){

    }
    public void onProviderDisabled(String Provider){

    }
    public IBinder onBind(Intent arg0){
        return null;
    }

}

MapsActivity.java

package com.example.suraj.androidgpstracker;

import android.*;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    private GPSTracker gpsTracker;
    private Location mLocation;
    double latitude, longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        // Checking permission is allowed or not
        int Permission_All = 1;

        String[] Permissions = {android.Manifest.permission.ACCESS_COARSE_LOCATION, android.Manifest.permission.ACCESS_FINE_LOCATION};
        if(!hasPermissions(this, Permissions)){
            ActivityCompat.requestPermissions(this, Permissions, Permission_All);
        }

        gpsTracker = new GPSTracker(MapsActivity.this);
        // checking GPS is enabled or not//
        gpsTracker.chkGPSorNetworkEnabled();
        mLocation = gpsTracker.getLocation();
        if(mLocation!=null) {
            latitude = mLocation.getLatitude();
            longitude = mLocation.getLongitude();
        }
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        // Add a marker in Sydney and move the camera
        LatLng sydney = new LatLng(latitude, longitude);
        mMap.addMarker(new MarkerOptions().position(sydney).title("I'm here..."));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(sydney));
    }

    public static boolean hasPermissions(Context context, String... permissions){

        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.M && context!=null && permissions!=null){
            for(String permission: permissions){
                if(ActivityCompat.checkSelfPermission(context, permission)!= PackageManager.PERMISSION_GRANTED){
                    return  false;
                }
            }
        }
        return true;
    }
}

 

Post a comment

Your email address will not be published. Required fields are marked *