一、發(fā)送標(biāo)準(zhǔn)廣播
Intent intent = new Intent("com.example.broadcasttest. MY_BROADCAST");
sendBroadcast(intent);
二癣疟、發(fā)送有序廣播
Intent intent = new Intent("com.example.broadcasttest. MY_BROADCAST");
sendOrderedBroadcast(intent, null);
截斷廣播:
public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received in MyBroadcastReceive", Toast.LENGTH_SHORT).show();
abortBroadcast();
}
}
abortBroadcast();
-
截斷后摸袁,后續(xù)的接收器就不會接收到廣播了。
-
接收廣播的先后順序:優(yōu)先級 android:priority:
<receiver android:name=".MyBroadcastReceiver">
<intent-filter android:priority="100" >
<action android:name="com.example.broadcasttest.MY_BROADCAST"/>
</intent-filter>
</receiver>
三庇忌、本地廣播
- 前面我們發(fā)送和接收的廣播全部都是屬于系統(tǒng)全局廣播窗骑,即發(fā)出的廣播可以被其他任何的任何應(yīng)用程序接收到,并且我們也可以接收來自于其他任何應(yīng)用程序的廣播漆枚。這樣就很容易會引起安全性的問題创译。
- Android 本地廣播機(jī)制,使用這個機(jī)制發(fā)出的廣播只能夠在應(yīng)用程序的內(nèi)部進(jìn)行傳遞墙基,并且廣播接收器也只能接收來自本應(yīng)用程序發(fā)出的廣播软族,這樣所有的安全性問題就都不存在了。
- 本地廣播是無法通過靜態(tài)注冊的方式來接收的残制。因為要用時程序肯定已經(jīng)啟動了立砸。
public class MainActivity extends Activity {
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
localBroadcastManager = LocalBroadcastManager.getInstance(this); // 獲取實例
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.example.broadcasttest. LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent); // 發(fā)送本地廣播
}
});
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter); // 注冊本地廣播監(jiān)聽器
}
@Override
protected void onDestroy() {
super.onDestroy();
localBroadcastManager.unregisterReceiver(localReceiver);
}
class LocalReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "received local broadcast", Toast.LENGTH_SHORT).show();
}
}
}
localBroadcastManager = LocalBroadcastManager.getInstance(this); // 獲取實例
Intent intent = new Intent("com.example.broadcasttest. LOCAL_BROADCAST");
localBroadcastManager.sendBroadcast(intent); // 發(fā)送本地廣播
localBroadcastManager.unregisterReceiver(localReceiver);
intentFilter = new IntentFilter();
intentFilter.addAction("com.example.broadcasttest.LOCAL_BROADCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter); // 注冊本地廣播監(jiān)聽器
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者