BroadcastReceiver can not only receive system broadcasts, but also receive customized broadcasts.
1. Define a broadcast receiver
Copy the codeThe code is as follows:
public class MyReceiver extends BroadcastReceiver
{
public MyReceiver()
{
(TAG,"MyReceiver");
}
//The getAction() of Intent can be used to distinguish different broadcasts received
@Override
public void onReceive(Context arg0, Intent arg1)
{
String action=();
//TO-DO LIST
}
}
2. Send broadcast, define the action flag, and send it with Intent
Copy the codeThe code is as follows:
//Instantiate the BroadcastReceiver
MyReceiver mReceiver=new MyReceiver();
//Set a unique action and send it with Intent
Intent intent=new Intent();
(str);
sendBroadcast(intent);
3. Register only broadcast receivers that receive the specified action
Copy the codeThe code is as follows:
IntentFilter filter1=new IntentFilter();
(str);
registerReceiver(mReceiver,filter1);
4. Cancel the broadcast receiver
Copy the codeThe code is as follows:
unregisterReceiver(mReceiver);