我有一项需要花费很长时间才能完成的任务。所以,我想实现一个进度对话框,旋转轮,向用户显示该任务仍在后台运行的消息。我在网上找到了很多解决方案,并使用了以下代码。我确保在单独的线程中运行任务。但它没有在UI上显示。
OnClickListener confirmPrintButtonListener = new OnClickListener() {
public void onClick(View v) {
try {
final SalesStockController salesStockController = new SalesStockController();
final ArrayList<ProductReload> productReloadList = reloadActivityAdapter
.getReloadList();
if (productReloadList.size() != 0) {
progressDialog = new ProgressDialog(StockReloadActivity.this);
progressDialog.setTitle("ABC Trading");
progressDialog.setMessage("Wait while loading...");
progressDialog.show();
new Thread(new Runnable() {
public void run()
{
// do the thing that takes a long time
try {
salesStockController.reload(productReloadList);
} catch (SQLiteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ABCException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread(new Runnable() {
public void run()
{
progressDialog.dismiss();
}
});
}
}).start();
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
finish();
}
});
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("Reload Successfully");
alert.show();
ReloadSlipPrint print = new ReloadSlipPrint(
productReloadList);
print.print();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(
v.getContext());
builder.setCancelable(false).setPositiveButton("OK", null);
AlertDialog alert = builder.create();
alert.setTitle("ABC Trading");
alert.setMessage("No Stock To Reload");
alert.show();
}
} catch (Exception e) {
ABCUtil.displayErrorMsg(v.getContext(), e);
}
}
};
有人可以指出我的代码有什么问题吗?任何帮助将非常感谢。
答案 0 :(得分:1)
刚刚为你做了一个简单的例子,你可以尝试一下。
public class MainActivity extends Activity {
private ProgressDialog mLoadingDialog;
private Handler mHandler = new Handler();
private void showLoadingDialog(final String title, final String msg) {
mHandler.post(new Runnable() {
@Override
public void run() {
if(mLoadingDialog == null) {
mLoadingDialog = ProgressDialog.show(MainActivity.this, title, msg);
}
mLoadingDialog.setTitle(title);
mLoadingDialog.setMessage(msg);
}
});
}
private void hideLoadingDialog() {
mHandler.post(new Runnable() { //Make sure it happens in sequence after showLoadingDialog
@Override
public void run() {
if(mLoadingDialog != null) {
mLoadingDialog.dismiss();
}
}
});
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread() {
@Override
public void run() {
showLoadingDialog("Loading", "Please wait...");
//DO something
hideLoadingDialog();
}
}.start();
}
}
答案 1 :(得分:1)
您可以使用AsyncTask类执行长时间运行的任务
下面是同一个
的api链接http://developer.android.com/reference/android/os/AsyncTask.html