Android中的AsyncTask或Thread

时间:2014-04-08 06:49:45

标签: android multithreading android-asynctask

我正在实现一个Android应用程序,我使用HttpResponse,HttpClient等来使用一些API调用来获取响应。如下所示:

HttpGet get = new HttpGet(targetURL); 
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(get);
String responseBody = EntityUtils.toString(response.getEntity());

在一种情况下,我想在按下Back按钮时调用API。当按下“返回”按钮时,它会转到另一个“活动”。

我应该使用onBackPressed()方法调用API吗?

我应该在onBackPressed()方法的新线程中调用API吗?

我应该使用AsyncTask来调用API吗?如果是,那么哪种方法?

最好的方法是什么?

3 个答案:

答案 0 :(得分:0)

 public void onBackPressed() {
    // TODO Auto-generated method stub
    super.onBackPressed();

 new ViewItems().execute();

 }

 public class ViewItems extends AsyncTask<Void, Void, Integer> {
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        progressDialog = ProgressDialog.show(LoginActivity.this, "Loading..",
                "Please Wait");
    }

    @Override
    protected Integer doInBackground(Void... arg0) {
        // TODO Auto-generated method stub
        HttpGet get = new HttpGet(targetURL); 
 HttpClient httpclient = new DefaultHttpClient();
 HttpResponse response = httpclient.execute(get);
 String responseBody = EntityUtils.toString(response.getEntity());
        return 0;
    }

    protected void onPostExecute(Integer result) {
        super.onPostExecute(result);

progressDialog.dismiss();

 // then your next activity code

    }

     }

答案 1 :(得分:0)

查看此代码,(通过AsyncTask)

public class getHTTP extends AsyncTask<String, Void, String>
{
    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        HttpGet get = new HttpGet(params[0]); 
        HttpClient httpclient = new DefaultHttpClient();
        HttpResponse response = httpclient.execute(get);
        String responseBody = EntityUtils.toString(response.getEntity());
        return responseBody;
    }
    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
    }
}

1:

doInBackground :  this is main method , when you execute getHTTP class for get URL, The main task this method.

2:

<String, Void, String> : these is return values and Parameter Values of doInBackground 

3:

onPreExecute : this method run before doInBackground (show alertdialog please wait)

4:

onPostExecute : this method running after doInBackground , in this method you want parse responseBody and hide alertdialog please wait.

如何使用getHTTP?

new getHTTP().execute("http://example.ex");

答案 2 :(得分:0)

我找到了问题的解决方案。

我在Thread方法的新OnBackPressed()中调用了API。

public void onBackPressed() 
{
    new Thread(new Runnable() {
    public void run() {
    //API call here
            }
        }).start();
}