为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

冉冉说 2019-11-27 10:47:59
我正在创建一个防盗应用程序,并通过短信找到我的手机,它可以完美运行到2.3。但是在4.0中,我无法以编程方式打开或关闭gps,是否还有其他可能的方式通过代码打开gps。
查看完整描述

3 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

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


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

    }

}


查看完整回答
反对 回复 2019-11-27
?
牛魔王的故事

TA贡献1830条经验 获得超3个赞

尝试使用以下代码关闭gps Intent intent = new Intent(“ android.location.GPS_ENABLED_CHANGE”); intent.putExtra(“ enabled”,false); sendBroadcast(intent); 

查看完整回答
反对 回复 2019-11-27
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

我收到“ java.lang.SecurityException:权限被拒绝:不允许发送广播android.location.GPS_ENABLED_CHANGE”。应用程序崩溃了

查看完整回答
反对 回复 2019-11-27
  • 3 回答
  • 0 关注
  • 484 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信