如何在等待接收短信5分钟的同时在android中显示进度条?

时间:2012-06-13 12:17:35

标签: android android-asynctask android-dialog

我的问题

如何在等待接收短信时在Android中显示进度条?

对话框应符合以下条件

  • 对话框最多应解散5分钟。
  • 如果在5分钟之前收到短信,则应该取消对话。

我尝试了什么

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;
   }
}

我有什么疑问

  • 我认为在5分钟之前收到短信时使用progressDialogFlag来解除progressDialog导致问题。
  • 在UI和工作线程中使用变量progressDialogFlag会导致某种竞争条件。

感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

当你启动progressDialog

时,

可以尝试下面的东西

   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);

    }
};

不知道这是否是最佳解决方案,但它确实有效!

相关问题