1. 创建Receiver,两种方式,动态和静态:
(1)静态注册:
首先自定义个Receiver,
public class MyReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "MyReceiver broadcast", 10000).show();
}
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(context, "MyReceiver broadcast", 10000).show();
}
}
然后在AndroidManifest注册即可:
<receiver android:name=".MyReceiver">
<intent-filter>
<action android:name="com.test.broadcasting" />
</intent-filter>
</receiver>
<intent-filter>
<action android:name="com.test.broadcasting" />
</intent-filter>
</receiver>
(2)动态注册:
private void regReceiver() {
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();
}
};
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.发送广播:
这个非常简单,只需一行代码即可:
this.sendBroadcast(new Intent("com.test.broadcasting"));
3. 应用场景:
最常见的就是SD插拔的广播注册(android.content.Intent.ACTION_MEDIA_MOUNTED).