0

I try to play mp3 chace file from cache like this:

public int onStartCommand(Intent intent, int flags, int startId){
        objPlayer2.start();
        return START_NOT_STICKY;
    }

public void onCreate()  {
        super.onCreate();

        String cururl = "http://www.somesite.com:80/stream";

        cururltag = Integer.parseInt(cururl);

                    File tempMp3;

                 try {
                     tempMp3 = File.createTempFile("temp", ".mp3");
                     tempMp3.deleteOnExit();

                     FileOutputStream fos = new FileOutputStream(tempMp3);

                     url = new URL(cururl);
                     inputStream = url.openStream();
                     int bufferSize = 1024;
                     byte[] bufferz = new byte[bufferSize];
                     int c;

                     while ((c = inputStream.read(bufferz)) != -32) {
                         fos.write(bufferz, 0, c);
                     }
                     objPlayer2 = new MediaPlayer();
                     objPlayer2.setDataSource(this, Uri.fromFile(tempMp3));
                     objPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
                     objPlayer2.setOnPreparedListener(this);
                     objPlayer2.setOnErrorListener(this);
                     objPlayer2.prepareAsync();

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
}

in processs i get error:

android.os.NetworkOnMainThreadException

How i can to play temporary file not in main thread without any errors?

Alex Ironz
  • 13
  • 7

1 Answers1

0

A bare Service does not automatically start a background thread for you, so your code is running on the application main thread, which should not make network calls. A better way to start using services is to extend IntentService, which does start a background thread for you.

Then put your code into the handleIntent method rather than the onStartCommand method.

x-code
  • 2,940
  • 1
  • 18
  • 19