Android : Broadcast

来源:互联网 发布:剑三光头捏脸数据 编辑:程序博客网 时间:2024/06/08 17:16

Broadcast是Application之间交换数据最简单的一种方法。

Broadcast组成部分

Broadcast 功能,由发送Broadcast的Sender和接收的Receiver组成。
Sendor和Receiver没有直接的联系,所以这两个部分可以在一个Application内,也可以不再一个Application内。然后可以从Broadcast字面字面意思上也可以知道,Sendor和Receiver不一定是一对一,也可以是1对N。
Broadcast的传递是用Binder传递的,其传递的数据放在Intent里边传递。

Broadcast发送

Broadcast可以使用Context class的sendBroadcast() 和 sendOrderedBroadcast() API进行发送。

Intent intent = new Intent("com.example.helloworld.TEST");intent.putExtra("number", 7);intent.putExtra("text", "hello");sendBroadcast(intent);
  1. sendBroadcast(Intent)是最为一般的发送方式。上面可以看到,Intent对象指定了Action name为com.example.helloworld.TEST。所以接收这个Broadcast的Receiver必须加上Intent-filter,其action name也必须指定为com.example.helloworld.TEST才能接收到Broadcast。
    sendBroadcast(intent, permission)和上面相同,只不过后面多了一个permission,指定接收这个Broadcast所需的权限。如果Receiver所在的Package没有指定这个permission,则收不到这个Broadcast。

  2. sendOrderedBroadcast():一般的Broadcast都是aync,所以对很多Receiver的接收顺序都不用太关心。
    Ordered Broadcast虽然也是async,但是 Intent filer指定了android:priority属性,根据android:priority来指定接收的顺序,每次只发送一个。即,前面一个Receiver的 onReceive()函数返回才会发送给下一个。接收到Ordered Broadcast的Receiver可以指定Abort flash,然后可以Set/Get Result code,data,extras等。

Broadcast接收

继承BroadcastReceiver,实现onReceiver(),然后在注册Receiver之后,就可以接收Broadcast intent。

public class HelloReceiver extends BroadcastReceiver {    public void onReceive(Context context, Intent intent) {        String action = intent.getAction();        if (action.equals("com.example.helloworld.TEST")) {            int num = intent.getIntExtra("number", -1);            String str = intent.getStringExtra("text");            Toast.makeText(context, "Broadcast : number=" + num                     + " text=" + str, Toast.LENGTH_LONG).show();        }    }}

Broadcast Receiver一般使用在manifest file里边声明的方式注册。

    <receiver android:name="com.example.helloworld.HelloReceiver">        <intent-filter>            <action android:name="com.example.helloworld.TEST" />        </intent-filter>    </receiver>

也可以使用Context class的registerReceiver(), unregisterReceiver() API的方式注册Receiver。
一个Receiver可以注册很多Intent filter,可以接收Android platform发送的ACTION_LOCALE_CHANGED或者ACTION_TIME_CHANGED等Broadcast。

注意事项

Broadcast发送的Data大小是有限制的。Broadcast是先被发送到Android platform的一个process里边的Broadcast queue,所以会发生Binder transaction。然后从Android platform发送给Receiver的过程当中也是会发生Binder transaction。所以一对一发送的Broadcast的过程当中,会发生两次的Binder transaction。

!!为了保存return值,会用到Binder transaction buffer,每个进程会分配分配这个buffer大小为1MB。
Intent会包含Extra内容但也包含其他的一些内容,所以Extra的大小不能大于1MB。而且一个Binder transaction buffer,会被一个Process内的所有Binder transaction所共享,所以发送的一个Extra小与1MB,但很多组合起来之后,其大小可能会超过1MB。这时候会有如下的log。这里13314是Sendor Process ID。

E/JavaBinder(13314): !!! FAILED BINDER TRANSACTION !!!

Android的Broadcast queue的Process因为不单单只接收我们发送的Broadcast而且还会与其他服务频繁发生Binder transaction。所以即使我们的发送给Broadcast queue成功了,但也有可能从Broadcast queue发送给Receiver的过程当中也有可能出现错误。

E/JavaBinder(690): !!! FAILED BINDER TRANSACTION !!! W/BroadcastQueue(690): Exception when sending broadcast to ComponentInfo{com.example.helloworld/com.example.helloworld.HelloReceiver} W/BroadcastQueue(690): android.os.TransactionTooLargeException W/BroadcastQueue(690):     at android.os.BinderProxy.transact(Native Method) W/BroadcastQueue(690):     at android.app.ApplicationThreadProxy.scheduleReceiver(ApplicationThreadNative.java:822) W/BroadcastQueue(690):     at com.android.server.am.BroadcastQueue.processCurBroadcastLocked(BroadcastQueue.java:236) W/BroadcastQueue(690):     at com.android.server.am.BroadcastQueue.processNextBroadcast(BroadcastQueue.java:870) W/BroadcastQueue(690):     at com.android.server.am.BroadcastQueue$1.handleMessage(BroadcastQueue.java:145) W/BroadcastQueue(690):     at android.os.Handler.dispatchMessage(Handler.java:99) W/BroadcastQueue(690):     at android.os.Looper.loop(Looper.java:137)

所以,要尽量避免通过Broadcast Intent传送接收大的数据。

Broadcast发送之后出现ANR,描述如下:
如下一个ANR,提示出现ANR的APP是com.sec.android.app.clockpackage。
原因是:MSG: Broadcast of Intent { act=android.intent.action.TIME_TICK flg=0x50000014 (has extras) }

01-08 15:05:10.606 26881 26975 E CrashAnrHandler: --------> APP NOT RESPONDING01-08 15:05:10.606 26881 26975 E CrashAnrHandler: // ANR: com.sec.android.app.clockpackage (pid 4952)01-08 15:05:10.606 26881 26975 E CrashAnrHandler: // MSG: Broadcast of Intent { act=android.intent.action.TIME_TICK flg=0x50000014 (has extras) }

当一个广播10s内还没处理完的时候,就会出现ANR。
你检查下Androidmanifest.xml里面有没有注册这个broadcast receiver, 再看看程序代码里,有没有调用registerReceiver之内的方法。

关于ANR的描述:
ANR stands for “Application not responding”. This message means that your application isn’t responsive to the user any more. Normally this exception is thrown if the UI thread is blocked by an operation which takes more than 5 seconds

0 0
原创粉丝点击