一、静态注册:在AndroidManifest.xml中用标签生命注册,并在标签内用标签设置过滤器。
1、Manifest.xml文件中application节点中添加
<!-- 继承BroadcastReceiver,重写onReceiver方法 -->
<receiver android:enabled="true" android:name=".myBroadcastReceiver">
<intent-filter>
<!-- 使用过滤器,接收指定action广播 -->
<action android:name="cbl.action">
</action>
</intent-filter>
</receiver>
2、发送广播
Intent intent = new Intent("cbl.action");
intent.putExtra("name", "cbl");
//发送广播,附带更新后的数据
sendBroadcast(intent);
2、Activity中创建广播接收器的类文件(仅创建接收器对象,经测试不可行,未继续研究)
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getIntExtra("name", 0);
counterText.setText(name); //TextView显示接收到的字符串
}
}
二、动态注册:
1、发送广播
Intent intent = new Intent("cbl.action");
intent.putExtra("name", "cbl");
//发送广播,附带更新后的数据
sendBroadcast(intent);
2、Activity中创建广播接收器
//创建广播接收器
private BroadcastReceiver counterActionReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
String name = intent.getIntExtra("name", 0);
counterText.setText(name); //TextView显示接收到的字符串
}
};
3、Activity注册广播
一般:在onStart中注册,onStop中取消unregisterReceiver
//注册广播
@Override
public void onResume() {
super.onResume();
//注册广播接收器
IntentFilter myFilter = new IntentFilter();
myFilter.addAction("cbl.action");
registerReceiver(counterActionReceiver, myFilter);
}
//取消注册
@Override
public void onPause() {
super.onPause();
unregisterReceiver(counterActionReceiver);
}
1、Manifest.xml文件中application节点中添加
<!-- 继承BroadcastReceiver,重写onReceiver方法 -->
<receiver android:enabled="true" android:name=".myBroadcastReceiver">
<intent-filter>
<!-- 使用过滤器,接收指定action广播 -->
<action android:name="cbl.action">
</action>
</intent-filter>
</receiver>
2、发送广播
Intent intent = new Intent("cbl.action");
intent.putExtra("name", "cbl");
//发送广播,附带更新后的数据
sendBroadcast(intent);
2、Activity中创建广播接收器的类文件(仅创建接收器对象,经测试不可行,未继续研究)
public class myBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String name = intent.getIntExtra("name", 0);
counterText.setText(name); //TextView显示接收到的字符串
}
}
二、动态注册:
1、发送广播
Intent intent = new Intent("cbl.action");
intent.putExtra("name", "cbl");
//发送广播,附带更新后的数据
sendBroadcast(intent);
2、Activity中创建广播接收器
//创建广播接收器
private BroadcastReceiver counterActionReceiver = new BroadcastReceiver(){
public void onReceive(Context context, Intent intent) {
String name = intent.getIntExtra("name", 0);
counterText.setText(name); //TextView显示接收到的字符串
}
};
3、Activity注册广播
一般:在onStart中注册,onStop中取消unregisterReceiver
//注册广播
@Override
public void onResume() {
super.onResume();
//注册广播接收器
IntentFilter myFilter = new IntentFilter();
myFilter.addAction("cbl.action");
registerReceiver(counterActionReceiver, myFilter);
}
//取消注册
@Override
public void onPause() {
super.onPause();
unregisterReceiver(counterActionReceiver);
}