即使应用程序关闭,也可以在服务中重复任务

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

即使应用程序关闭,我想在服务中以特定间隔调用方法,当应用程序在后台时,应用程序运行时它工作正常,但是当我从后台关闭应用程序时它停止了。我想保持它运行,即使应用程序关闭我怎么能实现它?

我在API 28下面面对这个问题这个工作正常。

这是我的代码。

public class ReminderHandlerService extends Service {


private Handler handler;

@Override
public IBinder onBind(Intent intent) {
    return null;
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler = new Handler();
    startReminderService();
    return START_STICKY;
    //return super.onStartCommand(intent, flags, startId);
}

@Override
public void onCreate() {
    super.onCreate();
}

Runnable runReminder = new Runnable() {
    @Override
    public void run() {
        try {

            Intent reminderServiceIntent = new Intent(ReminderHandlerService.this, ReminderService.class);
            reminderServiceIntent.putExtra("mydata", "this is my data");
            startService(reminderServiceIntent);

        } finally {

            handler.postDelayed(runReminder, 10000);
        }
    }
};

void startReminderService() {
    runReminder.run();
}

}
android service handler runnable
1个回答
0
投票

您将需要使用WorkManagerJobSchedulerAlarmManager的警报,以便在您的应用关闭时执行某些事件。如果您要定位较新的设备并希望具有向后兼容性,那么您应该查看WorkManager

https://developer.android.com/topic/libraries/architecture/workmanager/basics

JobSchedulerAlarmManager是Android中的旧技术,需要API特定编码才能正常运行。 WorkManager将自动为您处理此问题。

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