由于与ActionBarSherlock有关,我将 list 更改为目标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);
最佳答案
postDelayed()
告诉Android延迟后在主应用程序线程上运行Runnable
。它不会在后台线程上运行Runnable
。