[英]Notify users when they reach a location
在我正在處理的應用程序中,其中一個功能是在用戶到達之前設置的位置時通知用戶。
以下代碼位於Activity中的addProximityAlert中:
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);
}
}
這是接收器:
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");
}
}
}
它工作正常,但我每次銷毀Activity時都需要調用unregisterReceiver
- 這意味着我的應用程序不再通知用戶。 但是我希望在他離開該位置時通知用戶,直到他取消,或者即使他們關閉應用程序也已經通知。
我錯過了什么?
如果用戶關閉了您的活動,您應該取消注冊您的位置監聽器。
聽起來您需要移動部分應用程序(監視位置並警告用戶的位)到后台服務,以便即使在用戶關閉應用程序后它也可以繼續運行。
我需要做的就是在Manifest中定義接收器
然后我不再需要在Activity中注冊/取消注冊
<receiver android:name="th.clbs.android.broadcastreceiver.LocationReminderReceiver" >
<intent-filter>
<action android:name="th.co.clbs.action.LOCATION_REMINDER" />
</intent-filter>
</receiver>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.