Search code examples
androidmultithreadingasynchronoushandlernetworkonmainthread

Getting NetworkOnMainThreadException inside a runnable, when targeting 3.0+


I changed my Manifest to target API 16 because of a thing with ActionBarSherlock, and since then my handler that checks the currently playing song is no longer working. It throws a NetworkOnMainThreadException on the line I marked below.

What am I doing wrong? I thought I had multithreading set up right.

Here's my code:

    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);

Solution

  • postDelayed() tells Android to run the Runnable on the main application thread after a delay. It does not run the Runnable on a background thread.