gpt4 book ai didi

Android:IntentService 被终止

转载 作者:可可西里 更新时间:2023-11-01 11:40:57 26 4
gpt4 key购买 nike

我有一个 IntentService,它会永远运行,因为我使用的是无限 while 循环。但是,当我关闭我的应用程序时,服务会终止。也许我错了,但据我所知,IntentService 应该在后台运行,直到它完成任务。

此外,由于我使用的是无限 while 循环,因此该服务应该永远运行。但显然这不是正在发生的事情。

public class TaskNotifierService extends IntentService {

public static final String TAG="TaskNotifierIS";

public TaskNotifierService(){
super(TAG);
}

@Override
protected void onHandleIntent(Intent intent) {
while(true){
Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK);
String currentDay=null;

switch(day){
case 1:
currentDay="Sunday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 2:
currentDay="Monday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 3:
currentDay="Tuesday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 4:
currentDay="Wednesday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 5:
currentDay="Thursday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 6:
currentDay="Friday";
Log.i("currentDay","Current day is: "+currentDay);
break;
case 7:
currentDay="Saturday";
Log.i("currentDay","Current day is: "+currentDay);
break;
}

try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}


}

有人可以解释一下,这里出了什么问题吗?

最佳答案

IntentService 旨在处理传入的 Intent 并在之后立即停止。因此,对于您的情况,我强烈建议您将 IntentService 替换为 Service

Service和IntentService都会在应用被kill时被kill掉,你可以在service的onCreate函数中注册一个WatchAlarm来在一个可控的时间内自启动。您可以查看以下代码:

@Override
public void onCreate() {
registerWatchAlarm();
}

private void registerWatchAlarm() {
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
Intent startSelf = new Intent(this, BoostBallService.class);
PendingIntent pi = PendingIntent.getService(this, 0, startSelf,
PendingIntent.FLAG_UPDATE_CURRENT);
am.setRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + WAKE_UP_TIME_INTERVAL, WAKE_UP_TIME_INTERVAL, pi);
}

关于Android:IntentService 被终止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36122054/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com