Android LocalBroadcastManager与BroadcastReceiver

在Android系统中,BroadcastReceiver的设计初衷就是从全局考虑的,可以方便应用程序和系统、应用程序之间、应用程序内的通信,所以对单个应用程序而言BroadcastReceiver是存在安全性问题的,相应问题及解决如下:

1、当应用程序发送某个广播时系统会将发送的Intent与系统中所有注册的BroadcastReceiver的IntentFilter进行匹配,若匹配成功则执行相应的onReceive函数。可以通过类似sendBroadcast(Intent, String)的接口在发送广播时指定接收者必须具备的permission。或通过Intent.setPackage设置广播仅对某个程序有效。

2. 当应用程序注册了某个广播时,即便设置了IntentFilter还是会接收到来自其他应用程序的广播进行匹配判断。对于动态注册的广播可以通过类似registerReceiver(BroadcastReceiver, IntentFilter, String, android.os.Handler)的接口指定发送者必须具备的permission,对于静态注册的广播可以通过android:exported="false"属性表示接收者对外部应用程序不可用,即不接受来自外部的广播。

上面两个问题其实都可以通过LocalBroadcastManager来解决:

Android v4 兼容包提供android.support.v4.content.LocalBroadcastManager工具类,帮助大家在自己的进程内进行局部广播发送与注册,使用它比直接通过sendBroadcast(Intent)发送系统全局广播有以下几点好处。

1 因广播数据在本应用范围内传播,你不用担心隐私数据泄露的问题。

2 不用担心别的应用伪造广播,造成安全隐患。

3 相比在系统内发送全局广播,它更高效。


它的用法跟BroadcaseReceiver一样

public class LocalServiceBroadcasterActivity extends Activity {
    static final String ACTION_STARTED = "com.example.android.supportv4.STARTED";
    static final String ACTION_UPDATE = "com.example.android.supportv4.UPDATE";
    static final String ACTION_STOPPED = "com.example.android.supportv4.STOPPED";
 
    LocalBroadcastManager mLocalBroadcastManager;
    BroadcastReceiver mReceiver;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        setContentView(R.layout.main);
 
        final TextView callbackData = (TextView) findViewById(R.id.callback);
        callbackData.setText("No broadcast received yet");
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
 
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_STARTED);
        filter.addAction(ACTION_UPDATE);
        filter.addAction(ACTION_STOPPED);
         
        mReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(ACTION_STARTED)) {
                    callbackData.setText("STARTED");
                } else if (intent.getAction().equals(ACTION_UPDATE)) {
                    callbackData.setText("Got update: " + intent.getIntExtra("value", 0));
                } else if (intent.getAction().equals(ACTION_STOPPED)) {
                    callbackData.setText("STOPPED");
                }
            }
        };
        mLocalBroadcastManager.registerReceiver(mReceiver, filter);
 
         
        Button button = (Button) findViewById(R.id.start);
        button.setOnClickListener(mStartListener);
        button = (Button) findViewById(R.id.stop);
        button.setOnClickListener(mStopListener);
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocalBroadcastManager.unregisterReceiver(mReceiver);
    }
 
    private OnClickListener mStartListener = new OnClickListener() {
        public void onClick(View v) {
            startService(new Intent(LocalServiceBroadcasterActivity.this, LocalService.class));
        }
    };
 
    private OnClickListener mStopListener = new OnClickListener() {
        public void onClick(View v) {
            stopService(new Intent(LocalServiceBroadcasterActivity.this, LocalService.class));
        }
    };
 
    public static class LocalService extends Service {
        LocalBroadcastManager mLocalBroadcastManager;
        int mCurUpdate;
 
        static final int MSG_UPDATE = 1;
 
        Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MSG_UPDATE: {
                    mCurUpdate++;
                    Intent intent = new Intent(ACTION_UPDATE);
                    intent.putExtra("value", mCurUpdate);
                    mLocalBroadcastManager.sendBroadcast(intent);
                    Message nmsg = mHandler.obtainMessage(MSG_UPDATE);
                    mHandler.sendMessageDelayed(nmsg, 1000);
                }
                    break;
                default:
                    super.handleMessage(msg);
                }
            }
        };
 
        @Override
        public void onCreate() {
            super.onCreate();
            mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        }
 
        public int onStartCommand(Intent intent, int flags, int startId) {
            // Tell any local interested parties about the start.
            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STARTED));
 
            // Prepare to do update reports.
            mHandler.removeMessages(MSG_UPDATE);
            Message msg = mHandler.obtainMessage(MSG_UPDATE);
            mHandler.sendMessageDelayed(msg, 1000);
            return ServiceCompat.START_STICKY;
        }
 
        @Override
        public void onDestroy() {
            super.onDestroy();
 
            // Tell any local interested parties about the stop.
            mLocalBroadcastManager.sendBroadcast(new Intent(ACTION_STOPPED));
 
            // Stop doing updates.
            mHandler.removeMessages(MSG_UPDATE);
        }
 
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    }
}

源码解析可以看 Android编程之LocalBroadcastManager源码详解

你可能感兴趣的:(android)