【问题标题】:IntentService is stopping everytime i kill the app每次我杀死应用程序时,IntentService 都会停止
【发布时间】:2014-11-30 03:59:29
【问题描述】:

因为有人建议我实现一个 IntentService 在后台做一些工作。现在我只是用一些虚拟代码实现了一个非常基本的服务来假装一些长时间运行的工作:

public class ImageSendEmailService extends IntentService {
    private static final int MY_NOTIFICATION_ID = 1;
    private NotificationManager notificationManager = null;
    private Notification notification = null;

    public ImageSendEmailService() {
        super("EmailService");
    }

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

        this.notificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        for (int i = 0; i <= 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            String notificationText = String.valueOf((int) (100 * i / 10)) + " %";

            NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
            builder.setContentTitle("Progress");
            builder.setContentText(notificationText);
            builder.setTicker("Notification!");
            builder.setWhen(System.currentTimeMillis());
            builder.setDefaults(Notification.DEFAULT_SOUND);
            builder.setAutoCancel(true);
            builder.setSmallIcon(R.drawable.ic_launcher);

            this.notification = builder.build();
            this.notificationManager.notify(MY_NOTIFICATION_ID, this.notification);
        }
    }
}

不幸的是,当我杀死应用程序时,ui 进程总是停止。例如,如果进度为 50% 并且我终止了应用程序,则进度保持在 50% 并且不会继续。文档说 IntentService 在其工作完成之前不会被杀死,但在我的情况下它会被杀死。

稍后 IntentService 应该用于多个任务:

  1. 使用电子邮件发送图像
  2. 在服务器上存储图像
  3. 由于缺少互联网连接而导致任务失败时自动重复任务。

在后台运行也很重要,因为我不希望任务在用户接到电话时中断。而任务的重复则更为重要。可能会暂时无法连接到互联网、电池电量不足甚至整个手机崩溃。

【问题讨论】:

    标签: android


    【解决方案1】:

    文档说 IntentService 在其工作完成之前不会被杀死,但在我的情况下它会被杀死。

    我检查了the documentation 并没有说明这种行为,所以我认为你在这里有点误解。您的 IntentService 是应用程序的组件。如果你杀死你的应用程序,那么它的所有组件都会被杀死。

    【讨论】:

    • 这篇文章的 cmets:*.com/questions/27205134/… 都在说,只要有工作要做,intentservice 就应该存在。如果没有,我应该怎么做?
    • 总结一下:您应该在前台启动Service,这会自动将其与无法关闭的通知捆绑在一起,并防止它被操作系统杀死,例如当内存不足时。此外,您可以指定Service 应该在它自己的进程中运行。尽管根据我的经验,这不是必需的。如果您查看其他应用程序在前台 Services 方面的行为,例如 Google Play 商店和 Google Play 音乐,Service 本身似乎总是能在被杀死的进程中幸存下来,但相关的 UI 却没有。
    • 所以现在我应该使用Service,但我的意图并没有改变……几个小时前你推荐我使用IntentService
    • @Mulgard 我刚刚向您解释了您的选择,它们的优点和缺点。如果您只想异步处理Service 中的数据,那么使用IntentService 非常方便且推荐。如果您想在此工作完成时在通知中显示进度,并且您想防止Service 在正常操作期间被杀死,那么最好在前台启动Service。但这一切都取决于您想做什么和您的要求。
    • 我想我很好地列出了我的要求。我现在就试试这个:truiton.com/2014/10/android-foreground-service-example