Android中Handler的使用
当我们在处理下载或是其他需要长时间执行的任务时,如果直接把处理函数放Activity的OnCreate或是OnStart中,会导致执行过程中整个Activity无响应,如果时间过长,程序还会挂掉。Handler就是把这些功能放到一个单独的线程里执行,与Activity互不影响。
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
public class HandleActivity extends Activity { private ImageView imageView = null; private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0:
//你的操作 break; case 1:
//你的造作 break; } super.handleMessage(msg); } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); thread.start(); } Thread thread = new Thread(new Runnable() { public void run() { Message message = new Message();
message.what = 1;
message.obj = obj;
handler.sendMessage(message);
} }); }
也可以直接写在一个方法内实现
private void getRealTimeBills(final String date)
{
final Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if(msg.what == 1)
{
realTimeBills = (RealTimeBills) msg.obj;
}
}
};
new Thread(){
@Override
public void run()
{
Message message = new Message();
try
{
realTimeBills = context.getRealTimeBills(date);
if(realTimeBills.getResultMessage().OK())
{
message.what = 1;
message.obj = realTimeBills;
}
catch (Exception e)
{
e.printStackTrace();
}
handler.sendMessage(message);
}
}.start();
}