BroadcastReceiver---接收广播,用于应用程序之间传输信息,是对发送出来的管公布进行过滤并响应的组件。
发送:(可以通过intent传参数,在onReceive中获取)
按优先级大小(1000,-1000)向下传播,在iintent-infilter中声明,可以终止广播意图的继续传播 . 接收者可以篡改内容 .
abortBroadcast();//中止有序广播向下传播
实现:
继承 BroadcastReceiver,重写 onReceive方法,
注:onReceive 中不能进行耗时操作,它只有十秒的生命,超过时间android会以为它无响应,就会报错
public class MyBroadReceiver extends BroadcastReceiver { public static final String ACTION_SEND_SMS = "com.scxh.android.broadcastreceiver.send_sms"; public static final String ACTION_CALL = "com.scxh.android.broadcastreceiver.send_sms"; @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (action.equals(ACTION_SEND_SMS)) { Toast.makeText(context, "you have message", Toast.LENGTH_SHORT) .show(); } else if (action.equals(ACTION_CALL)) { Toast.makeText(context, "you have message", Toast.LENGTH_SHORT) .show(); } } }
</pre><pre name="code" class="html">注册一般都是包名+类名
<receiver android:name="com.scxh.android.broadcastreceiver.MyBroadReceiver"> <intent-filter > <action android:name="com.scxh.android.broadcastreceiver.send_sms"/> <action android:name="com.scxh.android.broadcastreceiver.com.scxh.android.broadcastreceiver.call"/> </intent-filter> </receiver>
<pre name="code" class="html"><pre name="code" class="html"><span style="font-size:14px;">MyBroadReceiver receiver = new MyBroadReceiver(); IntentFilter filter = new IntentFilter(ACTION_SEND_SMS); registerReceiver(receiver, filter);</span>
unRegisterReceiver(receiver);
建议:在activity声明周期中的onResume中注册,在onPause中注销