Android:如何每隔5分钟在后台调用Application类内部的函数

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

我想在我的应用中开始刷新Service。我要实现的是每5分钟进行一次API调用,即使用户锁定屏幕以更新数据(尤其是通过使用API​​调用中的新数据重新创建Notification来显示可见的Notification)。

我试图将逻辑移到Application类,在其中我将在Job中初始化GlobalScope,该类将无限期运行,直到我取消此Job。如果将延迟设置为10或30秒,则此解决方案有效。即使我的应用程序在后台运行也可以。但是,如果我将延迟设置为更长的时间(在这种情况下需要)(例如5-10分钟),它将突然停止。我的理解是,长时间不活动时,此Job将会消失或Application类被破坏。

我想创建将与我的Application类进行通信的Service,并在Service中初始化此Job以调用Application类函数以刷新Notification。但是我无法在Service中使用参数。

有什么方法可以链接应用程序类和服务?

如果应用被杀死,我不需要运行此refreshAPI。

示例(此程序正在Application类中运行-要将其移至Service并从Service类调用app.callRefreshAPI()):

var refresher: Job? = null
private var refreshRate = 300000L
fun createNotificationRefresher(){
    refresher = GlobalScope.launch {
        while (isActive){
            callRefreshAPI()
            delay(refreshRate)
        }
    }
}
android kotlin android-service kotlin-coroutines
2个回答
0
投票

您可以为此使用CountDownTimer。

JAVA

public void repeatCall(){

   new CountDownTimer(50000, 1000) {

        public void onTick(long millisUntilFinished) {

        }

        public void onFinish() {
           repeatCall();//again call your method
        }

    }.start();

}

//Declare timer
CountDownTimer cTimer = null;

//start timer function
void startTimer() {
    cTimer = new CountDownTimer(30000, 1000) {
        public void onTick(long millisUntilFinished) {
        }
        public void onFinish() {
        }
    };
    cTimer.start();
}


//cancel timer
void cancelTimer() {
    if(cTimer!=null)
        cTimer.cancel();
}

KOTLIN

 fun repeatCall() {

        object : CountDownTimer(50000, 1000) {

            override fun onTick(millisUntilFinished: Long) {

            }

            override fun onFinish() {
                repeatCall()//again call your method
            }

        }.start()

    }

0
投票

尽管每5分钟调用一次API并不是完成任务的最优化方法。定期作业的最小值为15分钟。您可以使用

[Ever Note Android Job库。

private void schedulePeriodicJob() {
    int jobId = new JobRequest.Builder(DemoSyncJob.TAG)
            .setPeriodic(TimeUnit.MINUTES.toMillis(15), TimeUnit.MINUTES.toMillis(5))
            .build()
            .schedule();
}
© www.soinside.com 2019 - 2024. All rights reserved.