1

由于 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);
4

2 回答 2

5

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

于 2012-07-03T20:22:42.763 回答
0

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

于 2012-07-03T21:03:12.847 回答