title: Audio Recording in Background throws IllegalStateException when I try to stop it
body: <p>I am creating a background audio recorder using <code>Service</code> class. When I start recording it works fine but when I stop it, it throws <code>IllegalStateException</code> on <code>onStop()</code>.</p>
  
  <p>Here is my Service Class Code:</p>
  
  <pre><code>public class AudioRecorderService extends Service {
  
      MediaRecorder mAudioRecorder;
      String fileName = null;
  
      public AudioRecorderService() {
      }
  
      @Override
      public void onCreate() {
  
      }
  
      @Override
      public int onStartCommand(Intent intent, int flags, int startId) {
  
         setupRecorder();
         Toast.makeText(this, "Recording Started", Toast.LENGTH_LONG).show();
  
  
          return START_STICKY;
      }
  
  
      private void setupRecorder(){
  
          fileName = Environment.getDataDirectory().getAbsolutePath() + "/" + "test.mp4";
  
          mAudioRecorder = new MediaRecorder();
          mAudioRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
          mAudioRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
          mAudioRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
          mAudioRecorder.setAudioEncodingBitRate(256);
          mAudioRecorder.setAudioChannels(1);
          mAudioRecorder.setAudioSamplingRate(44100);
          mAudioRecorder.setOutputFile(fileName);
  
          try {
              mAudioRecorder.prepare();
              mAudioRecorder.start();
          } catch (IOException e) {
              e.printStackTrace();
          }
      }
  
  
  
      @Nullable
      @Override
      public IBinder onBind(Intent intent) {
          return null;
      }
  
  
      @Override
      public void onDestroy() {
  
          if (mAudioRecorder != null) {
              mAudioRecorder.stop();
              mAudioRecorder.reset();
              mAudioRecorder.release();
          }
          Toast.makeText(this, "Recording Done", Toast.LENGTH_LONG).show();
      }
  
  
  }
  </code></pre>
  
  <p>I am unable to figure out what's wrong with the code. Please can anyone help????</p>