1. 创建Receiver,两种方式,动态和静态:
(1)静态注册:
首先自定义个Receiver,
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "MyReceiver broadcast", 10000).show();
}
}
然后在AndroidManifest注册即可:
<intent-filter>
<action android:name="com.test.broadcasting" />
</intent-filter>
</receiver>
(2)动态注册:
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("com.test.broadcasting");
// 注册BroadcastReceiver
this.registerReceiver(receiver, intentFilter);
// 取消注册
// this.unregisterReceiver(receiver);
}
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "receive broadcast", 10000).show();
}
};
2.发送广播:
这个非常简单,只需一行代码即可:
3. 应用场景:
最常见的就是SD插拔的广播注册(android.content.Intent.ACTION_MEDIA_MOUNTED).
网名:@"老舟"
兴趣:@"影音,阅读"
动态:@"系统架构设计,Android通信模块开发"
网址:@"http://kilonet.cnblogs.com"
签名:@"--------------------------------------------------
Stay Hungry , Stay Foolish
求 知 若 渴,处 事 若 愚
--------------------------------------------------"
]; // Never Release