【问题标题】:Getting NetworkOnMainThreadException inside a runnable, when targeting 3.0+以 3.0+ 为目标时,在可运行文件中获取 NetworkOnMainThreadException
【发布时间】:2012-07-03 20:20:31
【问题描述】:

由于 ActionBarSherlock 的问题,我将 Manifest 更改为目标 API 16,从那时起,我检查当前播放歌曲的处理程序不再工作。它会在我在下面标记的行上引发 NetworkOnMainThreadException。

我做错了什么?我以为我已经正确设置了多线程。

这是我的代码:

    handler = new Handler();

    updateSongTask = new Runnable() {
        public void run() {
            Log.d("asdf", "scraper started");
            Scraper scraper = new ShoutCastScraper(); // THIS LINE throws the exception
            List<Stream> streams;
            try {
                streams = scraper.scrape(new URI(url));
                for (Stream stream : streams) {                     
                    Intent songIntent = new Intent(CUSTOM_INTENT);

                    String[] songAndArtist = songAndArtist(stream.getCurrentSong());
                    songIntent.putExtra("song", songAndArtist[0]);
                    songIntent.putExtra("artist", songAndArtist[1]);
                    songIntent.putExtra("stationurl", url);
                    sendBroadcast(songIntent);
                    Log.d("asdf", "should send broadcast" );

                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            handler.postDelayed(this, 5000);
        }
    };

    handler.postDelayed(updateSongTask, 0);

【问题讨论】:

    标签: android multithreading asynchronous handler networkonmainthread


    【解决方案1】:

    postDelayed() 告诉 Android 在延迟后在主应用程序线程上运行 Runnable。它不会在后台线程上运行Runnable

    【讨论】:

    • 哦..这很有道理!如何让它在不同的线程上运行?
    • @D_Steve595:转储Runnable 并切换到其他内容。你似乎想要定期做一些事情,所以考虑使用后台线程的TimerTimerTask。或者,如果您需要更新 UI,请使用 AsyncTask 进行设置。
    • 呃.. 太糟糕了,Handler 似乎是一种优雅的方式来做到这一点。哦,好吧,我会查一下计时器指南之类的。
    【解决方案2】:

    CommonsWare 是对的。我只是在我的处理程序中放置了一个 ASyncTask 并将我所有的歌曲更新(工作)代码移动到 doInBackground() 方法中。适用于所有版本,无网络异常!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-25
      • 1970-01-01
      • 2012-01-25
      • 1970-01-01
      • 1970-01-01
      • 2013-11-23
      • 2021-04-17
      相关资源
      最近更新 更多