gpt4 book ai didi

android - 取消 ProgressDialog 并停止线程

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:50:19 25 4
gpt4 key购买 nike

我有一个线程一次运行多个操作,我想在用户取消 ProgressDialog 时停止它。

public void run() {

//operation 1

//operation 2

//operation 3

//operation 4
}

这个线程只运行一次,所以我无法实现一个循环来检查他的线程是否应该仍在运行。

这是我的进度对话框:

//Wait dialog
m_dlgWaiting = ProgressDialog.show(m_ctxContext,
m_ctxContext.getText(R.string.app_name),
m_ctxContext.getText(R.string.msg_dlg_analyse_pic),
true, //indeterminate
true,
new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
m_bRunning = false;
}
});

由于我不知道如何停止线程,通过循环对线程的操作进行排序以查看它是否仍应运行是否正确,或者是否有更好的方法?

public void run() {
int op = 0;
while(m_bRunning) {
switch(op) {
case 0 :
//operation 1
break;
case 1 :
//operation 2
break;
case 2 :
//operation 3
break;
case 3 :
//operation 4
break;
}
op++;
}
}

即使使用此解决方案,如果线程中有太多操作,也很难对操作进行排序。有没有更好的方法来实现这一目标?

最佳答案

使用回调或AsyncTask

http://developer.android.com/reference/android/os/AsyncTask.html

final AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
private ProgressDialog dialog;

@Override
protected void onPreExecute()
{
this.dialog = new ProgressDialog(context);
this.dialog.setMessage("Loading...");
this.dialog.setCancelable(true);
this.dialog.setOnCancelListener(new DialogInterface.OnCancelListener()
{
@Override
public void onCancel(DialogInterface dialog)
{
// cancel AsyncTask
cancel(false);
}
});

this.dialog.show();

}

@Override
protected Void doInBackground(Void... params)
{
// do your stuff
return null;
}

@Override
protected void onPostExecute(Void result)
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}

@Override
protected void onCancelled()
{
//called on ui thread
if (this.dialog != null) {
this.dialog.dismiss();
}
}
};
task.execute();

关于android - 取消 ProgressDialog 并停止线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15359989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com