Android Broadcast 与 LocalBroadcastManager

测试主程序

BaseReceiver.java

package com.chy.broadcastdemo;

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

//广播接收器的生命周期只有十秒左右,如果在 onReceive() 内做超过十秒内的事情,就会报错 。
public class BaseReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println(getClass().getSimpleName() + " : " + intent.getAction());
        // 如果不是OrderedBroadcast,调用abortBroadcast()会报java.lang.RuntimeException: BroadcastReceiver trying to return result during a non-ordered broadcast
        if (isOrderedBroadcast()) {
            // 这个方法可以截获由 sendOrderedBroadcast () 发送来的 广播,让其它广播接收者无法收到这个广播。
            //abortBroadcast();
            //System.out.println("getAbortBroadcast() = " + getAbortBroadcast());
            // 这个方法是针对上面的 abortBroadcast() 方法的,用于取消截获广播。这样它的下一级广播接收者就能够收到该广播了。
            //clearAbortBroadcast();
        }
//      try {
            //这里添加上休眠是为了方便查看同步情况下的按钮状态,如果正常情况在接收器要执行耗时操作请新建线程
            //Skipped 360 frames!  The application may be doing too much work on its main thread.
//          Thread.sleep(2000);
//      } catch (InterruptedException e) {
//          e.printStackTrace();
//      }
        System.out.println(getClass().getSimpleName() + " : onReceive end");
    }
}

MainActivity.java

package com.chy.broadcastdemo;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

    private static final String BROADCAST_ACTION = "com.chy.Broadcast.ACTION";
    private static final String LOCAL_BROADCAST_MANAGER_ACTION = "com.chy.Local_Broadcast_Manager.ACTION";
    private static final String BROADCAST_RECV_PERMISSION = "com.chy.permission.RECV_BROADCAST";

    private Context context = this;
    private BroadcastReceiver receiver = new BaseReceiver();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button sendBroadcastBtn = (Button) findViewById(R.id.send_broadcast_btn);
        Button sendOrderBroadcastBtn = (Button) findViewById(R.id.send_order_broadcast_btn);
        Button sendOrderBroadcastWithPermissionBtn = (Button) findViewById(R.id.send_order_broadcast_with_permission_btn);
        Button localBroadcastSendBtn = (Button) findViewById(R.id.local_broadcast_send_btn);
        Button localBroadcastSendSyncBtn = (Button) findViewById(R.id.local_broadcast_send_sync_btn);
        sendBroadcastBtn.setOnClickListener(this);
        sendOrderBroadcastBtn.setOnClickListener(this);
        sendOrderBroadcastWithPermissionBtn.setOnClickListener(this);
        localBroadcastSendBtn.setOnClickListener(this);
        localBroadcastSendSyncBtn.setOnClickListener(this);

        /*
        由于安全原因,StickyBroadcast 和  StickyOrderedBroadcast 已经被 deprecated了不推荐使用,因此这里不介绍这种粘性广播了
        context.sendStickyBroadcast(intent);
        context.sendStickyOrderedBroadcast(intent, resultReceiver, scheduler, initialCode, initialData, initialExtras);
        */
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(LOCAL_BROADCAST_MANAGER_ACTION);
        LocalBroadcastManager.getInstance(context).registerReceiver(receiver, intentFilter);
    }

    @Override
    public void onClick(View v) {
        Intent intent = new Intent();
        switch(v.getId()) {
        case R.id.send_broadcast_btn:
            System.out.println("send_broadcast_btn click start");
            intent.setAction(BROADCAST_ACTION);
            /*
             * 无序广播,接收器接收到的顺序是随机的,和receiver的priority属性无关,而且广播不能被终止
             * (1)当send与receiver处于同一个进程时,所有接收器均能收到该广播
             * (2)若send与receiver处于不同进程时,如果receiver进程中声明了<permission>,并且<receiver>中添加"android:permission"属性,那么只有send进程中声明使用<uses-permission>权限,才能将广播发送给该接收器
             */
            context.sendBroadcast(intent);
            break;
        case R.id.send_order_broadcast_btn:
            System.out.println("send_order_broadcast_btn click");
            //按照接收者的优先级顺序接收广播 , 优先级别在 intent-filter 中的 priority 中声明 ,-1000 到 1000 之间 , 值越大 , 优先级越高 . 可以终止广播意图的继续传播 . 接收者可以篡改内容 .
            intent.setAction(BROADCAST_ACTION);
            context.sendOrderedBroadcast(intent, null);
            break;
        case R.id.send_order_broadcast_with_permission_btn:
            System.out.println("send_order_broadcast_with_permission_btn click");
            /*
             * 带权限的广播
             * sender需要声明该权限<permission>,receiver声明要使用该权限<uses-permission>,才能收到该广播
             * (1)当send与receiver处于同一个进程时,所有接收器均能收到该广播,无论<receiver>是否添加"android:permission"属性
             * (2)若send与receiver处于不同进程时,只有在reveiver进程的<receiver>中添加"android:permission"属性的接受器才能接收到该广播
             */
            intent.setAction(BROADCAST_ACTION);
            context.sendOrderedBroadcast(intent, BROADCAST_RECV_PERMISSION);
            break;
        case R.id.local_broadcast_send_btn:
            System.out.println("local_broadcast_send_btn click");
            //LocalBroadcastManager只能动态注册广播接收器,在AndroidManifest.xml中注册的广播接收器是收不到数据的
            //这里context不管是activity还是application,最终都会转成applicationContext
            intent.setAction(LOCAL_BROADCAST_MANAGER_ACTION);
            LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
            break;
        case R.id.local_broadcast_send_sync_btn:
            System.out.println("local_broadcast_send_sync_btn click");
            //广播事件被处理完之前当前线程会被阻塞住
            intent.setAction(LOCAL_BROADCAST_MANAGER_ACTION);
            LocalBroadcastManager.getInstance(context).sendBroadcastSync(intent);
            break;
        }
        System.out.println("click end");
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(context).unregisterReceiver(receiver);
        super.onDestroy();
    }
}

MyReceiver1.java

package com.chy.broadcastdemo;

public class MyReceiver1 extends BaseReceiver {
}

MyReceiver2.java

package com.chy.broadcastdemo;

public class MyReceiver2 extends BaseReceiver {
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.chy.broadcastdemo.MainActivity" >

    <Button
        android:id="@+id/send_broadcast_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送无序广播——sendBroadcast" />

    <Button
        android:id="@+id/send_order_broadcast_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送有序广播——sendOrderBroadcast" />

    <Button
        android:id="@+id/send_order_broadcast_with_permission_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送带权限的有序广播——sendOrderBroadcast" />

    <Button
        android:id="@+id/local_broadcast_send_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送本地广播——LocalBroadcastManager.send" />

    <Button
        android:id="@+id/local_broadcast_send_sync_btn"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="发送本地同步广播——LocalBroadcastManager.sendSync" />

</LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.chy.broadcastdemo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="23"
        android:targetSdkVersion="25" />

    <permission android:name="com.chy.permission.SEND_BROADCAST" />
    <permission android:name="com.chy.permission.RECV_BROADCAST" />

    <uses-permission android:name="com.chy.permission.SEND_BROADCAST" />
    <uses-permission android:name="com.chy.permission.RECV_BROADCAST" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="MyReceiver1" >
            <intent-filter android:priority="-1000" >
                <action android:name="com.chy.Broadcast.ACTION" />
                <action android:name="com.chy.Local_Broadcast_Manager.ACTION" />
            </intent-filter>
        </receiver>
        <receiver android:name="MyReceiver2" >
            <intent-filter android:priority="998" >
                <action android:name="com.chy.Broadcast.ACTION" />
                <action android:name="com.chy.Local_Broadcast_Manager.ACTION" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

跨进程接收器测试程序

BaseReceiver.java

package com.example.broadcastdemo2;

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

public class BaseReceiver  extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        System.out.println(getClass().getSimpleName() + " : " + intent.getAction());
    }

}

NonePermissionReceiver.java

package com.example.broadcastdemo2;

public class NonePermissionReceiver extends BaseReceiver {
}

RecvPermissionReceiver

package com.example.broadcastdemo2;

public class RecvPermissionReceiver extends BaseReceiver {
}

SendPermissionReceiver

package com.example.broadcastdemo2;

public class SendPermissionReceiver extends BaseReceiver {
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.broadcastdemo2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="23"
        android:targetSdkVersion="25" />

    <permission android:name="com.chy.permission.SEND_BROADCAST" />
    <permission android:name="com.chy.permission.RECV_BROADCAST" />

    <uses-permission android:name="com.chy.permission.RECV_BROADCAST" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver android:name="NonePermissionReceiver" >
            <intent-filter android:priority="1000" >
                <action android:name="com.chy.Broadcast.ACTION" />
                <action android:name="com.chy.Local_Broadcast_Manager.ACTION" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="RecvPermissionReceiver"
            android:permission="com.chy.permission.RECV_BROADCAST" >
            <intent-filter android:priority="999" >
                <action android:name="com.chy.Broadcast.ACTION" />
                <action android:name="com.chy.Local_Broadcast_Manager.ACTION" />
            </intent-filter>
        </receiver>
        <receiver
            android:name="SendPermissionReceiver"
            android:permission="com.chy.permission.SEND_BROADCAST" >
            <intent-filter android:priority="999" >
                <action android:name="com.chy.Broadcast.ACTION" />
                <action android:name="com.chy.Local_Broadcast_Manager.ACTION" />
            </intent-filter>
        </receiver>
    </application>

</manifest>

运行截图

  • 发送无序广播
    这里写图片描述
  • 发送有序广播
    这里写图片描述
  • 发送带权限广播
    这里写图片描述
  • 发送本地广播
    异步传递,且仅动态注册到LocalBroadcastManager的接收器能收到广播。
    这里写图片描述
  • 发送本地同步广播
    阻塞传递,且仅动态注册到LocalBroadcastManager的接收器能收到广播。
    这里写图片描述

注意点:

  • 只要有使用到该自定义权限,都必须在AndroidManifest.xml的<permission>中进行声明。
  • 需要的权限在<uses-permission>中声明,无论是android权限还是自定义权限。

推荐以下博客

《Android Broadcast 和 BroadcastReceiver的权限限制》
http://blog.youkuaiyun.com/javensun/article/details/7334230

2点疑惑

  • 首先,注册到receiver中的权限貌似没啥用,从以上例子可以看出即使sendBroadcast中设定了权限。然后接收程序中只要添加相应的<uses-permission>,那么所有接收器都可以收到广播,无论<receiver>是否具有”permission”属性?
  • 其次对广播设置权限到底有什么用?只要反编译出AndroidManifest.xml所声明的权限就暴露无遗。即使说把权限设置为dangerous在安装时提示也是扯淡。至于要说安全,还是改用LocalBroadcastManager得了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值