如何解决Fused Location API 服务在一段时间后被 Android 杀死
对于位置更新,我使用了 Fused Location API,但似乎有些 Android 手机在一段时间后会终止前台服务。如何运行前台服务并确保它们不会被 Android 终止?
public class LocationUpdatesService extends Service {
public class LocalBinder extends Binder {
public LocationUpdatesService getService() {
return LocationUpdatesService.this;
}
}
private final IBinder mBinder = new LocalBinder();
@Override
public void onCreate() {
createFusedLocationClient();
createFusedLocationRequest();
createLocationCallback();
startForeground(NOTIFICATION_ID,createAutoUnlockEnabledNotification());
}
private void createFusedLocationClient() {
locationClient = LocationServices.getFusedLocationProviderClient(getApplicationContext());
}
private void createFusedLocationRequest() {
locationRequest = new LocationRequest();
locationRequest.setMaxWaitTime(MAXIMUM_WAIT_TIME);
locationRequest.setSmallestDisplacement(MAXIMUM_DISPLACEMENT);
locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
}
@Override
public int onStartCommand(Intent intent,int flags,int startId) {
String action = intent.getAction();
if (action != null && action.equalsIgnoreCase(Constants.REQUEST_LOCATION_UPDATES)) {
requestLocationUpdates();
}
if (action != null && action.equalsIgnoreCase(Constants.REMOVE_LOCATION_UPDATES)) {
removeLocationUpdates();
stopSelf();
}
return START_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
ContextCompat.startForegroundService(getApplicationContext(),new Intent(getApplicationContext(),LocationUpdatesService.class));
return mBinder;
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。