android----广播(BroadcastReceiver)的用法

来源:互联网 发布:beat制作软件 编辑:程序博客网 时间:2024/05/29 17:43

之前学习过广播(BroadcastReceiver),但是只是大概了解,并不清楚具体的用法,现在总结一下BroadcastReceiver的用法。


理论知识:

什么是BroadcastReceiver

BroadcastReceiver(广播接收器)是为了实现系统广播而提供的一种组件,并且广播事件处理机制是系统级别的。


注册BroadcastReceiver的方式

1.静态注册
静态注册方式是在AndroidManifest.xml的application里面定义receiver并设置要接收的action。
静态注册方式的特点:不管该应用程序是否处于活动状态,都会进行监听。
<receiver android:name="MyReceiver">    <intent-filter>         <action android:name="android.MyReceiver.action"/>    </intent-filter></receiver>
其中,MyReceiver为继承BroadcastReceiver的类,重写了onReceiver方法,并在onReceiver方法中对广播进行处理。<intent-filter>标签设置过滤器,接收指定action广播。


2.动态注册
动态注册方式在activity里面调用函数来注册,和静态的内容差不多。一个形参是receiver,另一个是IntentFilter,其中里面是要接收的action。
动态注册方式特点:在代码中进行注册后,当应用程序关闭后,就不再进行监听。

MyReceiver receiver = new MyReceiver();//创建过滤器,并指定action,使之用于接收同action的广播IntentFilter filter = new IntentFilter("MyReceiver_Action");//注册广播接收器registerReceiver(receiver, filter); 


发送广播的方式
无序方式
// 指定广播目标ActionIntent intent = new Intent("MyReceiver_Action");// 可通过Intent携带消息intent.putExtra("msg", "发送广播");// 发送广播消息sendBroadcast(intent);

有序方式
/** * intent  The Intent to broadcast; all receivers matching this  *         Intent will receive the broadcast. * receiverPermission (optional) String naming a permissions that a receiver must *         hold in order to receive your broadcast. If null, no permission is required. */sendBroadcast(intent, receiverPermission);
/*** intent The Intent to broadcast; all receivers matching this*        Intent will receive the broadcast. * receiverPermission (optional) String naming a permissions that a receiver must*        hold in order to receive your broadcast. If null, no permission is required. * resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast. * scheduler A custom Handler with which to schedule the resultReceiver callback; *       if null it will be scheduled in the Context's main thread. * initialCode An initial value for the result code. Often Activity.RESULT_OK. * initialData An initial value for the result data. Often null. * initialExtras An initial value for the result extras. Often null.*/sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);
注意第三个参数:最终广播的接受者(这个接受者一定会接受到广播)


注销BroadcastReceiver

//注销广播接收器unregisterReceiver(receiver);

注:
1.一般在onStart中注册BroadcastReceiver,在onStop中取消BroadcastReceiver。
2.一个BroadcastReceiver 对象只有在被调用onReceive(Context, Intent)时才有效,当从该函数返回后,该对象就无效的了,结束生命周期。

实例:

// 定义action常量protected static final String ACTION = "com.android.broadcast.RECEIVER_ACTIONS";// 定义Button对象private Button btnBroadcast;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    btnBroadcast = (Button) findViewById(R.id.btnBroadcast);// 为按钮设置单击监听器btnBroadcast.setOnClickListener(new Button.OnClickListener() {@Overridepublic void onClick(View v) {// 实例化IntentIntent intent = new Intent();// 设置Intent的action属性intent.setAction(ACTION);// 发出广播sendBroadcast(intent);}});}
public class MyReceiver extends BroadcastReceiver {//定义日志标签     private static final String TAG = "Test"; @Overridepublic void onReceive(Context context, Intent intent) {// TODO 自动生成的方法存根Log.i(TAG, "MyReceiver onReceive--->"); Toast.makeText(context, "恩啦,我收到广播啦!!!", 0).show();}}

从上面的例子可以看出,发送一个广播一般都是在onClick方法(即通过点击按钮的方式)中发送的。

我(Android菜鸟)所了解到的广播在项目中的应用:

例如,在一个项目中有很多的activity,当用户退出这个应用或者是打开其他的activity,若没有及时关闭那些没有用的activity,这就可能会造成内存不足,严重影响应用的运行效率。这时,就可用通过发送广播的方式关闭当前不用的activity。

通过实现一个抽象的BaseActivity,让每一个Activity都继承这个BaseActivity,然后在Activity中发送广播即可关闭对应的Activity。

BaseActivity

import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.os.Bundle;/** *  * @author Junguang_Gao * 这个类是一个基类,主要实现的是监听事件,监听退出的事件 */public abstract class BaseActivity extends Activity {    /**     * 退出事件监听     *      */private ExitListenerReceiver exit=null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);regListener();}/** * 注册退出监听事件 * @author Junguang_Gao * */public void regListener(){exit=new ExitListenerReceiver();//动态注册一个广播IntentFilter filter=new IntentFilter();filter.addAction(this.getPackageName()+".ExitListenerReceiver");registerReceiver(exit, filter);}/** * 取消注册事件 */public void unregListener(){if(exit!=null){unregisterReceiver(exit);exit=null;}}/** * 退出的广播,用于关闭activity * @author Junguang_Gao * */private class ExitListenerReceiver extends BroadcastReceiver{@Overridepublic void onReceive(Context context, Intent intent) {((Activity)context).finish();}} @Overrideprotected void onDestroy() {super.onDestroy();unregListener();}}

在具体的Activity中需要关闭Activity时可以调用:

@Overridepublic void onClick(View v) {     Intent intent = new Intent(getPackageName()+ ".ExitListenerReceiver");     sendBroadcast(intent);}

BroadcastReceiver在项目中的应用应该还有很多,以后会慢慢了解。




0 0
原创粉丝点击