我想在android中以编程方式更改gps设置但是崩溃了

时间:2016-09-16 07:44:04

标签: android

错误我正在:

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

我正在使用此代码。它在任何版本都不适用于我......

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

1 个答案:

答案 0 :(得分:0)

您在问题中显示的代码已从Android 4.4版停止运行。您将从Kitkat版本java.lang.SecurityException开始触发此异常:Permission Denial:不允许发送广播android.location.GPS_ENABLED_CHANGE

出于安全目的,Google开发人员阻止了之前正常工作的两种方法。 因此,结论是您无法以编程方式启动或关闭GPS。