如何处理在Android M中删除广播接收器的权限?

Gru*_*kes 29 android android-permissions android-6.0-marshmallow

我有一些遗留代码,我正在为Marshmallow提供安全许可.

使用PHONE_STATE权限进行广播,如下所示:

<receiver android:name="redacted.TheBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.PHONE_STATE"></action>
        <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    </intent-filter>
</receiver>
Run Code Online (Sandbox Code Playgroud)

如果PHONE_STATE权限被授予,但稍后用户被拒绝,那么当有电话呼叫时,存在与权限相关的崩溃.但崩溃发生广播接收器的onReceive()被调用之前(崩溃在android.app.ActivityThread.handleReceiver中).这意味着广播接收器甚至没有机会检查是否授予许可并处理该情况.

所以我的问题是,如果有这样的广播接收器,代码如何处理用户已禁用权限的情况,因为AFAIK没有API来监视权限发生时的变化,因此代码无法知道该权限已被撤销,因此它无法取消注册其广播接收器.

Kos*_*rak 1

至于 Android Marsmallow 中的权限,您可能需要在接收器被调用之前检查权限,如下所示:

// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
                Manifest.permission.PHONE_STATE)
        != PackageManager.PERMISSION_GRANTED) {

    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.PHONE_STATE)) {

        // Show an expanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.

    } else {

        // No explanation needed, we can request the permission.

        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.PHONE_STATE},
                MY_PERMISSIONS_REQUEST_PHONE_STATE);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
}
Run Code Online (Sandbox Code Playgroud)

这是一个迟到的答案,但我希望它能帮助别人!