在以3.0+为目标时,在runnable中获取NetworkOnMainThreadException

Ste*_*oen 1 multithreading android asynchronous handler networkonmainthread

由于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);
Run Code Online (Sandbox Code Playgroud)

Com*_*are 5

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