第一行代码——第五章:详解广播机制

1.本地广播

只能接受本程序的广播,而且发出去的广播只能发给本程序的广播接收器

第一行代码——第五章:详解广播机制_第1张图片

public class MainActivity extends AppCompatActivity {

    private IntentFilter filter;
    private LocalReveiver localReveiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button = findViewById(R.id.button);
        localBroadcastManager = LocalBroadcastManager().getInstance(this);
        filter = new IntentFilter();
        filter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
        localBroadcastManager.registerReceiver(localReveiver, filter);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });
    }

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

    class LocalReveiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            Toast.makeText(context,"received local broadcast",Toast.LENGTH_SHORT).show();
        }
    }

}

动态注册内部广播的方法:

1. class LocalBroadCast 继承Broadcast 实现onReceiver方法,并新建一个localBroadCast

2. 新建一个过滤器 IntentFilter filter = new IntentFilter() ;

3. 初始化一个LocalBroadCastManager manager = LocalBroadCastManager.getInstance(this)

4. 注册广播接收者: localBroadcastManager.registerReceiver(localReveiver, filter);

5. 发送广播:

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent("com.example.broadcasttest.LOCAL_BROADCAST");
                localBroadcastManager.sendBroadcast(intent);
            }
        });

你可能感兴趣的:(android)