[置顶] Android四大组件之广播接收器(三)

为了能够简单地解决广播的安全性问题,Android 引入了一套本地广播机制,使用这个机制发出的广播只能够在应用程序的内部进行传递,并且广播接收器也只能接收来自本应用程序发出的广播,这样所有的安全性问题就都不存在了。


代码示例:

public class MainActivity extends AppCompatActivity {

    private IntentFilter intentFilter;
    private LocalReceiver localReceiver;
    private LocalBroadcastManager localBroadcastManager;
    private Button localButton;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //发送本地广播
        localBroadcastManager = LocalBroadcastManager.getInstance(MainActivity.this);
        localButton = (Button)findViewById(R.id.localSend);
        localButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.horizon.localBroadcast");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
        //动态注册本地广播接收器
        intentFilter = new IntentFilter();
        intentFilter.addAction("com.horizon.localBroadcast");
        localReceiver = new LocalReceiver();
        localBroadcastManager.registerReceiver(localReceiver,intentFilter);
    }

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

    class LocalReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context, "收到本地广播!!!",
                    Toast.LENGTH_SHORT).show();
        }
    }

}

其实本地广播的发送和动态注册广播是类似的,在接收上也是通过内部类,需要注意的是本地广播无法被静态注册的接收器接收。

本地广播优势:

1. 可以明确地知道正在发送的广播不会离开我们的程序,因此不需要担心机密数据泄
漏的问题。
2. 其他的程序无法将广播发送到我们程序的内部,因此不需要担心会有安全漏洞的隐
患。
3. 发送本地广播比起发送系统全局广播将会更加高效。


你可能感兴趣的:(android,安全,Broadcast,本地广播)