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

Gop*_*.cs 30 gps android

我正在创建一个防盗应用程序,并通过短信定位我的手机,它完美地工作,直到2.3.但在4.0我无法以编程方式打开或关闭gps是否有任何其他可能的方式来通过代码打开gps.

Sag*_*til 41

尝试使用此代码.它适用于所有版本.

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);


    }
}
// automatic turn off the gps
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);
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 从Android 4.4开始,这不再起作用了 (7认同)
  • 尝试此代码关闭gps Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled",false); sendBroadcast(意向); (4认同)
  • 我收到"java.lang.SecurityException:Permission Denial:不允许发送广播android.location.GPS_ENABLED_CHANGE".应用程序正在崩溃 (4认同)
  • 对于那些面临"ctx"问题的人.ctx只不过是活动的实例.如果在活动中声明这些函数,则使用"className.this"而不是ctx. (3认同)
  • 嗨它不适合三星银河y.它把gps接收器一直打开模式,在修复之后它应该处于睡眠模式.. (2认同)