在我的应用程序中,我想通过GPS获取设备的位置。好的,我宣布<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
在清单中和应用启动时,系统会要求用户允许 GPS。
当我阅读Android dok时,有两种选择:
-
满足所有位置设置:
task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() { @Override public void onSuccess(LocationSettingsResponse locationSettingsResponse) { // All location settings are satisfied. The client can initialize // location requests here. // ... } });
-
位置设置不满足:
task.addOnFailureListener(this, new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { if (e instanceof ResolvableApiException) { // Location settings are not satisfied, but this can be fixed // by showing the user a dialog. try { // Show the dialog by calling startResolutionForResult(), // and check the result in onActivityResult(). ResolvableApiException resolvable = (ResolvableApiException) e; resolvable.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS); } catch (IntentSender.SendIntentException sendEx) { // Ignore the error. } } } });
似乎有两种资源,一种,我必须在清单中声明,另一种,我必须在运行时请求。
- 我做对了吗?
- 为什么会有这种区别?
通过在AndroidManifest.xml
中添加权限,应用程序告诉 Android 系统我将在应用程序中需要此权限才能按预期运行。
此后,如果您要求的权限被列为危险,则系统会向用户请求权限,否则系统将在运行时授予您该权限(这意味着您需要请求权限,系统将根据需要采取措施(。
此权限规则适用于 API 级别 23+。
如果用户授予您权限,您将能够访问用户的该信息。
在位置的情况下,您需要进行额外的检查(问题的第二点(,因为只有在启用位置设置时,系统才能检查位置。也就是说,WiFi符号列表中的位置符号,移动数据符号。
编辑:如果您省略检查位置设置的代码片段,那么如果用户的位置像此图像一样关闭,那么您将无法获得位置。
并且没有"android.permission.LOCATION_SETTINGS_ENABLED"
这样的许可.