Because someone recommended I implemented an IntentService to do some work in the background. For now i just implemented a very basic service with some dummy code to pretend some long running work:
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);
}
}
}
Unfortunately the ui process in stopping always when i kill the app. If the progress for example is at 50% and i kill the app the progress stays at 50% and does not continue. The documentation says that an IntentService is not getting killed until its work is done but it gets killed in my case.
Later the IntentService should be used for several tasks:
- Sending Images using E-Mail
- Storing Images on a Server
- Repeating the Task automatically when the Task failed caused by missing internet connection.
It is also important to run in the background because i dont want the task to get interrupted when the user gets a phone call. and the repetition of the task is even more important. there could be temporally no connection to the internet, low battery status or even a crash of the whole phone.