The Android system sends many system-level broadcasts, such as a screen shutdown and low battery broadcast. The same app can initiate custom "developer-defined" broadcasts. Broadcasting is one of the ways that messages are sent from one app to another.
Broadcastreceiver is a component that listens and responds to broadcasts. In this article, we'll show you how to send a custom broadcast and how to use the manifest file to define a broadcastreceiver to listen to this broadcast. We can send the broadcast message as soon as we call Sendbroadcast.
1, writing Myreceiver,myreceiver code is mainly inheriting the broadcastreceiver of the receiving class.
ImportAndroid.content.BroadcastReceiver;ImportAndroid.content.Context;Importandroid.content.Intent;ImportAndroid.util.Log;ImportAndroid.widget.EditText; Public classMyreceiverextendsBroadcastreceiver {Private Final StaticString TAG = "BR"; @Override Public voidOnReceive (Context context, Intent Intent) {log.i (TAG,"Broadcast:" + intent.getaction () + "\ n"); }}
2, register the broadcast, can be registered dynamically through Java code or in the manifest XML file.
<?XML version= "1.0" encoding= "Utf-8"?><Manifestxmlns:android= "Http://schemas.android.com/apk/res/android" Package= "Com.example.guangbo"Android:versioncode= "1"Android:versionname= "1.0" > <USES-SDKandroid:minsdkversion= "8"android:targetsdkversion= "+" /> <ApplicationAndroid:allowbackup= "true"Android:icon= "@drawable/ic_launcher"Android:label= "@string/app_name"Android:theme= "@style/apptheme" > <ActivityAndroid:name= "Com.example.guangbo.MainActivity"Android:label= "@string/app_name" > <Intent-filter> <ActionAndroid:name= "Android.intent.action.MAIN" /> <categoryAndroid:name= "Android.intent.category.LAUNCHER" /> </Intent-filter> </Activity> <receiverAndroid:name= "Com.example.guangbo.MyReceiver" > <Intent-filter> <ActionAndroid:name= "Com.example.android.USER_ACTION" /> </Intent-filter> </receiver> </Application></Manifest>
3, send, can call the Activity object's method Sendbroadcast can send the broadcast.
ImportAndroid.os.Bundle;Importandroid.app.Activity;Importandroid.content.Intent;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.Button; Public classMainactivityextendsActivityImplementsOnclicklistener {Button btn=NULL; @Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); BTN= (Button) This. Findviewbyid (R.id.btnsendbroadcast); Btn.setonclicklistener ( This); } @Override Public voidOnClick (view view) {Intent I=NewIntent ("Com.example.android.USER_ACTION"); Sendbroadcast (i); }}
I also learn from others, thanks to Baidu, thanks to the following article bloggers.
http://blog.csdn.net/zajin/article/details/12992705
Android custom broadcast send and receive