简体   繁体   English

如何在我的Android应用程序中以编程方式打开GPS?

[英]How turn on GPS programmatically in my android application?

If we use this code we see a message: searching for GPS . 如果使用此代码,则会看到一条消息: 搜索GPS However, the GPS symbol is merely shown; 但是,仅显示了GPS符号。 GPS doesn't actually work: GPS实际上不起作用:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Intent intent = new Intent("android.location.GPS_ENABLED_CHANGE");
    intent.putExtra("enabled", true);
    this.sendBroadcast(intent);   
}

Why isn't it working ? 为什么不起作用? And how to make it work correctly ? 以及如何使其正常工作?

That's not allowed anymore. 不再允许了。 If you take a look at this bug report , this hack was subverted in Android 4.4. 如果您查看此错误报告 ,则此漏洞已在Android 4.4中被颠覆。 It still works on older OS versions, though you shouldn't be using it anywhere now. 尽管您现在不应该在任何地方使用它,它仍然可以在较旧的OS版本上使用。 To quote that report: 引用该报告:

This doesn't work ... however, it can cause stuff to react as if the GPS status changed -- for example, the HTC One S will show the GPS icon in the status bar, even though the GPS is still disabled. 这是行不通的...但是,它可能导致东西做出反应,就像GPS状态发生了变化一样-例如,即使GPS仍处于禁用状态, HTC One S也会在状态栏中显示GPS图标。

That explains why you can see the GPS icon even though it isn't actually ON. 这就解释了为什么即使实际上没有打开GPS图标也能看到它的原因。 Now as for why you can't do that ... 现在,为什么你不能这样做...

Android's GPS technology periodically sends location data to Google even when no third-party apps are actually using the GPS function. 即使没有第三方应用程序实际在使用GPS功能,Android的GPS技术也会定期向Google发送位置数据。 In many Western countries this is seen as a major violation of privacy. 在许多西方国家,这被视为对隐私的严重侵犯。 That's why Google made it mandatory to get the user's consent before using the GPS function. 这就是Google强制使用GPS功能之前必须征得用户同意的原因。 The following dialog is seen whenever the user turns GPS on: 每当用户打开GPS时,都会看到以下对话框:

GPS用户权限

And hence it is no longer possible to programmatically change the GPS settings, as by necessity it requires the user's permission. 因此,不再可能以编程方式更改GPS设置,因为有必要需要用户的许可。 What the programmer can do is direct the user to the GPS settings by calling 程序员可以做的是通过调用将用户定向到GPS设置。

startActivity(context, new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));

and let the user make a choice. 并让用户做出选择。

As an interesting point, if you try sending the GPS_ENABLED_CHANGE broadcast on the new OS versions, you get a 有趣的是,如果您尝试在新的OS版本上发送GPS_ENABLED_CHANGE广播,则会收到

java.lang.SecurityException: Permission Denial: 
    not allowed to send broadcast android.location.GPS_ENABLED_CHANGE

error. 错误。 As you can see, its a SecurityException with a permission denial message. 如您所见,它是一个带有权限拒绝消息的SecurityException

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM