Android broadcast receiver custom permissions

夙愿已清 提交于 2020-04-30 07:45:08

问题


In view of the security model in Android, I'm trying out custom permissions. I'm trying out to enforce broadcaster permissions in my application. The scenario is that I have an activity A, which triggers a broadcasts like this (with a permission) :

Intent updateUserBroadcast = new Intent();
updateUserBroadcast.setAction("android.intent.action.ACTION_UPDATE_USERNAME");
updateUserBroadcast.putExtra("username", userName);
sendBroadcast(updateUserBroadcast, "com.android.MaliciousApp.RECEIVE_BROADCAST");

In this activity A, I register a receiver in onCreate like this :

    private BroadcastReceiver mUpdateUsernameReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.v("gaurav", "onReceive called");

        SharedPreferences prefs = context.getSharedPreferences("profilePref", Context.MODE_WORLD_READABLE);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putString("username", intent.getStringExtra("username"));
        editor.apply();

        Toast.makeText(context, context.getString(R.string.string_successfully_updated), Toast.LENGTH_SHORT).show();
    }
};

I expect the receiver to receive the broadcast as it has the required permissions that it needs. But it doesn't receive the broadcast sent out by the activity. There could be arguments on why I'm not using LocalBroadcastManager, but my motive is to figure out why this method isn't working as expected.

I have not declared my receiver in manifest and registering it dynamically only. All the above code is from a single activity within the same application. So there's no IPC involved here, just a simple example to check out the permissions. Any help would be appreciated.


回答1:


When you want to send a intent through a broadcast that have a permission, you should register your broadcast receiver using

registerReceiver(receiver, intentFilter, "com.android.MaliciousApp.RECEIVE_BROADCAST", null);

And in your manifest, you will have to tell which permissions are granted to your app.

<manifest>
    ...
    <uses-permission android:name="com.android.MaliciousApp.RECEIVE_BROADCAST" />
    <permission android:name="com.android.MaliciousApp.RECEIVE_BROADCAST" />
    ...
</manifest>

You can refer to the documentation about permission here.



来源:https://stackoverflow.com/questions/34349837/android-broadcast-receiver-custom-permissions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!