Android对话框和异步任务

麦克风

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

对话框是否有办法知道给定活动的所有异步任务何时完成?我在如何处理此问题上遇到问题。谢谢您的帮助!

穆罕默德·乌斯曼(Muhammad Usman)

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

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

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章