Using Handler for long-time operations in Android

Need to notify user when for example user clicks button and in onClick method program starts some long-time process. Need to have some solution which will do your task in background. Handler is very good solution for this problem.
If you will not use such approach then user will see that program appears to hang.

How to use it?
First need to to override handleMessage method.

private Handler handler = new Handler(){ @Override  public void handleMessage(Message msg){ super.handleMessage(msg); // do something  }  };

At second need to create Thread.

new Thread(){ public void run(){//long time method handler.sendEmptyMessage(0); }  }.start();

I will post full code for showing whole picture.
Example:

import android.app.Activity;import android.app.ProgressDialog;import android.os.Bundle;import android.os.Handler;import android.os.Message;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;public class Main extends Activity{ private Button clickBtn; private ProgressDialog progressDialog; private Handler handler = new Handler(){ @Override  public void handleMessage(Message msg){ super.handleMessage(msg); progressDialog.dismiss(); }  }; @Override  public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.main); clickBtn = (Button) findViewById(R.id.click); clickBtn.setText("Click me"); clickBtn.setOnClickListener(new OnClickListener(){ @Override  public void onClick(View v){processThread(); }  }); }  private void processThread(){ progressDialog = ProgressDialog.show(Main.this,"","Doing..."); new Thread(){ public void run(){longTimeMethod();handler.sendEmptyMessage(0); }  }.start(); }  private void longTimeMethod(){ try{ Thread.sleep(10000); } catch (InterruptedException e){ Log.e("tag",e.getMessage()); }  }}

This simple example shows whole process of using Handler in your code.
Using Handler is very useful and easy. If you will follow this practice your users will not see that your program appears to hang.

But in Android 1.5 and higher versions there is better approach. AsyncTask class is more preferred. How to use AsyncTask I will show next time.

Share

No related posts.

Leave a Reply

  

  

  

You can use these HTML tags

<a href=""title=""><abbr title=""><acronym title=""><b><blockquote cite=""><cite><code><del datetime=""><em><i><q cite=""><strike><strong>

A sample text widget

Etiam pulvinar consectetur dolor sed malesuada. Ut convallis euismod dolor nec pretium. Nunc ut tristique massa.

Nam sodales mi vitae dolor ullamcorper et vulputate enim accumsan. Morbi orci magna,tincidunt vitae molestie nec,molestie at mi. Nulla nulla lorem,suscipit in posuere in,interdum non magna.