使用BroadCastReceiver

来源:互联网 发布:mysql可视化工具导入 编辑:程序博客网 时间:2024/05/23 01:04

转载请注明出处: http://blog.csdn.net/a992036795/article/details/51596610

概念:BroadCast是一种广泛运用的,在应用程序之间传输信息的机制,Android中的广播与传统意义上的电台广播类似,一个广播可以有任意个接收者。广播机制是一个典型的发布-订阅模式。
Android的广播可分为普通广播、有序广播、本地广播和 Sticky广播。

一、普通广播
普通广播是完全异步的,通过Context的SendBroadCast()函数来发送,消息传递的效率比较高,但所有的receivers(接收器)的执行顺序不确定,缺点是:接受着不能将处理消息传递给一下个接受着,并且无法终止广播Intent的传播。
普通广播的使用:首先定义一个广播类,用来接收广播:

public class SimpleBroadCast extends BroadcastReceiver {    private static final String TAG = "SimpleBroadCast";    @Override    public void onReceive(Context context, Intent intent) {        Log.i(TAG, "onReceive: ");    }}

然后在注册该广播接收器:

  @Override    protected void onStart() {        super.onStart();        /*注册广播*/        registerReceiver(broadCast,new IntentFilter(ACTION));    }    @Override    protected void onStop() {        super.onStop();        /*取消注册*/        unregisterReceiver(broadCast);    }

这里我选择动态注册,当然也可以静态注册即在清单文件中注册。
最后:贴出发送广播的代码:

  /*发送一个普通广播*/                sendBroadcast(new Intent(ACTION));

二、有序广播。
有序广播通过Context.sendOrderBroadcast()来发送,所有的广播接收器按照优先级一次执行,广播接收器的有限制级可以通过receiver的intent-filter中的android:priotiry属性来设置,数值越大优先级越高,当广播接收器接收到广播之后,可以使用setResult()函数来将结果传递给下一个广播接收器,然后下一个广播接收器通过getResult函数获得上一个广播接收器返回的结果,并使用abortBroadcast函数来让系统丢弃该广播,使得该广播不在传递。
使用:
一、在清单文件中注册:

    <receiver android:name=".SimpleBroadCast">            <intent-filter                android:priority="100">                <action>"hello"</action>            </intent-filter>        </receiver>

发送广播代码:

  sendOrderedBroadcast(new Intent(ACTION),null);

上文提到的BroadCastReveiver中的setResut 和getResult,这里给出方法在BroadCastReceiver中的定义

public final void setResultCode(int code) {        checkSynchronousHint();        mPendingResult.mResultCode = code;    }    /**     * Retrieve the current result code, as set by the previous receiver.     *      * @return int The current result code.     */    public final int getResultCode() {        return mPendingResult != null ? mPendingResult.mResultCode : 0;    }    /**     * Change the current result data of this broadcast; only works with     * broadcasts sent through     * {@link Context#sendOrderedBroadcast(Intent, String)     * Context.sendOrderedBroadcast}.  This is an arbitrary     * string whose interpretation is up to the broadcaster.     *      * <p><strong>This method does not work with non-ordered broadcasts such     * as those sent with {@link Context#sendBroadcast(Intent)     * Context.sendBroadcast}</strong></p>     *      * @param data The new result data; may be null.     *      * @see #setResult(int, String, Bundle)     */    public final void setResultData(String data) {        checkSynchronousHint();        mPendingResult.mResultData = data;    }    /**     * Retrieve the current result data, as set by the previous receiver.     * Often this is null.     *      * @return String The current result data; may be null.     */    public final String getResultData() {        return mPendingResult != null ? mPendingResult.mResultData : null;    }    /**     * Change the current result extras of this broadcast; only works with     * broadcasts sent through     * {@link Context#sendOrderedBroadcast(Intent, String)     * Context.sendOrderedBroadcast}.  This is a Bundle     * holding arbitrary data, whose interpretation is up to the     * broadcaster.  Can be set to null.  Calling this method completely     * replaces the current map (if any).     *      * <p><strong>This method does not work with non-ordered broadcasts such     * as those sent with {@link Context#sendBroadcast(Intent)     * Context.sendBroadcast}</strong></p>     *      * @param extras The new extra data map; may be null.     *      * @see #setResult(int, String, Bundle)     */    public final void setResultExtras(Bundle extras) {        checkSynchronousHint();        mPendingResult.mResultExtras = extras;    }    /**     * Retrieve the current result extra data, as set by the previous receiver.     * Any changes you make to the returned Map will be propagated to the next     * receiver.     *      * @param makeMap If true then a new empty Map will be made for you if the     *                current Map is null; if false you should be prepared to     *                receive a null Map.     *      * @return Map The current extras map.     */    public final Bundle getResultExtras(boolean makeMap) {        if (mPendingResult == null) {            return null;        }        Bundle e = mPendingResult.mResultExtras;        if (!makeMap) return e;        if (e == null) mPendingResult.mResultExtras = e = new Bundle();        return e;    }

三、本地广播。
在21版的Support v4包中新增的本地广播,也就是LocalBroadCastManager。之前广播都是全局的,所有应用程序都可以接受到,这样就会带来安全隐患。LocalBroadCastManager使得广播只在进程内传播。用法其实很多简单。
主要使用4个方法

注册Receiver:
LocalBroadCastManager.getInstance(context).registerReceiver(receiver,intentFilter);
注销Receiver:
LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver)
发送异步广播:
LocalBroadcastManager.getInstance(context).sendBroadcast(new Intent(HELLO_ACTION);
发送同步广播:
LocalBroadcastManager.getInstance(context).sendBroadcastSync(new Intent());

本地广播与普通广播只是操作类不一样,其他接口基本都类似,因此,替换为本地广播的成本相对较低。为了程序安全,建议在不需要其他进程接受广播的情况下使用本地广播。

四、Sticky广播
sticky广播通过Context.sendStickBroadcast()函数来发送,用此函数发送的广播一直滞留,当有匹配此广播的广播接收器被注册后,该广播接收器会收到此条广播。使用此函数发送广播时,需要获得BROADCAST_STICKY权限

 <uses-permission android:name="android.permission.BROADCAST_STICKY"></uses-permission>

sendStickBroadcast只保留最后一条广播,并且一直保留下去,这样即使已经有广播接收器处理该广播,当再有匹配的广播被注册,此广播仍会被接收。如果你只想处理一遍该广播,可以通过removeStickBroadcast()函数实现。

0 0