gpt4 book ai didi

android - 设备上 IntentFilter 分辨率的奇怪行为

转载 作者:太空狗 更新时间:2023-10-29 15:23:22 25 4
gpt4 key购买 nike

我正在试验 requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent) 和 BroadcastReceiver。代码如下:

// 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”,我没有收到更新。

对于这种不一致的行为是否有合理的解释?

最佳答案

这种奇怪的行为是由于广播接收器的注册。您可以在位置监听器中编写代码,而不是注册广播接收器,它也是一个广播接收器并在后台监听位置更新。

final LocationManager locationManager = (LocationManager) context
.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {

public void onLocationChanged(Location location) {
// Code for action you wish to perform on Location Changed.
}

public void onStatusChanged(String provider, int status, Bundle extras) {}

public void onProviderEnabled(String provider) {}

public void onProviderDisabled(String provider) {}
};
// ...
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
3000, locationListener);

希望对您有所帮助。

关于android - 设备上 IntentFilter 分辨率的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5109663/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com