LocationListener 在 android 服务中一段时间​​后不提供更新

LocationListener doesn't provide update after sometime in android service

我正在编写一个应用程序,我需要从后台快速获取位置更新。 因此,我编写了一个服务来实现所需的结果。

我正在从 activity 的 onCreate() 方法启动服务。

我面临的问题是,该服务能够在服务激活后提供大约 20 到 30 秒的位置更新。然后我没有收到任何更新。

这是服务代码:

public class MyLocService extends Service
        implements
        LocationListener{

  private final LocationListener locationListener = this;

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Handler handler = new Handler(Looper.getMainLooper());
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (checkPermission()) {
                    manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

                    manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
                    manager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
                }
                else{
                    //Request Permission
                    Intent permissionIntent = new Intent();
                    permissionIntent.setAction(LOCATION_PERMISSION_REQUIRED);
                    sendBroadcast(permissionIntent);
                }
                Looper.loop();
            }
        };

        handler.post(runnable);

        //Create notification nad run in foreground
        startForeground(
                NotificationCreator.getNotificationId(),
                NotificationCreator.getNotification(context)
        );

        return Service.START_STICKY;

}

@Override
public void onLocationChanged(Location location) {
     Log.d("LocUpdate",  location.getLatitude() + " : " + location.getLongitude());
}

每次我从 activity 启动服务时,如:

Intent intent = new Intent(this, MyLocService.class);
startService(intent);

我在 onLocationChange() 中获得更新 20 到 30 秒。

另一个观察结果是:如果我保持 activity(从我开始服务的地方打开并可见),那么我会继续获取位置更新。 但是,当我关闭 activity 或终止应用程序并允许服务(单独)在后台 运行 时,我没有得到任何位置更新,尽管服务是 运行ning 因为我可以在我的屏幕顶部看到通知。

我做错了什么?

我已经解决了这个问题。关闭 miui 中的电池优化或将应用程序添加为例外。代码运行完美。