我有一个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设计用于处理传入的意图并在之后立即停止。因此,在您的情况下,我强烈建议您将IntentService替换为Service
当应用程序被终止时,服务和intentservice都将被终止,您可以在serviceonCreate函数中注册一个watchalarm来在一个控制期间启动self。您可以检查以下代码:

@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 - Android:IntentService终止,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36122054/

10-10 23:29