原文地址:http://blog.youkuaiyun.com/wleing/article/details/6086321
为了安抚用户等待的焦急心情,我们用ProgressDialog。它的用法书上有例子,就是:
ProgressDialog myDialog = ProgressDialog.show(YourClass.this, "正在连接服务器..", "连接中,请稍后..", true, true);
handler.post(mTasks);
它的用法一般都是在用intent开启一个新的activity的时候,你直接加上这句话,是达不到你想要的效果的。
你必须这样用:把用intent开启activity的这件事放在一个Runnable对象的run()方法中,然后用handler.post()方法来运行这个线程。
代码如下:
Handler handler = new Handler();
Runnable mTasks = new Runnable() {
public void run() {
Intent intent = new Intent();
intent.setClass(YourClass .this,EditHome.class);
startActivity(intent);
}
};
final ProgressDialog myDialog = ProgressDialog.show(YourClass.this, "正在连接服务器..", "连接中,请稍后..", true, true);
handler.post(mTasks);
这样算是达到我们要的效果了,可是,那个ProgressDialog的窗口并没有关闭,所以后面还要加上myDialog.dismiss();
但这样的话,窗口出来就消失,我们又看不到ProgressDialog了...所以,我们要用一个线程来控制窗口消失的时间:
new Thread() {
public void run() {
try{
sleep(5000);
}catch(InterruptedException e){
e.printStackTrace();
}
myDialog.dismiss();
}}.start();
那个sleep的时间是你估算下一个activity显示出来所需要的时间。OK了。
但显然这样做是不科学的。科学的做法是:首先在原avtivity中添加一个关闭Dialog的静态方法:
public static void closeProgressDialog() {
myDialog.dismiss();
}
然后在目标的activity中添加两个成员变量:
private static final int EVENT_TIME_TO_CHANGE_IMAGE = 100;
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
switch(msg.what){
case EVENT_TIME_TO_CHANGE_IMAGE:
YourPrimaryClass.closeProgressDialog();
break;
}
}};
其中Handler中注册了关闭窗口的条件和关闭动作(调用静态方法)。然后在这个activity的onCreat()方法里的最后面加上发送消息的代码:
Message message = mHandler.obtainMessage(EVENT_TIME_TO_CHANGE_IMAGE);
mHandler.sendMessage(message);
这样就能保证是在目标activity全部显现出来之后关闭那个progressDialog了。