0

在我的 android 中,我想显示一个无法退出的消息框,并且在显示时,需要运行另一个进程(在我的情况下是电子邮件发送功能)。然后在电子邮件发送完毕后,警报框需要关闭。

这是我到目前为止得到的,但它不起作用......

任何人都可以帮忙吗?

    AlertDialog.Builder alertDialog = new Builder(this); // create an alert box
    alertDialog.setTitle("Sending...");
    alertDialog.setMessage("Please wait while your details and image is being sent to x.");

    alertDialog.show(); // show the alert box
    Reusable_CodeActivity.send_email(gmailAC, gmpassword, get_all_details(), image_path, this);

    alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { // define the 'OK' button
        public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
        } 
    });
4

2 回答 2

2

这是您可能使用的AsyncTask的简单结构:

private class SendEmailTask extends AsyncTask<Void, Void, Void> {     
   protected void onPreExecute() {
      //Show the dialog first
   }
   protected void doInBackground(Void... params) {
      //Send Email Code
   }

   protected void onPostExecute(Void result) {
      //Dismiss the dialog 
   }
}
于 2012-08-13T00:08:28.280 回答
2

我不确定电子邮件发送部分,但我可以帮助您制作您想要的消息框。

如果您删除以下代码:

alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() { // define the 'OK' button
    public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
    } 
});

然后对话框将显示没有按钮,如果你添加.setCancelable(false)它不会被关闭,直到你告诉它,使用alertDialog.cancel();

这是一个示例(根据我的一个对话框修改):

AlertDialog.Builder builder = new AlertDialog.Builder(this); // Create the dialog object
        builder.setMessage(R.string.dialog_disclaimer_text)  // I use a reference to a string resource - it's good practice instead of using hardcoded text
               .setIcon(android.R.drawable.ic_dialog_info)   // Here I specify an icon to be displayed in the top corner
               .setTitle(R.string.dialog_disclaimer_title)
               .setCancelable(false) // This one makes the dialog stay until the dismiss is called

               .create().show(); // Show the dialog

此代码将显示一个带有文本的对话框,该对话框在活动调用之前不会消失builder.dismiss();- 然后您必须在某种侦听器中实现该对话框,或者在发送完成后进行回调。

更新

查看其他答案,这可能是您的代码应该是什么样子(感谢 iturki)

private class SendEmailTask extends AsyncTask<Void, Void, Void> {  
    AlertDialog.Builder alertDialog; // Define the AlertDialog builder object so it can be used/adressed across the entire class

    protected void onPreExecute() {
       //Show the dialog first
       alertDialog = new Builder(context);
       alertDialog.setTitle("Sending...")
                  .setMessage("Please wait while your details and image is being sent to x.");
                  .setCancelable(false)
                  .show();
    }
    protected void doInBackground(Void... params) {
       //Send Email Code
       Reusable_CodeActivity.send_email(gmailAC, gmpassword, get_all_details(), image_path, this);
    }

    protected void onPostExecute(Void result) {
       //Dismiss the dialog 
       alertDialog.dismiss();
    }
}
于 2012-08-13T00:17:18.607 回答