我在使用/理解BroadcastReceivers和IntentFilters方面遇到了困难。我的Test活动中有以下代码。测试活动包含.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);
Test2接收者:
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"
}
...
答案 0 :(得分:2)
测试扩展了BroadCast接收器,因此必须通知广播才能被激活。你确定那是你想做的吗?
它真的是Android的测试吗?我不这么认为。因此,如果您只需要使用该代码删除Test类,请使用按钮创建一个活动,并在单击该按钮时在Test中执行您的代码。
答案 1 :(得分:1)
您好,在您的活动(或服务)下使用BroadcastReceivers和IntentFilters来表示:
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);
添加您要接收的所有操作。 您的代码不起作用,因为您在另一个内部使用广播我不认为这是您想要的。
答案 2 :(得分:1)
您可以在同一时间注册两个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"
}
...
答案 3 :(得分:0)
我能够通过在android清单中注册接收器来使其工作,而不是尝试在test1中动态注册接收器。这个网站确实有所帮助:
http://www.techotopia.com/index.php/Android_Broadcast_Intents_and_Broadcast_Receivers