(4.1.5.1)App内广播LocalBroadcastManager局部通知管理器

本文介绍Android Support包中的LocalBroadcastManager工具,它用于同一应用内部组件间的广播通信。使用该工具可以增强应用程序的安全性和效率,避免隐私数据泄露,并阻止外部应用干扰。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LocalBroadcastManagerAndroid Support包提供了一个工具,是用来在同一个应用内的不同组件间发送Broadcast的。

使用LocalBroadcastManager有如下好处:

  • 发送的广播只会在自己App内传播,不会泄露给其他App,确保隐私数据不会泄露
  • 其他App也无法向你的App发送该广播,不用担心其他App会来搞破坏
  • 比系统全局广播更加高效

和系统广播使用方式类似:

  • 先获取实例
  • 然后通过函数 registerReceiver来注册监听器
  • 通过 sendBroadcast 函数来发送广播
LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);

lbm.registerReceiver(new BroadcastReceiver() {  
        @Override  
        public void onReceive(Context context, Intent intent) {  
        // TODO Handle the received local broadcast  
        }  
    }, new IntentFilter(LOCAL_ACTION));  
  



lbm.sendBroadcast(new Intent(LOCAL_ACTION));  



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

 

示例

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;
        }
    }
}

 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值