Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/227.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 屏幕锁定时,前台服务进入睡眠状态_Android_Android Location_Foreground Service - Fatal编程技术网

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

Android 屏幕锁定时,前台服务进入睡眠状态,android,android-location,foreground-service,Android,Android Location,Foreground Service,我希望将用户的位置同步到服务器。我已经为此编写了一个前台服务。但是,当屏幕被锁定时,服务将停止发送任何更新。我该如何解决这个问题 public final class LocationUpdateService extends Service { private static final String TAG = "LocationUpdateService"; private FusedLocationProviderClient fusedLocationProvider

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

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());
        }
    });
}
公共最终类位置更新服务扩展服务
{
私有静态最终字符串TAG=“LocationUpdateService”;
私有FusedLocationProviderClient FusedLocationProviderClient;
私人位置请求位置请求;
私有位置回调LocationCallback;
private Util=new Util();
专用静态最终长位置_间隔=15000;
专用静态最终长位置_MIN_位移=20;
私人处理程序服务处理程序;
@可空
@凌驾
公共IBinder onBind(意向)
{
返回null;
}
@凌驾
public void onCreate()
{
/*HandlerThread HandlerThread=新HandlerThread(标记);
handlerThread.start();
serviceHandler=新处理程序(handlerThread.getLooper())*/
fusedLocationProviderClient=新的fusedLocationProviderClient(getApplicationContext());
locationRequest=locationRequest.create();
locationRequest.setInterval(位置间隔);
locationRequest.setPriority(locationRequest.PRIORITY\u BALANCED\u POWER\u Accurance);
//位置请求。设置最小位移(位置最小位移);
locationCallback=新locationCallback()
{
@凌驾
public void onLocationResult(LocationResult LocationResult)
{
if(locationResult==null)
{
返回;
}
Location Location=locationResult.getLastLocation();
如果(位置!=null)
{
Log.d(标记“LocationCallback:location received”);
sendLocation(util.getToken(getApplicationContext())、new RequestLocationUpdate(String.valueOf(location.getLatitude())、String.valueOf(location.getLength());
}
其他的
{
Log.d(标记“LocationCallback:null location received”);
}
}
};
startForeground(Constants.NOTIFICATION_ID_LOCATION,getLocationNotification());
requestLocationUpdates();
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId)
{
返回开始时间;
}
@凌驾
公共空间
{
super.ondestory();
RemovelocationUpdate();
serviceHandler.removeCallbacksAndMessages(null);
stopSelf();
}
@凌驾
公共void onTaskRemoved(Intent rootIntent)
{
Intent restartServiceIntent=newintent(getApplicationContext(),this.getClass());
setPackage(getPackageName());
PendingEvent RestartServicePendingEvent=PendingEvent.getService(getApplicationContext(),1,restartServiceIntent,PendingEvent.FLAG_ONE_SHOT);
AlarmManager alarmService=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM\u服务);
alarmService.set(
AlarmManager.u实时,
SystemClock.elapsedRealtime()+1000,
restartServicePendingIntent);
super.onTaskRemoved(rootIntent);
}
私有void requestLocationUpdates()
{
fusedLocationProviderClient.RequestLocationUpdate(locationRequest、locationCallback、Looper.getMainLooper());
}
私有void removeLocationUpdates()
{
fusedLocationProviderClient.RemovelocationUpdate(locationCallback);
}
私有通知getLocationNotification()
{
返回新的NotificationCompat.Builder(这是常量.NOTIFICATION\u通道\u重要\u ID)
.setContentTitle(“位置服务”)
.setContentText(“您的位置正在同步到服务器”)
.setSmallIcon(R.drawable.vector_徽标)
.build();
}
私有void sendLocation(字符串授权、RequestLocationUpdate请求)
{
APIClient.getClient().updateLocation(授权、请求).enqueue(新回调()
{
@凌驾
公共void onResponse(调用、响应)
{
if(response.issusccessful())
{
if(response.body().getStatus())
{
Log.d(标记“sendLocation:成功发送的位置”);
}否则
{
Log.d(标记“sendLocation:+response.body().getMessage());
}
}否则
{
Log.d(标记“sendLocation:+response.message());
}
}
@凌驾
失败时公共无效(调用调用,可丢弃的t)
{
Log.d(标记“sendLocation:+t.getMessage());
}
});
}

}

尽管可能很奇怪,解决方案是使用
locationRequest.setPriority(locationRequest.PRIORITY\u高精度)而不是
locationRequest.setPriority(locationRequest.PRIORITY\u BALANCED\u POWER\u accurity)

我一做出这一改变,它就开始在屏幕锁定的情况下工作