0

我正在尝试制作一个在加载内容时弹出的进度对话框。我已经弄清楚如何使对话框出现和消失,并且可以更改其中的内容,但是我有多个异步任务,并且希望对话框在第一个异步任务开始时出现,然后在最后一个异步任务完成时消失。

对话框有没有办法知道给定活动的所有异步任务何时完成?我在如何解决这个问题上遇到问题。谢谢您的帮助!

4

1 回答 1

2

这是我用来实现相同功能的确切示例代码。

public class LoginActivity extends Activity 
{
    public static String TAG = "Login_Activity: ";

    private EditText usernameEditText;
    private EditText passwordEditText;

    private ProgressDialog progress_dialog;

    private int taskCount = 0;

    private void updateTaskCount(int value)
    {
        taskCount += value;

        if(progress_dialog != null && taskCount == 0)
        {
            progress_dialog.dismiss();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        usernameEditText = (EditText) findViewById(R.id.login_username);
        passwordEditText = (EditText) findViewById(R.id.login_password);

        progress_dialog = new ProgressDialog(this);
    }

    public void LoginClick(View view)
    {       
        String URL = "http://SOME.com/api/Members?Username=" +                        
                      usernameEditText.getText().toString()+ "&Password=" +  
                      passwordEditText.getText().toString();

         progress_dialog.setMessage("Authenticating. Please wait...");
         progress_dialog.setCancelable(false);
         progress_dialog.show();

         new AuthenticateUserFromServer().execute(URL);
         updateTaskCount(1);

         new NotifyWebService ().execute("some other url");
         updateTaskCount(1);    
    }

    protected void onDestroy()
    {
        progress_dialog.dismiss();
        super.onDestroy();
    }

    @Override
    protected void onPause()
    {
        progress_dialog.dismiss();
        super.onPause();
    }

    private class AuthenticateUserFromServer extends AsyncTask <String, Void, String> 
    {
        protected String doInBackground(String... urls)
        {
            return Utility.readJSONFromWebService(urls[0]);
        }

        protected void onPostExecute(String result) 
        {   
            // do other stuff 
            updateTaskCount(-1);
        }
    }

    private class NotifyWebService extends AsyncTask <String, Void, String> 
    {
        protected String doInBackground(String... urls)
        {
            return Utility.readJSONFromWebService(urls[0]);
        }

        protected void onPostExecute(String result) 
        {   
            // do other stuff 
            updateTaskCount(-1);
        }
    }
}

如果您有多个/单独的类用于异步任务,您可以创建一个静态实用程序类来跟踪和更新计数。

于 2013-08-10T12:33:03.657 回答