ActivityCompat.requestPermissions 不显示提示

ActivityCompat.requestPermissions does not show prompt

我正在尝试请求 ACCESS_FINE_LOCATION 权限以获取用户的当前位置。

我的日志显示我的应用程序在查询 ContextCompat.checkSelfPermission() 时目前没有此权限,但在调用 ActivityCompat.requestPermissions() 时没有任何显示。

我的 Google 地图代码(实现 OnMapReadyCallbackActivityCompat.OnRequestPermissionsResultCallback())在 FragmentActivity.

我已经设法让 requestPermissions() 功能在应用程序的其他活动中成功运行,它只是带有 Google 地图的那个。当放在 ActivityonCreate() 方法或 onMapReady() 中(它需要去的地方)时,它不起作用。

if(ContextCompat.checkSelfPermission(LocationActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        Log.d(TAG, "not granted");
        final String[] permissions = new String[] {android.Manifest.permission.ACCESS_FINE_LOCATION};
    if(ActivityCompat.shouldShowRequestPermissionRationale(this, android.Manifest.permission.ACCESS_FINE_LOCATION)) {
            Log.d(TAG, "rationale");
            // Explain to the user why permission is required, then request again
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setMessage("We need permissions")
                    .setCancelable(false)
                    .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            ActivityCompat.requestPermissions(LocationActivity.this, permissions, 1);
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();

    } else {
        Log.d(TAG, "request" + android.Manifest.permission.ACCESS_FINE_LOCATION);
        // If permission has not been denied before, request the permission
        ActivityCompat.requestPermissions(LocationActivity.this, permissions, 1);
    }
} else {
    Log.d(TAG, "granted");
}

有什么想法吗?这与我的 Activity 的 class (FragmentActivity) 或 Google 地图异步调用权限请求有关吗?

完全删除我的 class 后,它仍然无法正常工作,我意识到这个 Activity 正在使用 TabHost 实例化。

当我停止使用TabHost时,提示成功。我猜新的权限提示不支持 TabHosts - 这是一个错误吗?

相同的问题

我最终创建了一个 PermissionsRequestActivity,它代表我的 TabHost 处理权限请求和响应,然后退出(通过 Intent extras Bundle 传递请求的权限信息)。
它将对请求的响应作为广播传回,由我的 TabHost 接收。

有点乱,但工作正常!

检查您是否已经像 Android M 之前一样在 Android 的清单文件中添加了请求的权限,只有这样您才会得到预期的行为。

将权限添加到您的清单中,以便您可以通过 ActivityCompat.requestPermissions:

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

我将分享适合我的代码。在我想看到提示的 activity 的 protected void onCreate(Bundle savedInstanceState) {} 方法中,我包含了这段代码:

    /* Check whether the app has the ACCESS_FINE_LOCATION permission and whether the app op that corresponds to
     * this permission is allowed. The return value is an int: The permission check result which is either
     * PERMISSION_GRANTED or PERMISSION_DENIED or PERMISSION_DENIED_APP_OP.
     * Source: https://developer.android.com/reference/android/support/v4/content/PermissionChecker.html
     * While testing, the return value is -1 when the "Your location" permission for the App is OFF, and 1 when it is ON.
     */
    int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
    // The "Your location" permission for the App is OFF.
    if (permissionCheck == -1){
        /* This message will appear: "Allow [Name of my App] to access this device's location?"
         * "[Name of my Activity]._instance" is the activity.
         */
        ActivityCompat.requestPermissions([Name of my Activity]._instance, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_ACCESS_FINE_LOCATION);
    }else{
        // The "Your location" permission for the App is ON.
        if (permissionCheck == 0){
        }
    }

在 protected void onCreate(Bundle savedInstanceState) {} 方法之前,我创建了以下常量和方法:

public static final int REQUEST_CODE_ACCESS_FINE_LOCATION = 1; // For implementation of permission requests for Android 6.0 with API Level 23.

// Code from "Handle the permissions request response" at https://developer.android.com/training/permissions/requesting.html.
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE_ACCESS_FINE_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.                

            } 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
    }
}

我在使用 TabHost 的项目中遇到了同样的问题。 基于@Robin 解决方案,我使用 EventBus 库将消息从 child activity 发送到 TabActity。

事件总线:https://github.com/greenrobot/EventBus

创建活动 object :

public class MessageEvent {
    private String message;
    public MessageEvent(String message){
        this.message = message;
    }

    public String getMessage(){
        return this.message;
    }
}

在你的主要 Activity :

private EventBus eventBus = EventBus.getDefault();
@Override
protected void onCreate(Bundle savedInstanceState) {
    eventBus.register(this);
}
@Override
protected void onDestroy() {
    eventBus.unregister(this);
    super.onDestroy();
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
    if (event.getMessage().equals("contacts")){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && checkSelfPermission(android.Manifest.permission.WRITE_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(MainPage.this,new String[]{android.Manifest.permission.WRITE_CONTACTS}, 100 );
        }
    }
};

为您想要请求的权限设置不同的消息。 在你的 child activity 中你可以比 post 足够的信息 :

EventBus.getDefault().post(new MessageEvent("contacts"));

注意 onRequestPermissionsResult 回调和请求代码 ;)!它只适用于主要 activity.