title: Android - Recording Video in the Background
body: <p>I am trying to develop an application in Android with the following feature: record video and audio seamlessly, even if the user has another application in the foreground. A common scenario for it would be: the user opens the app, starts recording, then opens a navigation app or receives a call. <strong>I want my app to keep recording</strong>.</p>
  
  <p>I have put together some code, mainly inspired by this <a href="http://developer.android.com/guide/topics/media/camera.html" rel="nofollow"><strong>tutorial</strong></a>, which will be quoted below. I have encountered two problems, however:</p>
  
  <p><strong>1. When I press the "home" key, video recording freezes, but sound is fine</strong></p>
  
  <p><strong>2. When I navigate back to the app, the preview is black</strong></p>
  
  <p><em>My questions are:</em></p>
  
  <ul>
  <li><strong>Is my goal possible on Android?</strong></li>
  <li><strong>What am I doing wrong?</strong></li>
  </ul>
  
  <p><em>My code:</em></p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>public class GlobalState extends Application {
   private boolean recording = false;
   private boolean loggingEnabled = true;
  
   private Camera serviceCamera = null;
   private CameraPreview cameraPreview = null;
  
   @Override
   public void onCreate() {
    try {
     serviceCamera = Camera.open();
    } catch (Exception e) {
  
    }
  
    super.onCreate();
   }
  
   public boolean isRecording() {
    return recording;
   }
  
   public boolean isLoggingEnabled() {
    return loggingEnabled;
   }
  
   public void setRecording(boolean recording) {
    this.recording = recording;
   }
  
   public void setCamera(Camera serviceCamera) {
    this.serviceCamera = serviceCamera;
   }
  
   public Camera getCamera() {
    return serviceCamera;
   }
  
   public void setCameraPreview(CameraPreview cameraPreview) {
    this.cameraPreview = cameraPreview;
   }
  
   public CameraPreview getCameraPreview() {
    return this.cameraPreview;
   }
  
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>public class CameraPreview extends SurfaceView implements
    SurfaceHolder.Callback {
   private SurfaceHolder mHolder;
   private Camera mCamera;
  
   private static final String TAG = "CameraPreview";
  
   public CameraPreview(Context context, Camera camera) {
    super(context);
    mCamera = camera;
  
    mHolder = getHolder();
    mHolder.addCallback(this);
    mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
   }
  
   public void surfaceCreated(SurfaceHolder holder) {
    try {
     mCamera.setPreviewDisplay(holder);
     mCamera.startPreview();
    } catch (IOException e) {
     Log.d(TAG, "Error setting camera preview: " + e.getMessage());
    }
   }
  
   public void surfaceDestroyed(SurfaceHolder holder) {
   }
  
   public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
  
    if (mHolder.getSurface() == null) {
     return;
    }
  
    try {
     mCamera.stopPreview();
    } catch (Exception e) {
    }
  
    try {
     mCamera.setPreviewDisplay(mHolder);
     mCamera.startPreview();
    } catch (Exception e) {
     Log.d(TAG, "Error starting camera preview: " + e.getMessage());
    }
   }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>public class MainActivity extends Activity {
   public String TAG = "DE-MainActivity";
  
   ImageView mRecordView;
   ImageView mMenuButtonView;
   LinearLayout mMenuView;
   TextView mVideosTextView;
   TextView mSettingsTextView;
  
   private Camera mCamera;
   private CameraPreview mPreview;
  
   GlobalState mAppState = null;
  
   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
  
    mAppState = (GlobalState) getApplicationContext();
  
    if (mAppState.isLoggingEnabled()) {
     Log.v(TAG, "Activity: onCreate");
    }
  
    mCamera = mAppState.getCamera();
    if (mAppState.getCameraPreview() == null) {
     mPreview = new CameraPreview(this, mCamera);
     mAppState.setCameraPreview(mPreview);
    }
    FrameLayout preview = (FrameLayout) findViewById(R.id.fl_camera);
    preview.addView(mPreview);
  
    mMenuView = (LinearLayout) findViewById(R.id.ll_menu_list);
    mVideosTextView = (TextView) findViewById(R.id.tv_menu_item_videos);
    mSettingsTextView = (TextView) findViewById(R.id.tv_menu_item_settings);
  
    mRecordView = (ImageView) findViewById(R.id.iv_record);
    mRecordView.setImageResource(R.drawable.btn_not_recording);
    mRecordView.setAlpha((float) 0.5);
    mRecordView.bringToFront();
    mRecordView.setOnClickListener(new View.OnClickListener() {
  
     @Override
     public void onClick(View v) {
  
      if (!mAppState.isRecording()) {
  
       mRecordView.setImageResource(R.drawable.btn_recording);
       mRecordView.setAlpha((float) 0.3);
  
       startService(new Intent(MainActivity.this,
         RecorderService.class));
  
      } else {
  
       mRecordView.setImageResource(R.drawable.btn_not_recording);
       mRecordView.setAlpha((float) 0.5);
  
       stopService(new Intent(MainActivity.this,
         RecorderService.class));
  
      }
     }
    });
  
    mMenuButtonView = (ImageView) findViewById(R.id.iv_menu);
    mMenuButtonView.setImageResource(R.drawable.btn_menu);
    mMenuButtonView.setAlpha((float) 0.5);
    mMenuButtonView.bringToFront();
    mMenuButtonView.setOnClickListener(new View.OnClickListener() {
  
     @Override
     public void onClick(View v) {
      if (mMenuView.getVisibility() == View.VISIBLE) {
       mMenuView.setVisibility(View.INVISIBLE);
      } else {
       mMenuView.setVisibility(View.VISIBLE);
      }
     }
    });
  
    mSettingsTextView.setOnClickListener(new View.OnClickListener() {
  
     @Override
     public void onClick(View v) {
      if (mAppState.isLoggingEnabled())
       Log.v(TAG, "settings clicked!");
     }
    });
  
    mVideosTextView.setOnClickListener(new View.OnClickListener() {
  
     @Override
     public void onClick(View v) {
      if (mAppState.isLoggingEnabled())
       Log.v(TAG, "videos clicked!");
     }
    });
   }
  
   @Override
   protected void onDestroy() {
    if (mAppState.isLoggingEnabled())
     Log.v(TAG, "APPLICATION EXIT!");
  
    if (mCamera != null) {
     mCamera.release(); // release the camera for other applications
     mCamera = null;
    }
  
    super.onDestroy();
   }
  
   public boolean onCreateOptionsMenu(Menu menu) {
  
    if (mMenuView.getVisibility() == View.VISIBLE) {
     mMenuView.setVisibility(View.INVISIBLE);
    } else {
     mMenuView.setVisibility(View.VISIBLE);
    }
    return false;
   }
  }</code></pre>
  </div>
  </div>
  </p>
  
  <p><div class="snippet" data-lang="js" data-hide="false">
  <div class="snippet-code">
  <pre class="snippet-code-html lang-html prettyprint-override"><code>public class RecorderService extends Service {
  
   private static final String TAG = "RecorderService";
  
   private static Camera mServiceCamera;
   private MediaRecorder mMediaRecorder;
  
   private GlobalState mAppState;
  
   public static final int MEDIA_TYPE_IMAGE = 1;
   public static final int MEDIA_TYPE_VIDEO = 2;
  
   @Override
   public void onCreate() {
    mAppState = (GlobalState) getApplicationContext();
    mServiceCamera = mAppState.getCamera();
  
    if (mAppState.isLoggingEnabled())
     Log.v(TAG, "onCreate");
  
   }
  
   @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
    super.onStartCommand(intent, flags, startId);
  
    if (!mAppState.isRecording()) {
     if (prepareVideoRecorder()) {
      mMediaRecorder.start();
      mAppState.setRecording(true);
     } else {
      releaseMediaRecorder();
     }
    }
  
    return 5;
   }
  
   @Override
   public IBinder onBind(Intent intent) {
    return null;
   }
  
   @Override
   public void onDestroy() {
    if (mAppState.isLoggingEnabled())
     Log.v(TAG, "onDestroy");
  
    // stop recording and release camera
    mMediaRecorder.stop(); // stop the recording
    releaseMediaRecorder(); // release the MediaRecorder object
    mServiceCamera.lock(); // take camera access back from MediaRecorder
  
    mAppState.setRecording(false);
  
    super.onDestroy();
   }
  
   private void releaseMediaRecorder() {
    if (mMediaRecorder != null) {
     mMediaRecorder.reset(); // clear recorder configuration
     mMediaRecorder.release(); // release the recorder object
     mMediaRecorder = null;
    }
   }
  
   /** Create a file Uri for saving an image or video */
   private static Uri getOutputMediaFileUri(int type) {
    return Uri.fromFile(getOutputMediaFile(type));
   }
  
   /** Create a File for saving an image or video */
   private static File getOutputMediaFile(int type) {
    File mediaStorageDir = new File(
      Environment.getExternalStorageDirectory(), "DashEyeApp");
  
    if (!mediaStorageDir.exists()) {
     if (!mediaStorageDir.mkdirs()) {
      Log.d("MyCameraApp", "failed to create directory");
      return null;
     }
    }
  
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
      .format(new Date());
    File mediaFile;
    if (type == MEDIA_TYPE_IMAGE) {
     mediaFile = new File(mediaStorageDir.getPath() + File.separator
       + "IMG_" + timeStamp + ".jpg");
    } else if (type == MEDIA_TYPE_VIDEO) {
     mediaFile = new File(mediaStorageDir.getPath() + File.separator
       + "VID_" + timeStamp + ".mp4");
    } else {
     return null;
    }
  
    return mediaFile;
   }
  
   private boolean prepareVideoRecorder() {
  
    mMediaRecorder = new MediaRecorder();
  
    mServiceCamera.unlock();
    mMediaRecorder.setCamera(mServiceCamera);
  
    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
  
    mMediaRecorder.setProfile(CamcorderProfile
      .get(CamcorderProfile.QUALITY_HIGH));
  
    mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO)
      .toString());
  
    // Step 5: Set the preview output
    // mMediaRecorder.setPreviewDisplay(mAppState.getCameraPreview().getHolder().getSurface());
  
    try {
     mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
     Log.d(TAG,
       "IllegalStateException preparing MediaRecorder: "
         + e.getMessage());
     releaseMediaRecorder();
     return false;
    } catch (IOException e) {
     Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
     releaseMediaRecorder();
     return false;
    }
    return true;
   }
  }</code></pre>
  </div>
  </div>
   <strong>I am sorry for the wall of text and I greatly appreciate any help!</strong></p>