Notify users when they reach a location

最后都变了- 提交于 2019-12-07 16:33:25

问题


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?


回答1:


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.




回答2:


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>


来源:https://stackoverflow.com/questions/12638668/notify-users-when-they-reach-a-location

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!