1. Pay attention to the broadcast initiation action, and register the broadcast in the AndroidMainfest. xml file, and the broadcast needs to be filtered using intent-filter.
2. System-level broadcast: The call is the same. You only need to register the broadcast in the AndroidMainfest. xml file and add system-level filter conditions.
3. Broadcast can also be registered in the code, but it should be noted that you should not forget to deregister the broadcast at the same time:
Generally, this broadcast is registered in Activity. onResume:
IntentFilter filter = new IntentFilter ();
BroadcastReceiver receiver ER = new BroadcastReceiver ();
RegisterBroadcast (receiver er, filter );
Generally, the broadcast is canceled in Activity. onPause.
UnRegisterBroadcast (receiver ER );
In addition, broadcast should be registered and destroyed in the Code as much as possible, which can save the use of the device battery. If it is registered in AndroidMainfest. xml, the broadcast will always exist, and it is not easy to manage and consume power.
Package com. king. android. controls;
Import com. king. android. R;
Import android. app. Activity;
Import android. content. Intent;
Import android. OS. Bundle;
Import android. view. View;
Import android. view. View. OnClickListener;
Import android. widget. Button;
/**
* Description: launch a broadcast instance.
** Author: Andy. Liu
* Time: 11:57:20
**/
Public class BroadCastReceiverActivity extends Activity {
Public static final String MY_BROADCAST = "com. king. android. MY_BROADCAST ";
Public static final String MY_WORD = "myword ";
@ Override
Protected void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. main );
Button btnSend = (Button) findViewById (R. id. btn_voice );
BtnSend. setText ("broadcast ");
BtnSend. setVisibility (View. VISIBLE );
BtnSend. setOnClickListener (new OnClickListener (){
@ Override
Public void onClick (View v ){
Intent intent = new Intent ();
Intent. setAction (MY_BROADCAST );
Intent. putExtra (MY_WORD, "my name is kobe ");
SendBroadcast (intent );
}
});
}
}
Package com. king. android. controls;
Import android. content. BroadcastReceiver;
Import android. content. Context;
Import android. content. Intent;
Import android. widget. Toast;
/**
* Description: receives a broadcast.
* Author: Andy. Liu
* Time: 11:58:14
**/
Public class MyReceiver extends BroadcastReceiver {
@ Override
Public void onReceive (Context context, Intent intent ){
String msg = intent. getStringExtra (BroadCastReceiverActivity. MY_WORD );
Toast. makeText (context, "already received broadcast ==============" + msg, Toast. LENGTH_LONG). show ();
}
}