Programmatically turn ON GPS in android [duplicate

2020-03-31 08:24发布

问题:

Possible duplicates,

How to enable/disable gps and mobile data in android programmatically?

I have been seeing people telling that they are able to turn ON the GPS in android programatically. But I'm using the same code and not able to do that.

It is just showing that "Searching for GPS .." but not actually doing it.

Here is the code I'm using,

  //Enable GPS
  Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
  intent.putExtra("enabled", true);
  sendBroadcast(intent);

  //Disable GPS
 Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
 intent.putExtra("enabled", false);
 sendBroadcast(intent);

I also tried this,

    String provider = Settings.Secure.getString(context.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")); 
        context.sendBroadcast(poke);
    }

But when I do,

 LocationManager manager = (LocationManager) getSystemService( getApplicationContext().LOCATION_SERVICE );
 boolean isGPSEnabled = manager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

it returns me isGPSEnabled as false always. If I turn on the gps manually it is returned as true.

Can any body tell me is it possible to ON the GPS like this? If so, where I'm going wrong.

回答1:

//Enable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
context.sendBroadcast(intent);

//Disable GPS
Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", false);
context.sendBroadcast(intent);

use context when you broadcast.

hope this works..

To enable mobile data you should use this -

final ConnectivityManager conman = (ConnectivityManager) context
            .getSystemService(Context.CONNECTIVITY_SERVICE);
    final Class conmanClass = Class.forName(conman.getClass().getName());
    final Field iConnectivityManagerField = conmanClass
            .getDeclaredField("mService");
    iConnectivityManagerField.setAccessible(true);
    final Object iConnectivityManager = iConnectivityManagerField
            .get(conman);
    final Class iConnectivityManagerClass = Class
            .forName(iConnectivityManager.getClass().getName());
    final Method setMobileDataEnabledMethod = iConnectivityManagerClass
            .getDeclaredMethod("setMobileDataEnabled", Boolean.TYPE);
    setMobileDataEnabledMethod.setAccessible(true);

    setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);