我如何连续运行Android服务

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

即使清除正在运行的应用程序(RAM)后,我如何仍能连续运行Android服务...请提供给我服务代码,而不是让我退回Android开发人员我的代码如下:

public class MyService extends Service {
public MyService() {
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    // TODO: Return the communication channel to the service.
    return null;
}


@Override
public int onStartCommand(Intent intent1, int flags, int startId) {
    // do your jobs here
    return super.onStartCommand(intent1, flags, startId);
}
android android-studio android-service
2个回答
2
投票
您需要根据需要从onStartCommand返回START_STICKYSTART_REDELIVER_INTENT

public class MyService extends Service { public MyService() { } @Nullable @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. return null; } @Override public int onStartCommand(Intent intent1, int flags, int startId) { // do your jobs here return START_STICKY; } }

如开发者网站所述,如果您不打算传递任何启动服务的意图,则只需返回START_STICKY标志。这将使用空白的intent对象重新创建服务。 

0
投票
您将服务归还为粘性,像这样

@Override public int onStartCommand(Intent intent, int flags, int startId) { return START_STICKY; }

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