Android在Activity中启动一个新进程报错:Can't create handler inside thread that has not called Looper.prepare()。

时间:2022-03-03 20:41:41

现象:

在Activity中启动一个新进程报错:Can't create handler inside thread that has not called Looper.prepare()。

源码:

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("进度对话框");
dialog.setMessage( "正在加载,请稍后...");
dialog.show();////显示进度对话框
new Thread()
{
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
};
}.start();
}
});

分析:

一般在非 UI 的线程中不允许调弹出带或者关闭对话框之类的

解决方法:

方法一、将 代码块放到Looper.prepare();和Looper.loop();中间运行

public void onClick(View v) {
// TODO Auto-generated method stub
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("进度对话框");
dialog.setMessage( "正在加载,请稍后...");
dialog.show();////显示进度对话框
new Thread()
{
public void run() {
Looper.prepare();
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
dialog.dismiss();
Looper.loop();
};
}.start();
}
});
方法二、将代码块放到主线程的 UiThread中运行

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
final ProgressDialog dialog = new ProgressDialog(MainActivity.this);
dialog.setTitle("进度对话框");
dialog.setMessage( "正在加载,请稍后...");
dialog.show();////显示进度对话框
new Thread()
{
public void run() {
try {
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

MainActivity.this.runOnUiThread(new Runnable() {
@Override
public void run() {
dialog.dismiss();
}
});

};
}.start();
}
});