0

我想保护设备密码后面的某些功能。因此,如果用户尝试使用这些功能,他们必须再次确认密码。

这是活动类中的代码。

Context appContext = activity.getApplicationContext();
RestrictionsManager rManager = (RestrictionsManager) appContext.getSystemService(appContext.RESTRICTIONS_SERVICE);
rManager.requestPermission(RestrictionsManager.ACTION_REQUEST_PERMISSION, "someID", new PersistableBundle());

这是处理来自 PermissionResponseReceiver 类中密码确认对话框的响应的代码。

public class PermissionResponseReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
       ......
    }
}

有没有一种简单的方法来引用 PermissionResponseReceiver.onReceive(...) 中的原始活动。目前我必须跟踪活动实例并提供一个公共静态方法来获取它,但这似乎很hacky,我正在寻找一个替代方案。你有什么建议吗?谢谢。

4

1 回答 1

1

使用本地广播在您PermissionResponseReceiver和您的Activity.

在你的PermissionResponseReceiver

public class PermissionResponseReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(final Context context, Intent intent) {
       ......

    // Create the intent that will be broadcast
    Intent intent = new Intent("my-permission-response-action");
    // Add any extra data you want to put in the intent here..

    // Broadcast to any registered receivers
    LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
    }
}

在你的Activity

@Override
public void onResume() {
    super.onResume();

    final LocalBroadcastManager localBroadcastManager = LocalBroadcastManager.getInstance(this);

    // IntentFilter to define which actions mLocalBroadcastReceiver will respond to
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("my-permission-response-action");

    // Register for desired broadcasts
    localBroadcastManager.registerReceiver(mLocalBroadcastReceiver, intentFilter);
}

@Override
public void onPause() {

    // Unregister our mLocalBroadcastReceiver
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mLocalBroadcastReceiver);
    super.onPause();
}

/**
 * My Local Broadcast Receiver
 */
private BroadcastReceiver mLocalBroadcastReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {

        if (intent.getAction().equals(my-permission-response-action)) {
            // Our Activity has received the broadcast from PermissionResponseReceiver.
            // If we added any extras to the intent we can extract them here
            // for use in the Activity
        }
    }
};
于 2015-10-31T01:23:59.160 回答