【问题标题】:How can I enable disable GPS programmatically in Android? [duplicate]如何在 Android 中以编程方式启用禁用 GPS? [复制]
【发布时间】:2013-03-03 19:09:02
【问题描述】:

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

【问题讨论】:

标签: android gps


【解决方案1】:

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

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 = new Intent("android.location.GPS_ENABLED_CHANGE"); intent.putExtra("启用", false);发送广播(意图);
  • 对于那些面临“ctx”问题的人。 ctx 只不过是活动的实例。如果您在活动中声明这些函数,请使用“className.this”而不是 ctx。
  • 我收到“java.lang.SecurityException: Permission Denial: not allowed to send broadcast android.location.GPS_ENABLED_CHANGE”。应用程序崩溃
  • 这在 Android 4.4 之后不再起作用
猜你喜欢
  • 2011-06-10
  • 1970-01-01
  • 1970-01-01
  • 2013-05-21
  • 2012-05-05
  • 2021-08-01
  • 2011-04-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多