为什么我的AsyncTask在主线程上进行网络操作?

时间:2015-09-13 07:51:36

标签: android android-asynctask fragment

我在片段中有一个AsyncTask,代码中没有错误,但是AsyncTask甚至在主线程上执行网络操作。 AsyncTask确实执行但我无法弄清楚它为什么在主线程上执行newtwork操作。 这是我的代码:

 public class Tappal extends ActionBarActivity implements ActionBar.TabListener {

//codes of Tappal class

public static class PlaceholderFragment extends Fragment {
    private static final String ARG_SECTION_NUMBER = "section_number";

    public static PlaceholderFragment newInstance(int sectionNumber) {
        PlaceholderFragment fragment = new PlaceholderFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_SECTION_NUMBER, sectionNumber);
        fragment.setArguments(args);
        return fragment;
    }

    public PlaceholderFragment() {
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = null;

        int position = getArguments().getInt(ARG_SECTION_NUMBER);
        if (position == 1) {Toast.LENGTH_SHORT).show();
            new MyTask().execute("key", "id");

        } else if (position == 2)
            rootView = inflater.inflate(R.layout.fragment_history, container, false);
        else
            rootView = inflater.inflate(R.layout.fragment_update, container, false);
        return rootView;
    }

    private class MyTask extends AsyncTask<String, String, HttpResponse> {
        HttpResponse httpresponse = null;
        HttpEntity httpentity = null;
        String response = null;

        protected HttpResponse doInBackground(String... params) {
            publishProgress("Getting Tappal Details...");
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://***/***/***/****/");
            try {
                httpresponse = httpclient.execute(httppost);
            } catch (Exception e) {
                publishProgress(e.toString());
            }
            return httpresponse;
        }

        protected void onProgressUpdate(String... i) {
            Toast.makeText(getActivity(), i[0], Toast.LENGTH_SHORT).show();
        }

        protected void onPostExecute(HttpResponse r) {
            try {
                httpentity = r.getEntity();
                response = EntityUtils.toString(httpentity);
                JSONObject t = new JSONObject(response);
                Toast.makeText(getActivity(), "JSON GOT", Toast.LENGTH_SHORT).show();
            } catch (Exception e) {
                Toast.makeText(getActivity(), e.toString(), Toast.LENGTH_SHORT).show();
            }
        }
    }
}

}

2 个答案:

答案 0 :(得分:1)

因为您在onPostExecute()中使用HttpResponse。 onPostExecute在主线程中工作。 试试这个:

private class MyTask extends AsyncTask<String, String, JSONObject> {
    HttpResponse httpresponse = null;
    HttpEntity httpentity = null;
    String response = null;

    protected JSONObject doInBackground(String... params) {
        publishProgress("Getting Tappal Details...");
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://***/***/***/****/");
        JSONObject t = null;
        try {
            httpresponse = httpclient.execute(httppost);
            httpentity = r.getEntity();
            response = EntityUtils.toString(httpentity);
            t = new JSONObject(response);
        } catch (Exception e) {
            publishProgress(e.toString());
        }
        return t;
    }

    protected void onProgressUpdate(String... i) {
        Toast.makeText(getActivity(), i[0], Toast.LENGTH_SHORT).show();
    }

    protected void onPostExecute(JSONObject r) {
        if(r != null){
            Toast.makeText(getActivity(), "JSON GOT", Toast.LENGTH_SHORT).show();
        //Do work with response
        }
    }
}

答案 1 :(得分:1)

检查official doc

  

onPostExecute(Result),在后台计算完成后在UI线程上调用。后台计算的结果作为参数传递给此步骤。

在您的情况下,您正在使用onPostExecute(Result)方法处理httpresponse。您必须使用doInBackground方法移动此部分代码。

您可以尝试调试代码 如果您尝试在doInBackground中使用断点,您将看到一个单独的线程。

enter image description here

在onPostExecute代码上执行相同操作,您将看到MainThread。

enter image description here