How can i run and AsyncTask in a Service so that the UI does not freeze when i do my work in a service? Today i implemented a very basic service:
public class ImageSendEmailService extends Service {
private NotificationManager notificationManager = null;
private Notification notification = null;
@Override
public void onCreate() {
super.onCreate();
this.notificationManager = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
String notificationText = String.valueOf((int) (100 * i / 10)) + " %";
Notification.Builder builder = new Notification.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(0, notification);
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
but the ui is freezing while i perform that.