Android 四大组件(四)BroadcastReceiver

版权声明:本文出自朋永的博客,转载必须注明出处。 https://blog.csdn.net/VNanyesheshou/article/details/75449100

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

Andorid四大组件Activity、Service、ContentProvider都已经总结了,详情可以参考如下:
Android 四大组件(一)Activity
Android 四大组件(二)Service
Android 四大组件(三)ContentProvider
这篇说四大组件中的最后一个BroadcastReceiver。


广播接收者

BroadcastReceiver,”广播接受者”的意思。用来接收系统、应用的广播。
该组件应用非常广泛,许多地方都有用到,比如:wifi的连接断开,系统会发送广播,广播接受者可以获取wifi的连接状态;电量变化也会发送广播,通过广播接受者监听电量的变化。

创建BroadcastReceiver。

BroadcastReceiver是抽象类,所以使用它需要继承BroadcastReceiver,并实现其抽象方法onReceive()。

package com.zpengyong.receiver;  

import android.content.BroadcastReceiver;  
import android.content.Context;  
import android.content.Intent;  
import android.util.Log;  

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

} 

当接收到广播,系统会回调onReceive方法,通过参数intent可以获取其携带的数据。创建好广播接收者,还需要进行注册,否则不会接收到广播。

注册

BroadcastReceiver注册方法分为两种:

1.静态注册
在AndroidManifest.xml文件中注册。这种方式和应用是否可见没有关系,收到广播就可以运行。intent-filter用来指定接收的广播。

<receiver android:name=".MyBroadcastReceiver">  
    <intent-filter>  
        <action android:name="android.intent.action.zpengyong"/>  
        <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

2.动态注册
通常在代码中进行注册。在注册之后就可以接受指定的广播了。

MyBroadcastReceiver mReceiver = new MyBroadcastReceiver();          
IntentFilter filter = new IntentFilter();  
filter.addAction("android.intent.action.zpengyong");  

registerReceiver(mReceiver, filter); 

动态注册一般是在Activity和Service中进行注册(当然也可以通过context在普通类里面注册),既然register了,就需要unregister。在Activity、Service销毁前,应及时取消注册,否则会报异常如下所示:

Activity com.zpengyong.receiver.Mainactivity has leaked IntentReceiver ...BroadcastReceiver,that was originally register here.
Are you misssing a call to unregisterReceiver()?

取消注册方法如下:

@Override  
protected void onDestroy() {  
    super.onDestroy();  
    unregisterReceiver(mReceiver);  
} 

两种注册方式的区别
1. 静态注册:
常驻型、不受组件生命周期的影响,应用程序关闭后,接收到广播,依然可以运行。
2. 动态注册
非常驻、受Activity、Service生命周期的影响,在其生命周期结束前,必须移除广播接收者。

现在的广播接收器就可以接收广播了。


发送广播

发送广播有两种方式:

  • sendBroadcast 普通广播
  • sendOrderedBroadcast 有序广播

普通广播

普通广播的发送方式如下:

Intent intent = new Intent("android.intent.action.zpengyong");
sendBroadcast(intent);

发送普通广播,对于多个注册该action的广播,都能一块接收到,并没有接收的先后顺序。由于是一同接收到的,所以一个接收者是没有办法阻止另一个接收者接收这个广播的。

有序广播

有序广播的发送方式如下:

Intent intent = new Intent("android.intent.action.zpengyong");
intent.putExtra("msg", "hello");
sendOrderedBroadcast(intent, null);

发送有序广播,多个广播接收者,按顺序接收广播,高优先级的先收到,然后是低优先级的。优先级从-1000~1000,数越大,优先级越高。

不同优先级

清单文件如下所示:

<receiver android:name=".MyBroadcastReceiver">  
    <intent-filter android:priority="10">  
      <action android:name="android.intent.action.zpengyong"/>  
      <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

<receiver android:name=".SecondReceiver">  
    <intent-filter android:priority="100">  
      <action android:name="android.intent.action.zpengyong"/>  
      <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

两个广播接收者
MyBroadcastReceiver代码如下:

public class MyBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i(TAG, "action="+action);
        String msg = intent.getStringExtra("msg");
        Log.i(TAG, "msg="+msg);

        //接收通过setResultExtras传过来的msg  
        String result = getResultExtras(true).getString("msg");    
        Log.i(TAG, "result:" + result);
    }
}

SecondReceiver代码如下:

public class SecondReceiver extends BroadcastReceiver {
    private static final String TAG = "SecondReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i(TAG, "action="+action);
        String msg = intent.getStringExtra("msg");
        Log.i(TAG, "msg="+msg);

        //向低优先级的广播接收者发送消息 
        Bundle bundle = new Bundle();    
        bundle.putString("msg", "haha");    
        setResultExtras(bundle); 
    }
}

接收有序广播打印:
优先级不同
SecondReceiver优先级为100,MyBroadcastReceiver优先级为10,这说明优先级高的先接收广播,然后是优先级低的。优先级高的广播可以通过setResultExtras向优先级低的传递数据,但不会更改intent中携带的数据。

高优先级的BroadcastReceiver调用abortBroadcast();可以阻止低优先级的BroadcastReceiver接收广播。

相同优先级

对于相同优先级(priority)的BroadcastReceiver,有序广播的接收顺序是如何呢?
清单文件注册两个BroadcastReceiver,使用默认优先级

<receiver android:name=".MyBroadcastReceiver">  
    <intent-filter>  
          <action android:name="android.intent.action.zpengyong"/>  
          <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

<receiver android:name=".SecondReceiver">  
    <intent-filter>  
          <action android:name="android.intent.action.zpengyong"/>  
          <category android:name="android.intent.category.DEFAULT" />  
    </intent-filter>  
</receiver>

两个广播接收者
MyBroadcastReceiver代码如下:

public class MyBroadcastReceiver extends BroadcastReceiver {
    private static final String TAG = "MyBroadcastReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i(TAG, "action="+action);
        String msg = intent.getStringExtra("msg");
        Log.i(TAG, "msg="+msg);
    }
}

SecondReceiver代码如下:

public class SecondReceiver extends BroadcastReceiver {
    private static final String TAG = "SecondReceiver";
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        Log.i(TAG, "action="+action);
        String msg = intent.getStringExtra("msg");
        Log.i(TAG, "msg="+msg); 
    }
}

接收到有序广播的打印如下:
相同优先级

如上是两个BroadcastReceiver是使用默认优先级,如果AndroidManifest.xml中显示的设置相同的优先级,效果和上图一样。
这里猜想相同优先级的BroadcastReceiver接收顺序和清单文件中注册的先后顺序有关系。
更改AndroidManifest.xml中两个BroadcastReceiver的顺序。接收顺序确实有变化,打印如下:
相同优先级
这样就是证明了我的猜测是争取的,对于相同优先级的BroadcastReceiver,先注册的先接收到有序广播。如果在先注册的BroadcastReceiver中调用abortBroadcast(),也是会起作用,导致后面的接收不到广播。

sendOrderedBroadcast(Intent intent, String receiverPermission)方法中的第二个参数用来设置接收者是否需要申请权限。如果参数为null,则接收者不需要申请权限就可以接收广播。如果不为空则需要申请权限,否则接收不到广播。
发送广播

Intent intent = new Intent("android.intent.action.zpengyong");
intent.putExtra("msg", "hello");
sendOrderedBroadcast(intent, "zpengyong.permission.broadcast");

接收者申请权限方式:

//定义权限
<permission android:protectionLevel="normal"   
                android:name="zpengyong.permission.broadcast"/>
//声明使用该权限
<uses-permission android:name="zpengyong.permission.broadcast" />

生命周期

BroadcastReceiver对象仅对调用onReceive()的持续时间有效。一旦您的代码从此函数返回,系统会将该对象视为完成并且不再处于活跃状态。
这对于在onReceive()实现中可以做什么有重要的影响:任何需要异步操作的事情都不可用,因为您需要从函数返回以处理异步操作,但是在这一点上BroadcastReceiver是不再活跃的,因此系统可以在异步操作完成之前自由地终止其进程。
特别地,您可能不会在BroadcastReceiver内显示对话框或绑定到服务。对于前者,您应该使用{android.app.NotificationManager} API。对于后者,您可以使用{android.content.Context#startService Context.startService()}向服务发送命令。

当前正在执行BroadcastReceiver(即当前正在运行其onReceive()方法)的进程被认为是一个前台进程,除非是极端内存压力的情况,否则系统将继续运行该进程。
从onReceive()返回后,BroadcastReceiver不再处于活动状态,其进程与其中运行的任何其他应用程序组件一样重要。这一点尤为重要,因为如果这个进程只保持BroadcastReceiver(一个常见的例子,就是用户从来没有或最近没有交互过的应用程序),那么在从onReceive()返回时,系统会把它看成是空的进程,所以资源可用于其他更重要的流程。这意味着对于长时间运行的操作,应经常将{@link android.app.Service}与BroadcastReceiver结合使用,以便在整个操作过程中保持进程的活动状态。


总结

通过广播接收者可以在同一进程中使用,也可以在进程间使用。这也是进程间通信的一种方式。但是对于同一进程推荐使用LocalBroadcastManager
至此广播接收者就总结完成了。


欢迎大家关注、评论、点赞
你们的支持是我坚持的动力。

我新申请的简书

猜你喜欢

转载自blog.csdn.net/VNanyesheshou/article/details/75449100