Android: How to register passive LocationListener in manifest?

I need to get gps location fixes using adndroid, but I don't want the device to explicitly register the LocationListener in the Activity code or so ... i.e. I want to register the LocationListener directly in the manifest file.

Unfortunately it doesn't work :( Here's my code:

<uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<receiver android:name=".GPSLocationListener" android:enabled="true">
        <action android:name="android.location.LocationManager.KEY_LOCATION_CHANGED" />


while my listener looks like this:

public class GPSLocationListener implements LocationListener
    public void onLocationChanged(Location location)

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


but no matter what I do, I don't want the emulator to catch the new (mock) location that I push through DDMS ... :(

Does anyone know how to do this?


source to share

4 answers

Take a look at Deep Dive in Location . Reto Meier explains how to register a service as a recipient of a passive LocationUpdate via PendingIntent.

The important part is not to use the requestLocation update methods, which take a listener object, but use the methods that receive the PendingIntent . This way, even if all your actions are complete the moment a gps fix or network location is received, the PendingIntent will be triggered and your service will start.
Reto Meier uses a broadcast receiver for android.intent.action.BOOT_COMPLETED, which checks if the app should do location updates in the background and then requests location updates using PendingIntent.



The location manager does not broadcast location updates. You have to ask for location updates programmatically.

Also, the recipient declaration in the manifest for BroadcastReceiver

, yours is LocationListener

not BroadcastReceiver

. This means that if someone sent a braodcast that matched your filter, you would get a type mismatch when the classloader tries to instantiate it BroadcastReceiver




Try registering the pending intent with the LocationManager.requestLocationUpdates () method:

LocationManager mgr = (LocationManager) getSystemService(LOCATION_SERVICE);
Intent intent = new Intent("Unique_Broadcast_Message");       
PendingIntent launchIntent = PendingIntent.getBroadcast(your activity, 0, intent, 0);
mgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, launchIntent);


Also declare a recipient who receives "Unique_Broadcast_Message".



If you want to use the library, check it out. It uses a passive location provider and exposes it to the broadcast receiver. Very easy to use.

Little-Fluffy-Location Library for Android



All Articles