广播分为两种:标准广播和有序广播。
1. 系统广播
以监听网络变化为例子:
public class MainActivity extends Activity{
private IntentFilter intentFilter;
private NetworkChangeFilter networkChangeReceiver;
@Override
protected void onCreate(Bundle saveInstaceState){
...
intentFilter = new IntentFIlter();
intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
networkChangeReceiver = new NetworkChangeFilter();
registerReceiver(networkChangeReceiver, intentFilter); // 2. 注册接收者
}
@Override
protected void onDestroy(){
unregisterReceiver(networkChangeReceiver);
}
// 1. 接收者定义
class NetworkChangeFilter implements BrodcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
// TODO
}
}
}
// 3. Manfiest.xml申请权限
<use-premission android:name="android.permission.ACCESS_NETWORK_STATE" />
上面是动态注册,如果改成如下形式,那么就可实现静态注册开机启动:
<android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application >
<receiver android:name=".BootCompleteReceiver">
<intent-filter>
<action android:name="android.intent.action_BOOT_COMPLETED" />
</intent-filter>
</application>
2. 自定义广播
自定义广播和系统广播类似,但需用户手动采用sendBroadcast触发:
- 注册
<application >
<receiver android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.examle.broadcast.MY_BROADCAST" />
</intent-filter>
</application>
- 定义接收者
class MyBroadcastReceiver implements BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
// TODO
// abortBroadcast(); 如果是有序广播可以截断广播
}
}
- 手动触发广播
Intent intent = new Intent("com.examle.broadcast.MY_BROADCAST");
sendBroadcast(intent);
// sendOrderBroadcast(intent, null); 有序广播
3. 本地广播
前两种广播都是系统全局广播,即发出的广播可以被其他应用程序接收到,这样存在着安全性问题;本地广播可以解决这个问题。
public class MainActivity extends Activity{
private IntentFilter intentFilter;
private LocalReceiver localReceiver;
private LocalBroadcastManager localBroadcastManager;
@Override
protected void onCreate(Bundle savedInstanceState){
...
localBroadcastManager = LocalBroadcastManager.getInstance(this);
intentFilter = new IntentFilter(); intentFilter.addAction("com.example.broadcast.LOCAL_BRODCAST");
localReceiver = new LocalReceiver();
localBroadcastManager.registerReceiver(localReceiver, intentFilter);
...
Intent intent = new Intent("com.example.broadcast.LOCAL_BRODCAST");
localBroadcastManager.sendBroadcast(intent);
}
@Override
protected void onDestroy(){
unregisterReceiver(networkChangeReceiver);
}
class LocalReceiver implements BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent){
// TODO
}
}
}
网友评论