我在一个非常基本的Handler教程中遇到了这段代码.代码工作正常,但我不明白为什么我必须使用Handler progressDialog.dismiss()??? 我删除了处理程序部分并放置 progressDialog.dismiss()在run()方法中,它工作正常.那么为什么使用Handler ???
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class HandlerThread extends Activity{
private Button start;
private ProgressDialog progressDialog;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
start = (Button) findViewById(R.id.Button01);
start.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
fetchData();
}
});
}
protected void fetchData() {
// TODO Auto-generated method stub
progressDialog = ProgressDialog.show(this, "", "Doing...");
new Thread() {
public void run() {
try {
Thread.sleep(8000);
} catch (InterruptedException e) {
}
messageHandler.sendEmptyMessage(0);
}
}.start();
}
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
}
};
}
Run Code Online (Sandbox Code Playgroud)
Dev*_*ath 31
第一:让我们知道什么是线程:
第二:告诉我们应用程序线程: -
Android UI-Toolkit不是线程安全的
处理程序类:
android.os.Handler
处理程序的实例
Handler handlerObject = new Handler();
Run Code Online (Sandbox Code Playgroud)
使用处理程序的最后一件事是使用Runnable Interface:
Class NameOfClass implements Runnable
{
Public void run()
{
//Body of run method
}
}
Run Code Online (Sandbox Code Playgroud)
全部放在一起
//Create handler in the thread it should be associated with
//in this case the UI thread
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
public void run() {
while(running){
//Do time consuming stuff
//The handler schedules the new runnable on the UI thread
handler.post(new Runnable() {
//Ex.. using progressbar to set the pogress
//Updating the UI is done inside the Handler
});
}
}
};
new Thread(runnable).start();
Run Code Online (Sandbox Code Playgroud)
Dhe*_*.S. 18
在任何视图上调用任何方法时,您必须始终位于UI线程上.如果您正在处理其他线程并希望从该线程更新视图的状态,则应使用a
Handler.
在您的示例中,当您根据上述文档调用dismiss()方法时ProgressDialog,必须从UI线程执行此操作.在messageHandler实例化类Handler时HandlerThread(可能在UI线程上)初始化为a的实例.
每个
Handler实例都与一个线程和该线程的消息队列相关联.当你创建一个新的Handler,它被绑定到创建它的线程的线程/消息队列 - 从那时起,它将消息和runnables传递给该消息队列并在它们从消息队列中出来时执行它们.
因此,要从新线程与UI线程进行通信,只需将消息发布到HandlerUI线程上创建的消息.
如果View从UI线程外部调用方法,它会调用未定义的行为,这意味着它可能看起来工作正常.但它并不总能保证工作正常.
越容易越好。您可以尝试使用以下代码来代替使用处理程序:
runOnUiThread(
new Runnable() {
public void run()
{
//Update user interface here
}
}
);
Run Code Online (Sandbox Code Playgroud)
不要让生活变得复杂;)
| 归档时间: |
|
| 查看次数: |
13462 次 |
| 最近记录: |