I am experimenting with requestLocationUpdates(String provider, long minTime, float minDistance, PendingIntent intent)
and a BroadcastReceiver. The code is as follows:
// 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;
开发者_如何学Go public SomeReceiver(PendingLocationDemo caller) {
this.caller = caller;
}
@Override
public void onReceive(Context context, Intent intent) {
caller.someCallback(intent);
}
}
When I run this on a device, the output depends on the value I use for the action in the IntentFilter.
- for "some_action", the output is: Intent { act=some_action cat=[android.intent.category.DEFAULT] (has extras) }
- for "some_other_action", the output is: Intent { act=some_other_action (has extras) }
- for "still_something_different", I do not receive the updates.
Is there a reasonable explanation for such inconsistent behavior?
This strange behaviour is due to the registration of broadcast receiver. Instead of registering the broadcast receiver you can write your code within the Location Listener which is also a broadcast receiver and listens for location updates in background.
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);
Hope it helps.
精彩评论