android - 如何在 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);
     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 - 如何在 Android 中以编程方式启用禁用 GPS?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15426144/

相关文章:

java - 在屏幕上显示 GPS 位置 - Android

iphone - GPS定位器

java - 找不到从方法 gps.a 引用的类 'gpr'

java - 经过卡尔曼滤波的 GPS 数据仍然波动很大

java - 有没有办法在使用通用图像加载器获取图像时指定额外的 header ?

java - Android字符串操作,字符串中的分隔行

android - 更新推送通知 Android

android - WebView loadDataWithBaseUrl - android 4.0.3 中的奇怪问题

java - 使用过滤器以编程方式设置 EditText 数字

android - 从 Android 检索 gps 修复中使用的卫星数量