Skip to content Skip to sidebar Skip to footer

Service And AsyncTask

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

Solution 1:

You can run an AsyncTask in a Service just like you would run it in an Activity or Fragment. Why would there be any difference?

ExampleTask task = new ExampleTask();
task.execute();

But you can also subclass IntentService instead of Service! An IntentService automatically handles each Intent in a separate Thread. That way you can perform work in the Service without blocking the UI and you don't have to deal with AsyncTasks or Threads!

public class ImageSendEmailService extends IntentService {

    @Override
    protected void onHandleIntent(Intent intent) {
        // Do your work here!
    }
}

You can find the documentation of IntentService here.

As an aside: Whatever you are trying to there with Thread.sleep() is a really bad idea. Never use Thread.sleep() like that. Use a Timer or Handler instead!


Solution 2:

This is how you do an async task

AsyncTask<Void,Integer,Void> myTask = new AsyncTask<Void,Integer,Void>(){

@Override
public Void doInBackground(Void... params){
   for (int i = 0; i <= 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

           publishProgress((int) (100 * i / 10));
        }
return null;
}
     @Override
    public void onProgressUpdate(Integer... progress) {
     String notificationText = String.valueOf(progress[0]) + " %";

            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);
 }



}

myTask.execute();

Just to be clear this is what i meant in my answer

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) {
   AsyncTask<Void,Integer,Void> myTask = new AsyncTask<Void,Integer,Void>(){

@Override
public Void doInBackground(Void... params){
   for (int i = 0; i <= 10; i++) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

           publishProgress((int) (100 * i / 10));
        }
return null;
}
     @Override
    public void onProgressUpdate(Integer... progress) {
     String notificationText = String.valueOf(progress[0]) + " %";

            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);
 }



}

myTask.execute();
    return super.onStartCommand(intent, flags, startId);
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}


Post a Comment for "Service And AsyncTask"