安卓 本地广播

注册广播

LocalBroadcastManager localBroadcastManager;
LocalReciver localReciver;
     IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction("com.example.dashitu");
        localReciver = new LocalReciver();
        localBroadcastManager = LocalBroadcastManager.getInstance(this);
        localBroadcastManager.registerReceiver(localReciver, intentFilter);

发送广播

可在点击事件中发送广播

       Intent intent = new Intent("com.example.dashitu");
                intent.setClass(MainActivity.this, MainActivity.class);
                intent.putExtra("data", "数据");
                localBroadcastManager.sendBroadcast(intent);
                startActivity(intent);

销毁广播

在用到的生命周期中销毁

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

广播接收者

public class LocalReciver extends BroadcastReceiver {
     
    private LocalBroadcastManager localBroadcastManager;
    private IntentFilter intentFilter;
    private LocalReciver localReceiver;

    @Override
    public void onReceive(Context context, Intent intent) {
     
        Toast.makeText(context, "验证成功" + intent.getStringExtra("data").toString(), Toast.LENGTH_SHORT).show();

    }
}

你可能感兴趣的:(安卓 本地广播)