Karthik Karthik - 5 months ago 22
Android Question

How can i check user really enabled the gps location on his phone in android

My application needs GPS,so i have redirected the user to enable the GPS in case if it's off.

AlertDialog.Builder dialog = new AlertDialog.Builder(contxt);
dialog.setMessage("Enable GPS Location Service");
dialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface paramDialogInterface, int paramInt) {
// TODO Auto-generated method stub
Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
contxt.startActivity(myIntent);
}
});


The problem is that the user goes to the location setting from the pop up window and if the user don't activate the GPS from the location setting,instead of that the user press the back button and goes back to the application.If the person again goes back to the app instead of activating the GPS means, the application have to show the dialog box again.

So i have ensured it again like below,

GetLocationService();

LocationManager manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE );
boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);

if(statusOfGPS==false)
GetLocationService();


but again the user, from the location settings, could not enable the GPS and by clicking on the "back" button and going back to the application. How can i force the user to enable the GPS and work with the application.

Answer

How can i force the user to enable the GPS and work with the application.

To force user enable GPS before moving next screen in Application:

1. Create a method in which check is GPS is enabled or not and start next Activity accordingly :

private void isGPSEnabled(){
     LocationManager manager;
     boolean statusOfGPS =  
           manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
     if(statusOfGPS){
        // start next Activity
      }else{
         // show alert for enabling GPS
      }
  }

2. On AlertDialog Positive Button click start GPS setting screen using startActivityForResult :

@Override
 public void onClick(DialogInterface paramDialogInterface, int paramInt) {
    // TODO Auto-generated method stub
    Intent myIntent = new Intent( Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    contxt.startActivityForResult(myIntent,100);
 }

3. Override onActivityResult to check GPS is enabled or not when user back to app from Settings:

@Override
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        isGPSEnabled();
    }

Also make AlertDialog Cancelable false form both back and touch of outside Dialog:

dialog.setCanceledOnTouchOutside(false);
dialog.setCancelable(false);
Comments