【发布时间】: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 应该用于多个任务:
- 使用电子邮件发送图像
- 在服务器上存储图像
- 由于缺少互联网连接而导致任务失败时自动重复任务。
在后台运行也很重要,因为我不希望任务在用户接到电话时中断。而任务的重复则更为重要。可能会暂时无法连接到互联网、电池电量不足甚至整个手机崩溃。
【问题讨论】:
标签: android