屏幕锁定时,前台服务进入睡眠状态

问题描述

我希望将用户的位置同步到服务器。我已经为此编写了前台服务。但是,当屏幕锁定时,该服务将停止发送任何更新。我该如何解决

public final class LocationUpdateService extends Service
{
private static final String TAG = "LocationUpdateService";
private FusedLocationProviderClient fusedLocationProviderClient;
private LocationRequest locationRequest;
private LocationCallback locationCallback;
private Util util = new Util();

private static final long LOCATION_INTERVAL = 15000;
private static final long LOCATION_MIN_disPLACEMENT = 20;

private Handler serviceHandler;

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onCreate()
{
    /*HandlerThread handlerThread = new HandlerThread(TAG);
    handlerThread.start();
    serviceHandler = new Handler(handlerThread.getLooper());*/

    fusedLocationProviderClient = new FusedLocationProviderClient(getApplicationContext());

    locationRequest = LocationRequest.create();
    locationRequest.setInterval(LOCATION_INTERVAL);
    locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
//            locationRequest.setSmallestdisplacement(LOCATION_MIN_disPLACEMENT);

    locationCallback = new LocationCallback()
    {
        @Override
        public void onLocationResult(LocationResult locationResult)
        {
            if (locationResult == null)
            {
                return;
            }
            Location location = locationResult.getLastLocation();
            if (location != null)
            {
                Log.d(TAG,"LocationCallback: location received");
                sendLocation(util.getToken(getApplicationContext()),new RequestLocationUpdate(String.valueOf(location.getLatitude()),String.valueOf(location.getLongitude())));
            }
            else
            {
                Log.d(TAG,"LocationCallback: null location received");
            }
        }
    };

    startForeground(Constants.NOTIFICATION_ID_LOCATION,getLocationNotification());
    requestLocationUpdates();
}

@Override
public int onStartCommand(Intent intent,int flags,int startId)
{
    return START_STICKY;
}


@Override
public void onDestroy()
{
    super.onDestroy();
    removeLocationUpdates();
    serviceHandler.removeCallbacksAndMessages(null);
    stopSelf();
}

@Override
public void onTaskRemoved(Intent rootIntent)
{
    Intent restartServiceIntent = new Intent(getApplicationContext(),this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(),1,restartServiceIntent,PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
            AlarmManager.ELAPSED_REALTIME,SystemClock.elapsedRealtime() + 1000,restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
}

private void requestLocationUpdates()
{
    fusedLocationProviderClient.requestLocationUpdates(locationRequest,locationCallback,Looper.getMainLooper());
}

private void removeLocationUpdates()
{
    fusedLocationProviderClient.removeLocationUpdates(locationCallback);
}

private Notification getLocationNotification()
{
    return new NotificationCompat.Builder(this,Constants.NOTIFICATION_CHANNEL_IMPORTANT_ID)
            .setContentTitle("Location Service")
            .setContentText("Your location is being synced to the server")
            .setSmallIcon(R.drawable.vector_logo)
            .build();
}

private void sendLocation(String authorization,RequestLocationUpdate request)
{
    apiclient.getClient().updateLocation(authorization,request).enqueue(new Callback<ResponseGenericUser>()
    {
        @Override
        public void onResponse(Call<ResponseGenericUser> call,Response<ResponseGenericUser> response)
        {
            if (response.isSuccessful())
            {
                if (response.body().getStatus())
                {
                    Log.d(TAG,"sendLocation: Location sent successfully");
                } else
                {

                    Log.d(TAG,"sendLocation: " + response.body().getMessage());
                }
            } else
            {
                Log.d(TAG,"sendLocation: " + response.message());
            }
        }

        @Override
        public void onFailure(Call<ResponseGenericUser> call,Throwable t)
        {
            Log.d(TAG,"sendLocation: " + t.getMessage());
        }
    });
}

}

解决方法

奇怪的是,解决方案是使用locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);而不是locationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

进行此更改后,它也开始在锁定屏幕的情况下工作。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...