如何在 Android 中以编程方式启用禁用 GPS? [英] How can I enable disable GPS programmatically in Android?

查看:23
本文介绍了如何在 Android 中以编程方式启用禁用 GPS?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am creating an anti-theft application and, locating my phone through sms and it works perfectly until 2.3. But in 4.0 I can't turn on or off gps programmatically is there any other possible way to switch on gps through code.

推荐答案

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

Try using this code. It worked for me on all the versions.

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

这篇关于如何在 Android 中以编程方式启用禁用 GPS?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆