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

Ant*_*ann 3 java permissions android location

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

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

Har*_*ana 10

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

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.
} 
Run Code Online (Sandbox Code Playgroud)


Abh*_*tic 5

你可以这样做

在清单中:

<uses-feature android:name="android.hardware.location.gps" />
Run Code Online (Sandbox Code Playgroud)

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

ActivityCompat.requestPermissions(this,new String[]
{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
Run Code Online (Sandbox Code Playgroud)

然后使用此函数获取用户答案:

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
}
}
Run Code Online (Sandbox Code Playgroud)

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

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