【发布时间】:2013-05-10 08:05:18
【问题描述】:
我正在试验requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent) 和一个广播接收器。代码如下:
// PendingLocationDemo.java
public class PendingLocationDemo extends Activity {
public TextView output;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
output = (TextView) findViewById(R.id.output);
SomeReceiver receiver = new SomeReceiver(this);
IntentFilter filter = new IntentFilter();
filter.addAction("some_action");
// filter.addAction("some_other_action");
// filter.addAction("still_something_different");
filter.addCategory(Intent.CATEGORY_DEFAULT);
getApplicationContext().registerReceiver(receiver, filter);
Intent intent = new Intent();
intent.setAction("some_action");
PendingIntent pending = PendingIntent.getBroadcast(
getApplicationContext(), 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT);
// Get the location manager
LocationManager locationManager = (LocationManager)
getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER, 3000, 0, pending);
}
protected void someCallback(Intent intent) {
printObject(intent);
}
}
// SomeReceiver.java
public class SomeReceiver extends BroadcastReceiver {
PendingLocationDemo caller;
public SomeReceiver(PendingLocationDemo caller) {
this.caller = caller;
}
@Override
public void onReceive(Context context, Intent intent) {
caller.someCallback(intent);
}
}
当我在设备上运行它时,输出取决于我在 IntentFilter 中用于操作的值。
- 对于“some_action”,输出为: Intent { act=some_action cat=[android.intent.category.DEFAULT](有附加功能)}
- 对于“some_other_action”,输出为: Intent { act=some_other_action(有附加功能)}
- 对于“still_something_different”,我没有收到更新。
对这种不一致的行为有合理的解释吗?
【问题讨论】:
-
抱歉上面的代码有点不清楚。所以你注册一个永远不会触发的广播(或者至少我看不到在哪里)。然后,当您获得 gps 更新时,您要求在 PendingIntent 中触发一个空白意图?你怎么得到任何输出?我猜您的问题可能与拼写错误有关?
-
你是对的,上面的代码有一个错字:PendingIntent 触发了一个带有“some_action”的 Intent。然后我改变过滤器中的动作,得到预期的输出,或者当我根本不期望任何输出时得到奇怪的东西。
-
为了更清楚一点:第一种和最后一种情况是预期的(操作匹配所以我得到更新,或者不匹配并且没有更新)。然而,第二种情况既奇怪又出人意料。我的直觉是它可能与 dalvik-cache 相关......
-
你是说当只添加动作
some_other_action(你不是一次都添加它们吗?)到你的IntentFilter并使用动作some_action广播时,你会收到更新到你的接收者?如果是这样,那么您认为它不应该发生是正确的。我猜它可能与缓存相关 - 如果将some_other_action更改为some_other_action2或some_other_action_A会发生什么? -
@Joseph:是的,我就是这个意思。这是一个很老的问题,所以我不能直接回答你的问题,但关键是我尝试了不同的值并得到了完全出乎意料的结果。