1 <receiver android:name=".MyBroadcastReceiver"> 2 <intent-filter> 3 <action android:name="com.example.administrator.broadcastreceiver.SEND_MESSAGE"/> 4 </intent-filter> 5 </receiver>
特点:不管应用程序是否处于活动状态,都会进行监听。比如某个应用程序监听内存使用情况,当在手机上安装好之后,不管其处于什么状态都会监听内存状态。
2.3 生命周期
BroadcastReceiver的生命周期很简单,如下图
3.Broadcast介绍
3.1Broadcast被分为两种:
1>Normal Broadcast(普通广播):
Normal Broadcast是完全异步的,可以在同一时刻,被所有接收者接收到(逻辑上),消息传递效率比较高。缺点是接收者不能将结果传给下一个接收者,并且无法阻止Broadcast Intent的传播
2>Ordered Broadcast(有序广播):
Ordered Broadcast的接收者将按照预先声明的优先级次序依次接收Broadcast。如果priority:A>B>C,那么Broadcast先传给A->B->C。
3.2 发送广播的两种方式:
1>sendBroadcast():发送Normal Broadcast
2>sendOrderedBroadcast():发送Ordered Broadcast
对于Ordered Broadcast而言系统会根据接收者声明的优先级别按顺序依次执行接收者,优先收到Broadcast的接收者可以终止Broadcast(调用BroadcastReceiver的abortBroadcast()方法),那么后面的接收者将无法取到Broadcast.
不仅如此,对于Ordered Broadcast而言,优先级别高的接收者,可以通过setResultExtras(Bundle bundle)将结果存到Broadcast中,下一个接收者可以通过Bundle bundle = getResultExtras(true)获取上一个数据
TIP:系统接收短信,发出的Broadcast属于Ordered Broadcast.如果想拦截用户收到短信,可以设置优先级,让自定义的BroadcastReceiver先接收到短信,然后终止broadcast。
4.下面是一个Ordered Broadcast广播例子,代码如下:
MainActivity类:
1 package com.example.administrator.broadcastreceivertest; 2 3 import android.app.Activity; 4 import android.content.Intent; 5 import android.os.Bundle; 6 import android.view.View; 7 8 9 public class MainActivity extends Activity { 10 11 private static final String SHOW_MESSAGE = "com.example.administrator.broadcastreceiver.SEND_MESSAGE"; 12 @Override 13 protected void onCreate(Bundle savedInstanceState) { 14 super.onCreate(savedInstanceState); 15 setContentView(R.layout.activity_main); 16 } 17 18 public void sendOrderedBroadcast(View view){ 19 Intent intent = new Intent(SHOW_MESSAGE); 20 intent.putExtra("msg","Ordered Broadcast"); 21 sendOrderedBroadcast(intent,null); 22 } 23 24 }
MyBroadcastReceiver类
1 package com.example.administrator.broadcastreceivertest; 2 3 import android.content.BroadcastReceiver; 4 import android.content.Context; 5 import android.content.Intent; 6 import android.util.Log; 7 import android.widget.Toast; 8 9 10 public class MyBroadcastReceiver extends BroadcastReceiver{ 11 12 @Override 13 public void onReceive(Context context, Intent intent) { 14 String msg = intent.getStringExtra("msg"); 15 Log.i("tag","MyBroadcastReceiver:"+msg); 16 Toast.makeText(context,"MyBroadcastReceiver:"+msg,Toast.LENGTH_SHORT).show(); 17 } 18 }
MyBroadcastReceiver2类