我正在试验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中的操作的值。
这种不一致的行为是否有合理的解释?
答案 0 :(得分:0)
这种奇怪的行为是由于广播接收器的注册。您可以在位置侦听器中编写代码,而不是注册广播接收器,位置侦听器也是广播接收器,并在后台侦听位置更新。
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);
希望它有所帮助。