我最近尝试创建一种在第二个线程中打开ProgressDialog的简单方法,因此如果主线程冻结,该对话框将继续工作。
这是课程:
公共类ProgressDialogThread扩展线程
{
公共活套螺纹活套;
公共处理程序mhandler;
公共进程对话框线程加载;
公共上下文对话上下文;
公共字符串对话框标题;
公共字符串dialogmessage;
public ProgressDialogThread(Context mContext, String mTitle, String mMessage)
{
DialogContext = mContext;
DialogTitle = mTitle;
DialogMessage = mMessage;
}
public void run()
{
Looper.prepare();
ThreadLooper = Looper.myLooper();
ThreadDialog = new ProgressDialog(DialogContext);
ThreadDialog.setTitle(DialogTitle);
ThreadDialog.setMessage(DialogMessage);
ThreadDialog.show();
mHandler = new Handler();
Looper.loop();
}
public void Update(final String mTitle, final String mMessage)
{
while(mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Update)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadDialog.setTitle(mTitle);
ThreadDialog.setMessage(mMessage);
}});
}
public void Dismiss()
{
while(ThreadDialog == null || mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Dismiss)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadDialog.dismiss();
}});
}
public void Continue()
{
while(ThreadLooper == null || mHandler == null)
synchronized(this) {
try { wait(10); }
catch (InterruptedException e) {
Log.d("Exception(ProgressDialogThread.Continue)", e.getMessage() == null ? "MISSING MESSAGE" : e.getMessage());
}
}
mHandler.post(new Runnable(){
@Override
public void run() {
ThreadLooper.quit();
}});
}
然而,它有时工作得很好,但有时应用程序最终会冻结并崩溃。
以下是使用示例:
ProgressDialogThread thread = new ProgressDialogThread(this, "Loading", "Please wait...");
thread.start();
// Do Stuff
thread.Dismiss();
thread.Continue();
它会产生大量警告,有时甚至会导致一些崩溃:
如。
处理程序:将消息发送到死线程….
例外情况如
在……中
原因:按键发送时间结束
谢谢你的帮助,
亚历克斯。