這個哥們寫的東西很實際 應用場合很典型,比很多文章嘰歪的都好。
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 whole code for showing whole picture.
Example:
package com.faynasoftlabs.tutorial.android.handlerexample;
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;
/**
* Class which shows how to work with handler class
* @author FaYna Soft Labs
*/
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());
}
}
}
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.