使用Async进行网络活动

时间:2016-06-10 15:25:55

标签: android asynchronous networking android-asynctask

我知道网络任务应该在异步线程中完成,我认为我的代码在一个内部,但我仍然得到错误

.MainActivity}:android.os.NetworkOnMainThreadException

让我感到困惑,因为几乎所有内容都在异步任务中:

    public void onStart() {
        super.onStart();
        new GetRssFeedTask().execute();
    }

其余代码在Async任务中:

  private class GetRssFeedTask extends AsyncTask<Void, Void, List<String>> {
        private String getRssFeed() throws IOException {
            InputStream in = null;
            String rssFeed = null;
            try {
                URL url = new URL("http://stuffilikenet.wordpress.com/feed/main.xml");
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                in = conn.getInputStream();
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                for (int count; (count = in.read(buffer)) != -1; ) {
                    out.write(buffer, 0, count);
                }
                byte[] response = out.toByteArray();
                rssFeed = new String(response, "UTF-8");
            } finally {
                if (in != null) {
                    in.close();
                }
            }
            return rssFeed;
        }      

  ...rest of code (seriously)...
  }

我应该在哪里查找错误?

2 个答案:

答案 0 :(得分:3)

网络任务应该在doInBackground()中完成。

  

doInBackground()回调方法在后台池中运行   线程。要更新UI,您应该实现onPostExecute(),   它从doInBackground()传递结果并在UI中运行   线程,这样您就可以安全地更新UI。

  • 在onPreExecute()方法中执行启动
  • 在doInBackground()方法中执行后台任务
  • 更新onPostExecute()方法中的UI

    public class MyAyncTask extends AsyncTask<Void, Void, Void> {
    
    @Override
    protected void onPreExecute() {
        //Here you can show progress bar or something on the similar lines.
        //Since you are in a UI thread here.
        super.onPreExecute();
    }
    
    @Override
    protected Void doInBackground(Void... params) {
        // Here you are in the worker thread and you are not allowed to access UI thread from here
        //Here you can perform network operations or any heavy operations you want.
        return null;
    }
    
    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        //After completing execution of given task , control will return here.
        //Hence if you want to populate UI elements with fetched data, do it here
    }
    
    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
        // You can track you progress update here
    }
    
    }
    

答案 1 :(得分:2)

仅在AsyncTask课程中定义网络操作以在后台Thread上运行它们是不够的。

您必须在doInBackgrund()内执行它们。

您需要覆盖doInBackground()课程中的AsyncTask并在那里执行网络操作。

@Override
protected Void doInBackground(Void... params) {
    // here
    return null;
}