在 Android 应用程序中获取用户的位置权限

新手上路,请多包涵

我试图通过典型的权限框获取用户的实际位置:像这样: 在此处输入图像描述

如果有人知道怎么做,请回答。

原文由 Antonio Gschossmann 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 506
2 个回答

在运行时请求权限以使用设备当前位置,如下所示:

 if (ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(YourActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
      ActivityCompat.requestPermissions(YourActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
      return;
}else{
  // Write you code here if permission already given.
}

原文由 Haresh Chhelana 发布,翻译遵循 CC BY-SA 3.0 许可协议

你可以这样做

在清单中:

 <uses-feature android:name="android.hardware.location.gps" />

在您想要此权限请求的活动中:

 ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

然后使用此功能获取用户答案:

 public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
    case 1: {
        // If request is cancelled, the result arrays are empty.
        if (grantResults.length > 0
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

        } else {
            // permission denied, boo! Disable the
            // functionality that depends on this permission.
        }
    return;
    }
        // other 'case' lines to check for other
        // permissions this app might request
}
}

如果用户接受一次,那么您的应用程序将记住它,您将不再需要发送此 DialogBox。请注意,如果用户决定,他可以稍后将其禁用。然后在请求位置之前,您必须测试权限是否仍然被授予:

  public boolean checkLocationPermission()
{
String permission = "android.permission.ACCESS_FINE_LOCATION";
int res = this.checkCallingOrSelfPermission(permission);
return (res == PackageManager.PERMISSION_GRANTED);
}

原文由 Abhishek Charismatic 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题