因为有人建议我实现一个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应该用于几个任务:
在后台运行也很重要,因为我不希望在用户接到电话时任务被中断。而重复任务更为重要。可能暂时没有连接到互联网,电池电量不足甚至整个手机崩溃。
答案 0 :(得分:0)
文档说IntentService在其工作完成之前不会被杀死但在我的情况下会被杀死。
我已经检查了the documentation并且它没有说明这种行为,所以我认为你在这里有一点误会。您的IntentService
是应用程序的组件。如果你杀了你的应用程序,那么它的所有组件都会被杀死。