您的位置:首页 > 其它

基于BroadCast Receiver的一些思考

2014-05-16 00:31 211 查看
1.BroadCast Receiver的作用?

用来接收系统的一些短暂的非耗时消息,从而进行的响应的动作;

2.BroadCast Receiver有几种?

常规消息:sendBroadCast();

对于消息接收者,其接收的顺序是不固定的,但由于接收时间间隙小,我们可以认为是同时接收。

排序消息:sendOrderedBroadCast();

其排序定义在<Intent-filter />中,通过属性android:priority来定义,数字越大,越先接收,一般系统定义的该属性都为负数。

3.如何定义BroadCast Receiver ?

继承BroadcastReceiver

/**
 * @author Lean
 *
 */
public class MyBroadCastReceiver extends BroadcastReceiver {

	@Override
	public void onReceive(Context context, Intent intent) {
		if (intent.getAction().equals("org.lean.action.BroadCastMsg")) {
			Log.v("LeanLog", "onReceiver()");
		}
	}

}
注册AndroidManifest.xml

<receiver android:name=".MyBroadCastReceiver">
            <intent-filter android:priority="2" >
                <action android:name="org.lean.action.BroadCastMsg"/>
            </intent-filter>
        </receiver>
调用

private void sendBroadCast() {
		Intent intent=new Intent();
		intent.setAction("org.lean.action.BroadCastMsg");
		
		sendBroadcast(intent);
		//sendOrderedBroadcast(intent,null);
	}


4.BroadcastReceiver是异步还是同步的?
发送消息如sendBroadcast是异步的,指把消息直接发送到MessageQueue中,再经由Looper取出并分发给相同action的<receiver />

而onReceive是在主线程中接收的,也就是说,在onReceive中操作时间应该不超过10s,避免ANR错误;

5.BroadcastReceiver如何进行拦截?

一般通过把android:priority属性的值提高。并在onReceive()中处理完后调用abortBroadcast();

6.BroadcastReceiver的生命周期:

在应用安装时,通过<Intent-filter />的HashMap进行注册。与ContentProvider不同的是,ContentProvider是在应用安装时通过URI注册的;

当调用系统的排序广播时,通过权限高低的顺序分发广播。

7.系统的广播如何调用:

通过Intent的Action属性查看4类组件的系统Action,并调用他们;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: