Android Broadcast Receiver-android learning tour
First, inherit the BroadcastReceiver class and register it in manifest.
public class MyReceiver extends BroadcastReceiver { public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { throw new UnsupportedOperationException(Not yet implemented); }}
Register in mainifest
Dynamically register and cancel broadcast receivers
Code:
Worker Er:
public class MyReceiver extends BroadcastReceiver { public static final String ACTION = peng.liu.testview.intent.action.MyReceiver; public MyReceiver() { } @Override public void onReceive(Context context, Intent intent) { System.out.println(intent.getStringExtra(data)+hello); }}
Main class:
public class MainActivity extends Activity implements View.OnClickListener{ private MyReceiver receiver = null; private Button send,reg,unReg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.send).setOnClickListener(this); findViewById(R.id.reg).setOnClickListener(this); findViewById(R.id.unReg).setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()){ case R.id.send: Intent intent = new Intent(MyReceiver.ACTION); intent.putExtra(data,jiekxueyuan); sendBroadcast(intent); break; case R.id.reg: if (receiver == null){ receiver = new MyReceiver(); registerReceiver(receiver,new IntentFilter(MyReceiver.ACTION)); } break; case R.id.unReg: if (receiver != null){ unregisterReceiver(receiver); receiver = null; } break; } }}
Layout code:
Broadcast priority
Static registration in manifest this time
Android: priority: Used to set priority. A larger number indicates a higher priority.
High-priority terminal Broadcast
// Note that sendOrderedBroadcast (intent, null); Intent intent = new Intent (MyReceiver. ACTION); intent. putExtra (data, jiekxueyuan); sendOrderedBroadcast (intent, null );
Receiving part
Public class MyReceiver2 extends BroadcastReceiver {public MyReceiver2 () {}@ Override public void onReceive (Context context, Intent intent) {System. out. println (intent. getStringExtra (data); // This user is used to interrupt the next low-priority acceptance of abortBroadcast ();}}