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

如何在Android中以编程方式启用或禁用GPS?,android,gps,Android,Gps,我正在创建一个防盗应用程序,并通过短信找到我的手机,它在2.3版之前都能正常工作。 但在4.0中,我无法以编程方式打开或关闭gps。是否有其他可能的方式通过代码打开gps。尝试使用此代码。所有的版本都对我有用 public void turnGPSOn() { Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("enabled", true); thi

我正在创建一个防盗应用程序,并通过短信找到我的手机,它在2.3版之前都能正常工作。
但在4.0中,我无法以编程方式打开或关闭gps。是否有其他可能的方式通过代码打开gps。

尝试使用此代码。所有的版本都对我有用

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

请查看您问题中的代码图片。您检查过此链接吗?您好,它在三星galaxy y中不起作用。它将gps接收器设置为常开模式,得到修复后应设置为睡眠模式。尝试此代码关闭gps Intent Intent=新Intent(“android.location.gps_ENABLED_CHANGE”);intent.putExtra(“已启用”,false);发送广播(意图);对于那些面临“ctx”问题的人。ctx只是活动的实例。如果您在活动中声明这些函数,请使用“className.this”而不是ctx.I'm get“java.lang.SecurityException:权限拒绝:不允许发送广播android.location.GPS\u ENABLED\u CHANGE”。应用程序崩溃自Android 4.4以来,该应用程序不再工作