我的问题
如何在等待接收短信时在Android中显示进度条?
对话框应符合以下条件
我尝试了什么
public class GetSMS extends Activity {
...
...
private boolean progressDialogFlag;
private ProgressDialog progressDialog;
...
...
new SMSReceiver().execute();
}
public class SMSReceiver extends AsyncTask<Void, Integer, Void> {
protected void onPreExecute() {
// start a progressdialog box
super.onPreExecute();
progressDialogFlag = true;
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Waiting to Receive SMS...");
progressDialog.setCancelable(false);
progressDialog.show();
}
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
if (progressDialogFlag == true) {
progressDialog.setProgress(progress[0]);
}
if (progress[0] == 100 || progressDialogFlag == false) {
progressDialog.dismiss();
}
}
protected void onPostExecute(Void result) {
}
@Override
protected Void doInBackground(Void... params) {
int interval = 2;
int totalDuration = 5 * 60 * 1000; // 5 min
int sleepPeriod = (totalDuration / 100) * interval;
for (int i = 2; i <= 100; i += 2) {
publishProgress(i);
try {
Thread.sleep(sleepPeriod);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
}
smsReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
progressdialog = false;
}
}
我有什么疑问
progressDialogFlag
来解除progressDialog
导致问题。progressDialogFlag
会导致某种竞争条件。感谢您的帮助。
答案 0 :(得分:0)
可以尝试下面的东西
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
if(null!=progressDialog && progressDialog.isShowing()){
// try{
progressDialog.dismiss();
}
}
}, 5*60*1000);
但需要更多检查......
答案 1 :(得分:0)
这样做:
private ProgressDialog p;
private void sendSMS(){
p = new ProgressDialog(Context);
registerReceiver(broadcastReceiver, SMSINTENT);
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
p.dismiss();
getActivity().unregisterReceiver(this);
}
};
不知道这是否是最佳解决方案,但它确实有效!