android - 将 Async 用于网络 Activity

标签 android asynchronous networking android-asynctask

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

.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() callback method runs in a pool of background threads. To update your UI, you should implement onPostExecute(), which delivers the result from doInBackground() and runs in the UI thread, so you can safely update your 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
    }
    
    }
    

关于android - 将 Async 用于网络 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37751907/

相关文章:

android - 在此代码中插入对输入值的控制

ruby-on-rails - Sidekiq Rails 4.2 使用 Active Job 还是 Worker?有什么不同

javascript - 在 Node 函数中进行数据库调用

c# - 如何检查谁在 C# 中使用某个端口?

networking - Raspberry Pi 上使用 batman-adv 协议(protocol)的无线网状网络

Android API 21+ - 以编程方式在 TimePickerDialog 中隐藏模拟时钟

android - 单击 Android 中 Horizo​​ntalListView 内的项目

android - 网络图像在 android Flutter 中不显示

asynchronous - Flutter中可靠/持久的计时器

linux - 在 Linux 机器上运行 whois -h 时识别 IP 地址