如果我已经使用AsyncTask,如何避免主线程异常上的网络?

时间:2015-03-28 17:15:48

标签: android android-asynctask networkonmainthread asynctaskloader

在我看来,我并没有真正从MainActivity调用URL,网络操作

  • 我在另一个类ProcessData
  • 中调用url.connect()
  • 我使用doInBackground()
  • 我使用AsyncTask扩展ProcessData类

但异常仍然存在:

public class MainActivity extends ActionBarActivity {

    private final String LOG_TAG = MainActivity.class.getSimpleName();
    @Override
    protected void onCreate(Bundle savedInstanceState) {            
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ProcessData test = new ProcessData();
        test.doInBackground("mysql") ;
    }

//separate file ProcessData.java
public class ProcessData extends AsyncTask<String, Void, String> {

public String createValidUrl(String s){
       .....//code in this method works fine
}
public String doInBackground(String ...params){
        String validUrl = createValidURL(params[0]);                   
        HttpURLConnection urlConnection = null;
        BufferedReader reader = null;
        URL url = new URL(validUrl);
        urlConnection = (HttpURLConnection) url.openConnection();        
        urlConnection.setRequestMethod("GET");            
        urlConnection.connect();           

        InputStream inputStream = urlConnection.getInputStream();
        StringBuffer buffer = new StringBuffer();

        reader = new BufferedReader(new InputStreamReader(inputStream));

        String line;
            while((line = reader.readLine()) != null) {

                buffer.append(line + "\n");
            }
            urlConnection.disconnect();
            reader.close();

            return buffer.toString();
}
}

网络主线程异常仍然发生,我读了其他SO帖子。 我可以将我的http连接代码包装到新线程中,但我想找到确切的错误

2 个答案:

答案 0 :(得分:5)

您必须在execute上调用AsyncTask方法才能在后台线程中运行它。你正在做的是直接从主线程调用doInBackground

答案 1 :(得分:3)

你必须致电

test.execute();

而不是

test.doInBackground("mysql") ;