【问题标题】:Foreground Service Stopped after several hours几个小时后前台服务停止
【发布时间】:2019-11-22 13:53:08
【问题描述】:

创建 Android 服务以在后台更新位置并将其与 Unity 集成。服务在启动时工作正常,但几个小时后服务停止并且它不会更新用户位置。

下面是OnStartCommand, OnCreate, Override方法的代码sn-p。

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);


}

任何帮助将不胜感激。谢谢

【问题讨论】:

    标签: android unity3d service location


    【解决方案1】:

    如果您需要“永远”运行,您的服务必须保持为前台。问题是你正在停止你的前景。

    试试这个:

    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 次)。但在前台你可以让它更频繁。

    【讨论】:

    • 感谢彼得的详细回答。当应用程序进入后台时,是否可以在不显示通知栏的情况下将服务作为前台运行?
    • @AsadAli 对不起,“前台服务必须显示通知”,如developer.android.com/guide/components/services 中所述。如果服务在前台,则通知是强制性的,但如果它进入后台(不是前台),则通知不是强制性的。
    • 您好,您知道是否有可能知道 Android 是否会终止该服务?
    猜你喜欢
    • 1970-01-01
    • 2021-07-16
    • 1970-01-01
    • 1970-01-01
    • 2012-12-20
    • 2021-11-22
    • 2018-11-11
    • 1970-01-01
    • 2014-09-23
    相关资源
    最近更新 更多