我在使用/理解BroadcastReceivers和IntentFilters时遇到困难。我的测试活动中有以下代码。测试活动包含一个 .addProximityAlert,如果触发了 .addProximityAlert,我想广播到 Test2 接收器。测试时出现错误。我做错了什么?
测试活动:
public class Test extends BroadcastReceiver
{
LocationManager lm;
...
@Override
public void onReceive(Context context, Intent intent)
{
...
final String PROX_ALERT_INTENT = "com.example.proxalert.Test2";
Intent alert = new Intent(PROX_ALERT_INTENT);
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, 0, alert, 0);
lm.addProximityAlert(latitude, longitude, radius, expiration, proximityIntent);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
context.registerReceiver(new Test2(), filter);
测试2 接收器:
public class Test2 extends BroadcastReceiver {
@Override
public void onReceive(Context arg0, Intent arg1) {
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = arg1.getBooleanExtra(key, false);
if (entering) {
//toast notification "welcome"
}
...
测试扩展了 BroadCast 接收器,因此必须通知广播才能激活。你确定这就是你想做的吗?
这真的是一个测试吗?我不这么认为。因此,如果您只是该代码可以删除 Test 类,请创建一个带有按钮的活动,并在单击按钮时在 Test 中执行您的代码。
使用广播接收器和意图过滤器在您的活动(或服务)下喜欢这个:
broadcastReceiver = new BroadcastReceiver() {//global BroadcastReceiver
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
//Action receive
};
意图过滤器 :
IntentFilter intentfilterTime = new IntentFilter();
intentfilterTime.addAction(Intent.ACTION_BATTERY_CHANGED);//receive battery level change
registerReceiver(broadcastReceiver, intentfilterTime);
添加要接收的所有操作。您的代码不起作用,因为您在另一个广播中使用广播,我认为这不是您想要的。
您可以简单地同时注册两个 BroadcastReceiver 并控制启用,通过简单的方法禁用它们,例如
- 使用静态/非静态布尔变量
- 使用首选项保存键值对
例如:
public class Test extends BroadcastReceiver
{
LocationManager lm;
...
@Override
public void onReceive(Context context, Intent intent)
{
...
final String PROX_ALERT_INTENT = "com.example.proxalert.Test2";
Intent alert = new Intent(PROX_ALERT_INTENT);
PendingIntent proximityIntent = PendingIntent.getBroadcast(context, 0, alert, 0);
lm.addProximityAlert(latitude, longitude, radius, expiration, proximityIntent);
IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
Test2.someStaticVariable = true;
public class Test2 extends BroadcastReceiver {
public static boolean someStaticVariable;
@Override
public void onReceive(Context arg0, Intent arg1) {
if (!someStaticVariable){
return;
}
String key = LocationManager.KEY_PROXIMITY_ENTERING;
Boolean entering = arg1.getBooleanExtra(key, false);
if (entering) {
//toast notification "welcome"
}
...
我能够通过在 android 清单中注册接收器来让它工作,而不是尝试在 test1 中动态注册接收器。 这个网站真的很有帮助:
http://www.techotopia.com/index.php/Android_Broadcast_Intents_and_Broadcast_Receivers