前台服务在几个小时后停止

问题描述 投票:0回答:2

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

下面是OnStartCommand,OnCreate的代码片段,重写方法。

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
2个回答
0
投票

您是否尝试扩展JobService?即使重新启动手机,它也可以正常工作。

public class NotificationService extends JobService {


    public static final String TASK_ID = "notification_task_id";
    private static final String TAG = "NotificationJobService";
    private boolean jobCancelled = false;
    private String notificationTaskID;



    @Override
    public boolean onStartJob(JobParameters params) {
        Log.d(TAG, "onStartJob: Job Started");
        doBackgroundWork(params);
        return true;
    }

    private void doBackgroundWork(final JobParameters params) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                notifiy(params);
            }
        }).start();
    }

    public void notifiy(JobParameters params) { // dzieje się w przy notyfikacji


        createNotification("Title", "message", 'channelID', getApplicationContext());

        jobFinished(params, false);
    }


    public void createNotification(String aTitle, String aMessage, int channelID, Context context) {
        // create your notification here
    }

    @Override
    public boolean onStopJob(JobParameters params) {

        Log.d(TAG, "onStopJob: Job Cancelled");
        jobCancelled = true;
        return true;
    }


}

0
投票

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

尝试一下:

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

© www.soinside.com 2019 - 2024. All rights reserved.