如何在Android 4.4中以编程方式启用/禁用GPS?

时间:2013-12-12 04:51:49

标签: android gps

Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
intent.putExtra("enabled", true);
getBaseContext().sendBroadcast(intent);`

我使用此代码启用GPS,但它给我这样的错误。

java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE from pid=1208, uid=10051

所以任何人都可以给我解决方案。

2 个答案:

答案 0 :(得分:5)

你永远不会这样做。它是API中的错误。您现在可以为用户提供设置,以便使用以下意图进行选择:

startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

答案 1 :(得分:0)

public void turnGPSOn()
     {
     Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
     intent.putExtra("enabled", true);
     this.ctx.sendBroadcast(intent);

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