Android tutorial 6 ---- one of the four major components -- BroadcastReciever
The blog has not been updated for a long time. Make a basic summary. Continue with the previous record and learn new things! This series is an entry-level article.!
Hello everyone. Let's explain the BroadcastReceiver in Android today. In Android, Broadcast is a widely used
The mechanism for transmitting information between applications is a widely used mechanism for transmitting information between applications. In essence, it is a global monitoring mechanism.
Listener, used to listen to global broadcast messages of the system.
BroadcastReceiver has two registration methods: static registration and dynamic registration.
I. Static registration is configured in Anroidmanifest. xml:
Example:
The key code for sending an Activity is as follows:
String actionName = "android. intent. myfirstbroadcast"; // defines an Action
Intent broadcastIntent = new Intent (actionName );
SendBroadcast (broadcastIntent); // send Broadcast
To accept a message broadcast, you must inherit BroadcastReceiver, for example, the instance MyReceiver. The key code is as follows:
Public class MyReceiver extends BroadcastReceiver {
Public void onReceive (Context arg0, Intent arg1 ){
// TODO Auto-generated method stub
Toast toast = Toast. makeText (context, "the received broadcast is" + intent. getAction, Toast. LENGTH_SHORT );
Toast. show ();
}
2. Dynamic Registration: The application handles registration of such events. Generally, the onResume event is registered through registerReceiver,
UnregisterReceiver is used to cancel registration in onPause and other events. With this registration method, you can keep an eye on the event during running.
Protected void onResume (){
Super. onResume ();
System. out. println ("==== onResume ==== ");
IntentFilter intentFilter = new IntentFilter ();
IntentFilter. addAction ("android. intent. myfirstbroadcast ");
MyReceiver myfisrtreceiver = new MyReceiver (); // defines the worker er object
RegisterReceiver (myfirstreceiver, intentFilter); // register
}
Protected void onPause (){
Super. onPause ();
System. out. println ("==== onPause === ");
UnregisterReceiver (myfistreceiver); // unregister in onPause
}
Corresponding to the broadcast message acceptance class mycycler:
Public MyReceiver extends BroadcastReceiver {
@ Override
Public void onReceive (Context context, Intent intent ){
Toast toast = Toast. makeText (context, "Send dynamic register broadcast", Toast. LENGTH_SHORT );
Toast. show ();
}
};
The two registration methods have been completed. For more information about the broadcast mechanism, please refer to the source code analysis of Luo shengyang's broadcast registration listening mechanism. Here is an introduction.
Context provides two methods for sending broadcasts:
SendBroadcast: used to send normal Broadcast messages.
SendOrderedBroadcast: used to send an ordered Bradcast.