【发布时间】:2018-03-22 08:45:50
【问题描述】:
我从 Google 的 LocationUpdatesPendingIntent 示例开始。 我已将位置信息从 Main Activity 移至 onBoot 广播接收器,因为我需要在设备启动时立即开始位置更新。这完美地工作并在状态栏中提供通知。
但是我该如何从 Activity 开启和关闭位置更新?
这是用于轮询车辆位置。
这是我的广播接收器:
public class StartupComplete1 extends BroadcastReceiver {
private static final long UPDATE_INTERVAL = 10000; // Every 10 seconds.
private static final long FASTEST_UPDATE_INTERVAL = 5000; // Every 5 seconds
private static final long MAX_WAIT_TIME = UPDATE_INTERVAL * 2; // Every 20 seconds.
private LocationRequest mLocationRequest;
private FusedLocationProviderClient mFusedLocationClient;
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED)) {
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(context);
createLocationRequest();
try {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, getPendingIntent(context));
} catch (SecurityException e) {
Toast.makeText(context, "Error - Cant start location updates", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
private PendingIntent getPendingIntent(Context context) {
Intent intent = new Intent(context, LocationUpdatesBroadcastReceiver.class);
intent.setAction(LocationUpdatesBroadcastReceiver.ACTION_PROCESS_UPDATES);
return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
private void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(UPDATE_INTERVAL);
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setMaxWaitTime(MAX_WAIT_TIME);
}
【问题讨论】: