知識(shí)點(diǎn):
- 廣播的發(fā)送分為:普通廣播、有序廣播
- 廣播的注冊(cè)分為:靜態(tài)厦酬、動(dòng)態(tài)
先看普通廣播:
靜態(tài)注冊(cè)方式
1胆描、定義一個(gè)廣播接收類(lèi),繼承BroadcastReceiver
public class MyBroadCast_One extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_One收到廣播消息:"+intent.getExtras().getString("msg"));
}
2仗阅、AndroidManifest.xml注冊(cè)這個(gè)廣播接收器昌讲,注意filter篩選廣播
<receiver android:name="com.bzx.androidlearning.MyBroadCast_One">
<intent-filter>
<action android:name="BC"/>
</intent-filter>
</receiver>
3、MainActivity中發(fā)送廣播减噪,注意是sendBroadcast普通廣播短绸。setAction可以理解為這個(gè)廣播的名字,上一個(gè)步驟中intent-filter篩選出這個(gè)廣播
Intent intent1 = new Intent();
intent1.putExtra("msg", "這是一條普通廣播");
intent1.setAction("BC");
sendBroadcast(intent1);
動(dòng)態(tài)注冊(cè)方式
1筹裕、和靜態(tài)區(qū)別在于醋闭,不用在manifest中進(jìn)行注冊(cè) ,直接在activity中進(jìn)行注冊(cè)朝卒。注意证逻,注冊(cè)內(nèi)容要寫(xiě)在發(fā)送廣播前面。
//動(dòng)態(tài)注冊(cè)廣播
myBroadCast_Two = new MyBroadCast_Two();
IntentFilter intentFilter = new IntentFilter("BC");
registerReceiver(myBroadCast_Two, intentFilter);
2扎运、動(dòng)態(tài)注冊(cè)的廣播要在activity銷(xiāo)毀時(shí)進(jìn)行解綁
@Override
protected void onDestroy() {
//動(dòng)態(tài)注冊(cè)廣播要在銷(xiāo)毀時(shí)取消注冊(cè)
unregisterReceiver(myBroadCast_Two);
super.onDestroy();
}@Override
有序廣播:
1瑟曲、activity中有序廣播發(fā)送饮戳,注意是sendOrderedBroadcast
Intent intent2 = new Intent();
intent2.putExtra("msg", "這是一條普通廣播");
intent2.setAction("BC");
sendOrderedBroadcast(intent2, null);
2、與普通廣播一點(diǎn)差別在于廣播接收部分洞拨。有序廣播可以對(duì)消息進(jìn)行截?cái)嗷蛘咛幚沓豆蕖_@里MyBroadCast_Two 因?yàn)槭莿?dòng)態(tài)注冊(cè),所以優(yōu)先級(jí)高一些烦衣,先接收到廣播后歹河,可以對(duì)廣播進(jìn)行處理setResultExtras
public class MyBroadCast_Two extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_Two收到廣播消息");
Bundle bundle = new Bundle();
//abortBroadcast();
bundle.putString("msg", "MyBroadCast_Two截?cái)嗟南?);
setResultExtras(bundle);
}
}
3、MyBroadCast_One后接收到廣播花吟。通過(guò) getResultExtras(true)接收MyBroadCast_Two 處理后的廣播消息秸歧。另外,MyBroadCast_Two 中注釋的部分abortBroadcast()如果使用的話衅澈,就會(huì)截?cái)鄰V播键菱,MyBroadCast_One就不會(huì)收到發(fā)送的廣播了
public class MyBroadCast_One extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
System.out.println("MyBroadCast_One收到廣播消息:"+intent.getExtras().getString("msg"));
Bundle bundle = getResultExtras(true);
System.out.println("MyBroadCast_One收到截?cái)嗟南ⅲ?+bundle.getString("msg"));
}
}