几个小时后前台服务停止

Foreground Service Stopped after several hours

创建了 Android 服务以在后台更新位置并将其与 Unity 集成。服务在启动时运行良好,但几个小时后服务停止并且不更新用户位置。

下面是 OnStartCommand、OnCreate、Override 方法的代码片段。

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


    super.onStartCommand(intent, flags, startId);

    return START_STICKY;
}

public void onCreate()
{

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

        NotificationChannel   channel  = new NotificationChannel(
                "channel_01",
                "My Channel",
                NotificationManager.IMPORTANCE_DEFAULT
        );
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
        Notification.Builder builder = new Notification.Builder(getApplicationContext(), "channel_01");
        startForeground(12345678, builder.build());


    }
    initializeLocationManager();

    stopForeground(true);


}

如有任何帮助,我们将不胜感激。谢谢

如果您需要 运行 "forever",您的服务必须保持为前台。问题是你正在停止你的前台。

试试这个:

import android.app.Notification;
...
public void onCreate()
{
   super.onCreate();
   ...

   // Build the notification.
   Notification notification = notificationBuilder.build();

   // And Start Foreground.
   startForeground(SERVICE_ID, notification); // Where SERVICE_ID is any integer.
}

并且:

public int onStartCommand(Intent intent, int flags, int startId)
{
        //Return START_STICKY to inform the system that service must be woken up automatically if destroyed
        return START_STICKY;
}

注意:您可以参考这个示例。 https://github.com/android/location-samples/tree/master/LocationUpdatesForegroundService

编辑:

如果你真的需要在后台维护这个(而不是前台),你可以参考Workers。更多信息在这里:https://medium.com/androiddevelopers/workmanager-periodicity-ff35185ff006 请记住,后台位置可能不太频繁(每 15 分钟更新 1 次)。但是在前台你可以让它更频繁。