Android权限ACCESS_FINE_LOCATION始终被拒绝

时间:2018-11-05 22:00:58

标签: java android permissions

我尝试检查单击按钮时的权限,它总是为我提供 -1

这是我的AndroidManifest文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.natalia.assignment_2">

    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

我也有compileSdkVersion 28,minSdkVersion 22和targetSdkVersion 28。

在我的MainActivity中,我尝试检查权限,但它始终被拒绝,因为它返回 -1

public class MainActivity extends AppCompatActivity  {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button buttonLocate = (Button) findViewById(R.id.buttonLocate);

    buttonLocate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            askForPermission("android.permission.ACCESS_FINE_LOCATION");
    });
}

private void askForPermission(String permission) {

    if(MainActivity.this != null) {
        if (PermissionChecker.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {

        // IT ALWAYS COMES TO THIS IF AND SHOWS -1
            Toast.makeText(this, "" + String.valueOf(PermissionChecker.checkSelfPermission(MainActivity.this, permission)), Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
        }
    } 
}

}

我尝试了很多小时,但是没有帮助...这里可能有什么问题?

1 个答案:

答案 0 :(得分:0)

  

askForPermission(“ android.permission.ACCESS_FINE_LOCATION”);

这就是传递给方法时的结果。 尝试做:

askForPermission("Manifest.permission.ACCESS_FINE_LOCATION");

这可能有效。如果没有,我检查了其他一些文章,到处都是,它不是作为字符串传递的。

尝试在不使用字符串的情况下使用它:

(PermissionChecker.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)

希望它能起作用!