- 静态登记
<receiver
android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="myAction" />
</intent-filter>
</receiver>
- 动态注冊
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("myAction");
registerReceiver(myReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(myReceiver);
}
- 发送广播
Intent intent = new Intent();
intent.setAction("myAction");
sendBroadcast(intent);
- 注意事项:
假设没有加入IntentFilter的Action。那么BroadcastReceiver将的onReceive(Context context, Intent intent)将收不到通知。除非你在发送的时候指明的详细的Class:
Intent intent = new Intent(MyActivity.this,MyReceiver.class);
sendBroadcast(intent);
版权声明:本文博主原创文章,博客,未经同意不得转载。