This example shows a custom broadcast event. What we need to do is write the code that sends the broadcast in the main activity, and then write the code that receives the broadcast in the class that receives the broadcast. 1. After clicking the button in the main event, send the broadcast mainactivity.java:
Public class Mainactivity extends Appcompatactivity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
super.oncreate (savedinstancestate);
Setcontentview (r.layout.activity_main);
}
Public void OnClick (view view) {
Intent Intent = new Intent ();
intent.setaction ("com.thanlon.diyAction"); Types of custom broadcasts
// Sendbroadcast (intent); send broadcast directly
Intent.putextra ("Info_key", " The broadcast passed parameters "); send a broadcast with parameters;
Sendbroadcast (Intent, "com.thanlon.permission.name"); You need a recipient with the specified permission to receive the broadcast
}
}
2. Write a class to receive the broadcast. Mybroadcastreceiver.java:
Public class Mybroadcastreceiver extends broadcastreceiver {
@Override
Public void onreceive(context context, Intent Intent) {
log.d ("Thanlon", " receive custom broadcasts ");
String info = Intent.getstringextra ("Info_key"); //Accept the parameters of the broadcast belt
log.d ("Thanlon", info);
}
}
3. Configure the custom broadcast type and the custom recipient's permissions in Androidmanifest.xml (register broadcast). Androidmanifest.xml:
<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
package= "Thonlon.example.cn.diybroadcastreceiverdemo" >
<!--Custom Recipient permissions --
<permission android:name= "Com.thanlon.permission.name"/>
<!--Configure recipient permissions --
<uses-permission android:name= "Com.thanlon.permission.name"/>
<application
android:allowbackup= "true"
android:icon= "@mipmap/ic_launcher"
android:label= "@string/app_name"
android:roundicon= "@mipmap/ic_launcher_round"
android:supportsrtl= "true"
android:theme= "@style/apptheme" >
<activity android:name= ". Mainactivity ">
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!--register a broadcast, this example customizes the broadcast type-
<receiver android:name= ". Mybroadcastreceiver ">
<intent-filter>
<action android:name= "com.thanlon.diyAction"/>
</intent-filter>
</receiver>
</application>
</manifest>
4. Under Logcat, see if the broadcast recipient is receiving a broadcast.
It is obvious that the broadcast was received correctly and the parameters of the broadcast pass were received.
Custom Broadcast (Broadcastreceiver) event--android Development