广播发送,接收和跳转

时间:2020-12-04 10:10:44
发送广播
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.putExtra("key", "这是来自广播的消息");
intent.setAction("com.example.broadcastreceiver.intent.MainActivity");
MainActivity.this.sendBroadcast(intent);
}
});

}
接收,静态注册广播,
 <activity
android:name="com.test.broadcastreceiver2.ABC"
></activity>
<!-- 静态注册 -->
<receiver android:name="com.test.broadcastreceiver2.BroadCastReceiver_JieShou_1" >
<intent-filter>
<action android:name="com.test.broadcastreceiver.intent.MainActivity" />
</intent-filter>
</receiver>
//动态注册广播
public class MainActivity extends Activity {

private BroadCastReceiver_JieShou_1 receiver;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
receiver = new BroadCastReceiver_JieShou_1();
IntentFilter filter = new IntentFilter();
filter.addAction("com.test.broadcastreceiver.intent.MainActivity");
this.registerReceiver(receiver, filter);

}
@Override
protected void onDestroy() {
super.onDestroy();
this.unregisterReceiver(receiver);
receiver=null;
}
}
//接收广播,并跳转
public class BroadCastReceiver_JieShou_1 extends BroadcastReceiver {@Overridepublic void onReceive(Context context, Intent intent) {Log.v("OtherActivity_1", intent.getStringExtra("key"));Intent intent2 = new Intent(context, ABC.class);intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);context.startActivity(intent2);}}