使用背景:项目中需要使用几个机器学习模型,由于加载很缓慢,所以考虑用ProgressDialog来进行提示,预测结束后dialog自动消失。
效果如下:
1.声明Handler和ProgressDialog
public ProgressDialog progressDialog;
public Handler handler = null;
2.点击事件
query.setOnClickListener(v -> {
progressDialog = new ProgressDialog(AdaBoostActivity.this);
progressDialog.setTitle("提示");
progressDialog.setMessage("正在加载...");
progressDialog.setIcon(R.drawable.running);
new Thread(){
public void run(){
try{
runOnUiThread(() -> createList());
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
}catch(Exception e){
e.printStackTrace();
}
}
}.start();//线程启动
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
ToastUtil.showMessage(AdaBoostActivity.this, "预测完成!");
}
};
progressDialog.show();
});
其中:
runOnUiThread(() -> createList());
createList()方法完成后ProgressDialog消失,因为createList()中涉及到渲染TextView,所以使用runOnUiThread()。
createList完成后handler发送消息:
Message msg = new Message();
msg.what = 1;
handler.sendMessage(msg);
然后销毁dialog:
handler = new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
progressDialog.dismiss();
ToastUtil.showMessage(AdaBoostActivity.this, "预测完成!");
}
};
3.销毁线程
@Override
protected void onDestroy() {
super.onDestroy();
if(handler != null) {
handler.removeCallbacksAndMessages(null);
}
}