Jer*_*ith 4 multithreading android progressdialog
我有一个运行几次操作的线程,我想在用户取消时停止它ProgressDialog.
public void run() {
//operation 1
//operation 2
//operation 3
//operation 4
}
Run Code Online (Sandbox Code Playgroud)
这个线程只运行一次,所以我无法实现一个循环来检查他的线程是否仍然在运行.
这是我的ProgressDialog:
//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;
}
});
Run Code Online (Sandbox Code Playgroud)
由于我不知道如何停止线程,通过循环对线程的操作进行排序以查看它是否仍应该运行是否正确,还是有更好的方法?
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++;
}
}
Run Code Online (Sandbox Code Playgroud)
即使使用此解决方案,如果线程中的操作过多,则可能很难对操作进行排序.有没有更好的方法来实现这一目标?
Yar*_*lyk 10
使用回调或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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10730 次 |
| 最近记录: |