title: How to prevent mediaplayer to stop when screen goes off?
body: <p>I have a mediaplayer in a <code>Music</code> class that is called from another secondary <code>Activity</code>. It works fine.</p>
  
  <p>But when screen goes off (either by timeout or button), the music stops playing, and when coming back and try to close the activity the program goes to "App Not Responding", because an <code>IllegalStateException</code> at a query like <code>mediaplayer.isPlaying()</code>.</p>
  
  <p>How can I prevent the mediaplayer to stop when screen goes off? </p>
  
  <p>Does it have to be through a service??</p>
  
  <p>Assuming that the answer is yes, I tried to convert the <code>Music</code> class into a service (see below). I also added <code>&lt;service android:enabled="true" android:name=".Music" /&gt;</code> into the <code>Manifest.xml</code>, and I am calling the <code>Music</code> class like this:</p>
  
  <pre><code>startService(new Intent(getBaseContext(), Music.class));
  Music track = Music(fileDescriptor);
  </code></pre>
  
  <p>The only 2 new lines in the main Activity are <code>startService(new Intent(getBaseContext(), Music.class));</code> and <code>stopService(new Intent(getBaseContext(), Music.class));</code>, together with the corresponding imports.</p>
  
  <p>But now I get <code>InstantiationException</code> error because <code>can't instantiate class</code> when trying to start the service. What am I missing?</p>
  
  <p>This is the exception:</p>
  
  <pre><code>E/AndroidRuntime(16642): FATAL EXCEPTION: main
  E/AndroidRuntime(16642): java.lang.RuntimeException: Unable to instantiate service com.floritfoto.apps.ave.Music:                                                                             java.lang.InstantiationException: can't instantiate class com.floritfoto.apps.ave.Music; no empty constructor                                                                   
  E/AndroidRuntime(16642):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2249)
  E/AndroidRuntime(16642):    at android.app.ActivityThread.access$1600(ActivityThread.java:127)
  E/AndroidRuntime(16642):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1213)
  E/AndroidRuntime(16642):    at android.os.Handler.dispatchMessage(Handler.java:99)
  E/AndroidRuntime(16642):    at android.os.Looper.loop(Looper.java:137)
  E/AndroidRuntime(16642):    at android.app.ActivityThread.main(ActivityThread.java:4507)
  E/AndroidRuntime(16642):    at java.lang.reflect.Method.invokeNative(Native Method)
  E/AndroidRuntime(16642):    at java.lang.reflect.Method.invoke(Method.java:511)
  E/AndroidRuntime(16642):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:980)
  E/AndroidRuntime(16642):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:747)
  E/AndroidRuntime(16642):    at dalvik.system.NativeStart.main(Native Method)
  E/AndroidRuntime(16642): Caused by: java.lang.InstantiationException: can't instantiate class com.floritfoto.apps.ave.Music; no empty constructor
  E/AndroidRuntime(16642):    at java.lang.Class.newInstanceImpl(Native Method)
  E/AndroidRuntime(16642):    at java.lang.Class.newInstance(Class.java:1319)
  E/AndroidRuntime(16642):    at android.app.ActivityThread.handleCreateService(ActivityThread.java:2246)
  E/AndroidRuntime(16642):    ... 10 more
  </code></pre>
  
  <p>and this is the Music.class:</p>
  
  <pre><code>package com.floritfoto.apps.ave;
  
  import java.io.FileDescriptor;
  import java.io.IOException;
  
  import android.app.Service;
  import android.content.Intent;
  import android.media.MediaPlayer;
  import android.media.MediaPlayer.OnCompletionListener;
  import android.os.IBinder;
  import android.widget.Toast;
  
  public class Music extends Service implements OnCompletionListener{
      MediaPlayer mediaPlayer;
      boolean isPrepared = false;
  
      //// TEstes de servico
      @Override
      public void onCreate() {
          super.onCreate();
          info("Servico criado!");
      }
      @Override
      public void onDestroy() {
          info("Servico fudeu!");
      }
      @Override
      public void onStart(Intent intent, int startid) {
          info("Servico started!");
      }   
      @Override
      public IBinder onBind(Intent intent) {
          return null;
      }
      public void info(String txt) {
          Toast toast = Toast.makeText(getApplicationContext(), txt, Toast.LENGTH_LONG);
          toast.show();
      }
      //// Fim testes de servico
  
      public Music(FileDescriptor fileDescriptor){
          mediaPlayer = new MediaPlayer();
          try{
              mediaPlayer.setDataSource(fileDescriptor);
              mediaPlayer.prepare();
              isPrepared = true;
              mediaPlayer.setOnCompletionListener(this);
          } catch(Exception ex){
              throw new RuntimeException("Couldn't load music, uh oh!");
          }
      }
  
      public void onCompletion(MediaPlayer mediaPlayer) {
          synchronized(this){
              isPrepared = false;
          }
      }
  
      public void play() {
          if(mediaPlayer.isPlaying()) return;
          try{
              synchronized(this){
                  if(!isPrepared){
                      mediaPlayer.prepare();
                  }
                  mediaPlayer.seekTo(0);
                  mediaPlayer.start();
              }
          } catch(IllegalStateException ex){
              ex.printStackTrace();
          } catch(IOException ex){
              ex.printStackTrace();
          }
      }
  
      public void stop() {
          mediaPlayer.stop();
          synchronized(this){
              isPrepared = false;
          }
      }
  
      public void switchTracks(){
          mediaPlayer.seekTo(0);
          mediaPlayer.pause();
      }
  
      public void pause() {
          mediaPlayer.pause();
      }
  
      public boolean isPlaying() {
          return mediaPlayer.isPlaying();
      }
  
      public boolean isLooping() {
          return mediaPlayer.isLooping();
      }
  
      public void setLooping(boolean isLooping) {
          mediaPlayer.setLooping(isLooping);
      }
  
      public void setVolume(float volumeLeft, float volumeRight) {
          mediaPlayer.setVolume(volumeLeft, volumeRight);
      }
  
      public String getDuration() {
          return String.valueOf((int)(mediaPlayer.getDuration()/1000));
      }
      public void dispose() {
          if(mediaPlayer.isPlaying()){
              stop();
          }
          mediaPlayer.release();
      }
  }
  </code></pre>