0

I am using this code will get Security exception.

private void turnGPSOn(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);
if(!provider.contains("gps")){ //if gps is disabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider"); 
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3")); 
    sendBroadcast(poke);
}
}

private void turnGPSOff(){
    String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

if(provider.contains("gps")){ //if gps is enabled
    final Intent poke = new Intent();
    poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
    poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
    poke.setData(Uri.parse("3")); 
    sendBroadcast(poke);
}
}

How to fix problem automatic enable GPS.

Anirudh Sharma
  • 7,968
  • 13
  • 40
  • 42
Ramesh
  • 47
  • 10

2 Answers2

1

For The security purpose Google developer has block above both methods which were previously working fine. So you cant enable GPS programatically

1

Well Now There is no Way/work-around To Enable Gps Progmatically.

what you can do is to Ask From the user to open the gps, if gps is not enabled.

first check if gps is enabled or not

public boolean check_Gps(Context context) {
    LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
    boolean statusOfGPS = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return statusOfGPS;
}

and then open gps Actvity if not enabled.

if (!check_Gps(Your_Activity_Name.this)) {

   open_Gps_Activity(Your_Activity_Name.this);


 }

  public void open_Gps_Activity(Context context) {
    final Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

and you can also show a toast to tell the user that if you will not turn on the gps your app will not work properly.

Moubeen Farooq Khan
  • 2,875
  • 1
  • 11
  • 26