本地广播

使用本地广播可以避免广播被其他任何应用程序接收到,同时广播接收器也只能接收来自本应发出的广播,这样就可以避免其他应用程序广播的污染了。

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView((R.layout.first_layout));
    
    localBroadcastManager = LocalBroadcastManager.getInstance(Main2Activity.this);
    rece = new BootCompleteReceiver();
    IntentFilter iF = new IntentFilter();
    iF.addAction("group.chicai.study.JJJ");
    localBroadcastManager.registerReceiver(rece,iF);

    Button button9 = (Button)findViewById(R.id.button9);
    button9.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent("group.chicai.study.JJJ");
            localBroadcastManager.sendBroadcast(intent);
        }
    });
}

protected void onDestroy() {
    super.onDestroy();
    localBroadcastManager.unregisterReceiver(rece);
}


public class BootCompleteReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Toast.makeText(context,"啦啦啦空间啊沙发哈会计法哈克金凤凰",Toast.LENGTH_LONG).show();
    }
}

首页 我的博客
粤ICP备17103704号