Android:IntentService被终止

时间:2016-03-21 02:05:33

标签: android service intentservice background-service

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

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

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();
            }

        }
    }


}

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

2 个答案:

答案 0 :(得分:2)

IntentService旨在处理传入的意图并立即停止。因此,在您的情况下,我强烈建议您将IntentService替换为Service

在应用程序被杀死时,Service和IntentService都将被终止,您可以在服务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);
}

答案 1 :(得分:0)

Android可以随时杀死任何应用程序进程而不会发出警告。它有一个优先级系统,通过它可以决定哪些进程首先被杀死。使服务处于活动状态不会阻止您的进程被杀死,尤其是在没有可见UI的情况下。

您可以阅读更多details about the priority system here。从以下文字开始:

  

Android系统尝试维护as的应用程序进程   尽可能长,但最终需要删除旧进程   为新的或更重要的过程回收记忆。