【问题标题】:Using Async for a Network activity将异步用于网络活动
【发布时间】:2016-06-10 15:25:54
【问题描述】:

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

.MainActivity}: android.os.NetworkOnMainThreadException

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

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

其余代码在异步任务中:

  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)...
  }

我应该在哪里查找我的错误?

【问题讨论】:

  • 发布您的doInBackground() 方法。
  • 您的代码应该在 doInBackground() 中,而不仅仅是您创建的某个方法

标签: android asynchronous networking android-asynctask


【解决方案1】:

网络任务应该在 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
    }
    
    }
    

【讨论】:

    【解决方案2】:

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

    你必须在doInBackgrund()中执行它们。

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多