Search code examples
javaandroidandroid-permissionsandroid-broadcastandroid-broadcastreceiver

Android Broadcasts - sending and receiving with permissions


I try to implement the permission approach of BroadcastReceiver.

In sender class, I try to send a normal broadcast

    Intent intent = new Intent();
    intent.setAction("com.vn.BroadcastReceiver");
    intent.putExtra("Foo", "Bar");
    sendBroadcast(intent);

with AndroidManifest file

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

In receiver class, I write a custom FirstBroadcastReceiver

    public class FirstBroadcastReceiver extends BroadcastReceiver {
        private static final String TAG = FirstBroadcastReceiver.class.getSimpleName();

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive: " + intent.getStringExtra("Foo"));
        }
    }

and its AndroidManifest

    <permission android:name="com.nhp" />

    <receiver
        android:permission="com.nhp"
        android:exported="true"
        android:name=".receivers.FirstBroadcastReceiver">
        <intent-filter>
            <action android:name="com.vn.BroadcastReceiver" />
        </intent-filter>
    </receiver>

I install receiver application first and sender then. And it worked!!

But when I try to call sendBroadcast(intent,"com.nhp");, it never trigger any thing. Anyone can explain for me why? Thank you


Solution

  • The custom permission should be declared in the sender and the receiver should request for it.

    Moreover, broadcast receiver doesn't need the android:permission attribute. You should only use it if sender must have a specific permission.


    Sender

    The sender declares the custom permission in its manifest

    <permission android:name="com.nhp" />
    

    and sends the broadcast

    Intent intent = new Intent();
    intent.setAction("com.vn.BroadcastReceiver");
    intent.putExtra("Foo", "Bar");
    sendBroadcast(intent, "com.nhp");
    

    Receiver

    The receiver requests for the custom permission in its manifest and listens for broadcasts

    <uses-permission android:name="com.nhp"/>
    ...
    ...
    ...
    <receiver
        android:exported="true"
        android:name=".receivers.FirstBroadcastReceiver">
        <intent-filter>
            <action android:name="com.vn.BroadcastReceiver" />
        </intent-filter>
    </receiver>
    

    Of course, the order of the installations is important and the sender app must be installed first as it defines the custom permission.

    Note: Custom permissions are registered when the app is installed. The app that defines the custom permission must be installed before the app that uses it.