简体   繁体   English

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

[英]How to enable/disable GPS Programatically in Android 4.4?

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

I use this code for Enable GPS but it give me error like this. 我使用此代码启用GPS,但它给我这样的错误。

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

So anyone give me solution of that. 所以任何人都给我解决方案。

you never do that. 你永远不会那样做。 it was bug in API. 它是API中的错误。 you can now give settings to user for choose using below intent: 您现在可以为用户提供设置,以便使用以下意图进行选择:

startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
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);
     }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM