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

一时失言乱红尘 2022-08-09 02:28 373阅读 0赞

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

理论知识:

什么是BroadcastReceiver

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

注册BroadcastReceiver的方式

1.静态注册

静态注册方式是在AndroidManifest.xml的application里面定义receiver并设置要接收的action。

静态注册方式的特点:不管该应用程序是否处于活动状态,都会进行监听。

  1. <receiver android:name="MyReceiver">
  2. <intent-filter>
  3. <action android:name="android.MyReceiver.action"/>
  4. </intent-filter>
  5. </receiver>

其中,MyReceiver为继承BroadcastReceiver的类,重写了onReceiver方法,并在onReceiver方法中对广播进行处理。标签设置过滤器,接收指定action广播。

2.动态注册

动态注册方式在activity里面调用函数来注册,和静态的内容差不多。一个形参是receiver,另一个是IntentFilter,其中里面是要接收的action。

动态注册方式特点:在代码中进行注册后,当应用程序关闭后,就不再进行监听。

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

发送广播的方式
无序方式

  1. // 指定广播目标Action
  2. Intent intent = new Intent("MyReceiver_Action");
  3. // 可通过Intent携带消息
  4. intent.putExtra("msg", "发送广播");
  5. // 发送广播消息
  6. sendBroadcast(intent);

有序方式

  1. /**
  2. * intent The Intent to broadcast; all receivers matching this
  3. * Intent will receive the broadcast.
  4. * receiverPermission (optional) String naming a permissions that a receiver must
  5. * hold in order to receive your broadcast. If null, no permission is required.
  6. */
  7. sendBroadcast(intent, receiverPermission);
  8. /**
  9. * intent The Intent to broadcast; all receivers matching this
  10. * Intent will receive the broadcast.
  11. * receiverPermission (optional) String naming a permissions that a receiver must
  12. * hold in order to receive your broadcast. If null, no permission is required.
  13. * resultReceiver Your own BroadcastReceiver to treat as the final receiver of the broadcast.
  14. * scheduler A custom Handler with which to schedule the resultReceiver callback;
  15. * if null it will be scheduled in the Context's main thread.
  16. * initialCode An initial value for the result code. Often Activity.RESULT_OK.
  17. * initialData An initial value for the result data. Often null.
  18. * initialExtras An initial value for the result extras. Often null.
  19. */
  20. sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler, initialCode, initialData, initialExtras);

注意第三个参数:最终广播的接受者(这个接受者一定会接受到广播)

注销BroadcastReceiver

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

注:

1.一般在onStart中注册BroadcastReceiver,在onStop中取消BroadcastReceiver。

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

实例:

  1. // 定义action常量
  2. protected static final String ACTION = "com.android.broadcast.RECEIVER_ACTIONS";
  3. // 定义Button对象
  4. private Button btnBroadcast;
  5. @Override
  6. protected void onCreate(Bundle savedInstanceState) {
  7. super.onCreate(savedInstanceState);
  8. setContentView(R.layout.activity_main);
  9. btnBroadcast = (Button) findViewById(R.id.btnBroadcast);
  10. // 为按钮设置单击监听器
  11. btnBroadcast.setOnClickListener(new Button.OnClickListener() {
  12. @Override
  13. public void onClick(View v) {
  14. // 实例化Intent
  15. Intent intent = new Intent();
  16. // 设置Intent的action属性
  17. intent.setAction(ACTION);
  18. // 发出广播
  19. sendBroadcast(intent);
  20. }
  21. });
  22. }
  23. public class MyReceiver extends BroadcastReceiver {
  24. //定义日志标签
  25. private static final String TAG = "Test";
  26. @Override
  27. public void onReceive(Context context, Intent intent) {
  28. // TODO 自动生成的方法存根
  29. Log.i(TAG, "MyReceiver onReceive--->");
  30. Toast.makeText(context, "恩啦,我收到广播啦!!!", 0).show();
  31. }
  32. }

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

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

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

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

BaseActivity

  1. import android.app.Activity;
  2. import android.content.BroadcastReceiver;
  3. import android.content.Context;
  4. import android.content.Intent;
  5. import android.content.IntentFilter;
  6. import android.os.Bundle;
  7. /**
  8. *
  9. * @author Junguang_Gao
  10. * 这个类是一个基类,主要实现的是监听事件,监听退出的事件
  11. */
  12. public abstract class BaseActivity extends Activity {
  13. /**
  14. * 退出事件监听
  15. *
  16. */
  17. private ExitListenerReceiver exit=null;
  18. @Override
  19. protected void onCreate(Bundle savedInstanceState) {
  20. super.onCreate(savedInstanceState);
  21. regListener();
  22. }
  23. /**
  24. * 注册退出监听事件
  25. * @author Junguang_Gao
  26. *
  27. */
  28. public void regListener(){
  29. exit=new ExitListenerReceiver();
  30. //动态注册一个广播
  31. IntentFilter filter=new IntentFilter();
  32. filter.addAction(this.getPackageName()+".ExitListenerReceiver");
  33. registerReceiver(exit, filter);
  34. }
  35. /**
  36. * 取消注册事件
  37. */
  38. public void unregListener(){
  39. if(exit!=null){
  40. unregisterReceiver(exit);
  41. exit=null;
  42. }
  43. }
  44. /**
  45. * 退出的广播,用于关闭activity
  46. * @author Junguang_Gao
  47. *
  48. */
  49. private class ExitListenerReceiver extends BroadcastReceiver{
  50. @Override
  51. public void onReceive(Context context, Intent intent) {
  52. ((Activity)context).finish();
  53. }
  54. }
  55. @Override
  56. protected void onDestroy() {
  57. super.onDestroy();
  58. unregListener();
  59. }
  60. }

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

  1. @Override
  2. public void onClick(View v) {
  3. Intent intent = new Intent(getPackageName()+ ".ExitListenerReceiver");
  4. sendBroadcast(intent);
  5. }

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

发表评论

表情:
评论列表 (有 0 条评论,373人围观)

还没有评论,来说两句吧...

相关阅读

    相关 Android广播BroadcastReceiver

    Android 系统里定义了各种各样的广播,如电池的使用状态,电话的接收和短信的接收,开机启动都会产生一个广播。当然用户也可以自定义自己的广播。 既然说到广播,那么必定有一个