Android 广播的两种注册的方式

1.Android广播使用 , 静态广播

首先在清单文件中注册:

<receiver android:name=".MyBroadCastReceiver">
    <intent-filter>
        <action android:name="com.pateo.mybroadcast"/>
    </intent-filter>
</receiver>

写一个广播类:

public class MyBroadCastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d("zhang", "000000000");
        Toast.makeText(context, "收到广播", Toast.LENGTH_SHORT).show();
    }
}

自己发送广播:

button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        intent.setAction("com.pateo.mybroadcast");
        sendBroadcast(intent);
    }
});

运行项目可以直接测试

2.动态注册广播

先把刚才的 清单文件中广播注册都去掉:

@Override
protected void onResume() {
    super.onResume();
    // 1. 实例化BroadcastReceiver子类 &  IntentFilter
    myBroadCastReceiver = new MyBroadCastReceiver();
    // 2. 设置接收广播的类型
    IntentFilter intentFilter = new IntentFilter();
    intentFilter.addAction("com.pateo.mybroadcast");
    // 3. 动态注册:调用ContextregisterReceiver()方法
    registerReceiver(myBroadCastReceiver,intentFilter);

}

@Override
protected void onPause() {
    super.onPause();
    //销毁在onResume()方法中的广播
    unregisterReceiver(myBroadCastReceiver);
}





阅读更多

没有更多推荐了,返回首页