Android / Java:我如何实现AsyncTask?

时间:2012-05-18 12:04:18

标签: android crash android-asynctask

我制作了一个应用程序,它在指定的时间间隔内向Web服务器发送请求并获取XML数据。然后它解析XML数据,从手机获取信息(短信,联系人或类似的东西),并通过http post请求将其发送回服务器。

问题是应用程序通常需要几秒钟才能获取信息,这通常会导致应用程序崩溃。出现一个对话框,说应用程序没有响应,并询问我是否要关闭应用程序或等待,如果我按下等待它最终会再次开始工作。

AsyncTask是解决这个问题的正确方法吗?

另一件我不太了解的事情是AsyncTask实际上是如何工作的。假设我有两种方法可以完成大量工作并使应用程序崩溃,我可以将它们放在一个AsyncTask中,只需从doInBackground()中调用它们吗?

3 个答案:

答案 0 :(得分:1)

我也实现了类似的尝试。即向服务器发送请求,接收XML响应,解析XML,显示结果。 View This。我已经使用了AsyncTask。

以下是我使用AsynTask实现它的方法

private class AsyncClass extends AsyncTask<Void, Void, Bundle>{
    @Override
protected Bundle doInBackground(Void... arg0) {
    Bundle b=startProcess();        

// startBundle() method do all the processing and return result in a bundle. You can as many methods from within startBundle() method

    return b;
}       

@Override
protected void onPostExecute(Bundle result) {
    Log.d(TAG , "In onPostExecute");
    dialog.dismiss();
    if(result==null)
        Toast.makeText(cont, "Can't process query.\nTry again later.", Toast.LENGTH_LONG).show();
    else{
        Intent in = new Intent(cont, QueryResultDisplay.class);
        Log.d(TAG , "Displaying");
        in.putExtras(result);        
        cont.startActivity(in);           
    }
}

答案 1 :(得分:1)

我简要介绍一下你的问题。

您可能无法从服务器获取数据

  1. 如果您的网络速度非常慢并且您尝试获取所有内容 来自服务器和XML数据的信息,然后在这种情况下,如果网络崩溃,那么它会显示错误

  2. 如果您向不在服务器

  3. 的页面发出请求

    现在,如果您在代码中遇到问题,那么我将为您提供我在项目中实现的AsyncTask类的完整代码,它可以正常工作。

    private class GetLoginResponse extends AsyncTask<Void, Void, Boolean> {
        private ProgressDialog progressDialog;
        private String email;
        private String password;
    
        public GetLoginResponse(String emailId, String paswd) {
            this.email = emailId;
            this.password = paswd;
        }
    
        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(LoginActivity.this, "",
                    "Loading....", true, false);
        }
    
        @Override
        protected Boolean doInBackground(Void... params) {
    
            try {
                DefaultHttpClient httpclient = new DefaultHttpClient();
                HttpGet httpGet = new HttpGet(url);
                                HttpResponse response = httpclient.execute(httpGet);
            //here u can check the reponse is ok and 200 
                             } catch (NetworkException e) {
                isNetworkError = true;
            }
            return false;
        }
    
        @Override
        protected void onPostExecute(Boolean data) {
            progressDialog.dismiss();
            System.out.println("lOGIN RESPONSE for email = " + email + data);
        }
    }// end AsyncTask
    

    这可以解决您的问题。

答案 2 :(得分:0)

是的,您可以使用AsyncTask。

doInBackground()中调用的代码不得触及UI。

您可以使用publishProgress()触摸UI线程。