Intathep
Intathep

Reputation: 3388

Notify users when they reach a location

In the application I'm working on, one of the features is to notify the user when they reach a location that they have set prior.

The code below is in addProximityAlert in Activity:

final Intent intent = new Intent(PROX_ALERT_INTENT);
final PendingIntent pendingIntent = PendingIntent.getBroadcast(
        InfoActivity.this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
LocationManager locationManager = (LocationManager) this
        .getSystemService(Context.LOCATION_SERVICE);
locationManager.addProximityAlert(18.7726271, 98.9738381, 5000, -1,
        pendingIntent);
this.locationReminderReceiver = new LocationReminderReceiver();
final IntentFilter filter = new IntentFilter(PROX_ALERT_INTENT);
this.registerReceiver(this.locationReminderReceiver, filter);

@Override
protected void onPause() {
    super.onPause();
    if (this.locationReminderReceiver != null) {
        Log.i("unregisterReceiver", "unregisterReceiver");
        this.unregisterReceiver(this.locationReminderReceiver);
    }
}

Here's the receiver:

public class LocationReminderReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    final String key = LocationManager.KEY_PROXIMITY_ENTERING;
    final Boolean entering = intent.getBooleanExtra(key, false);

    if (entering) {
        Toast.makeText(context, "LocationReminderReceiver entering", Toast.LENGTH_SHORT).show();
        Log.i("LocationReminderReceiver", "entering");
    } else {
        Toast.makeText(context, "LocationReminderReceiver exiting", Toast.LENGTH_SHORT).show();
        Log.i("LocationReminderReceiver", "exiting");
    }
}
}

It works fine, but I need to call unregisterReceiver every single time I destroy the Activity - that means my application no longer notifies the user. But I want to notify the user when he is near the location until he cancels, or is already notified even if they close the app.

What am I missing?

Upvotes: 3

Views: 2396

Answers (2)

Intathep
Intathep

Reputation: 3388

all i need to do is define receiver in Manifest

then i don't need to register/unregister in Activity anymore

  <receiver android:name="th.clbs.android.broadcastreceiver.LocationReminderReceiver" >
        <intent-filter>
            <action android:name="th.co.clbs.action.LOCATION_REMINDER" />
        </intent-filter>
    </receiver>

Upvotes: 2

logical Chimp
logical Chimp

Reputation: 1014

If the user closes your activity, you should indeed unregister your location listener.

It sounds like you need to move part of your application (the bit that monitors location and alerts the user) to a background service, so that it can continue to run even after the user closes the app.

Upvotes: 3

Related Questions