title: Android - App crashes only on first launch but works the second time
body: <p>I am having a problem with my Android Flashlight App. The app crashes when I try to press the home button of the device while the app is opened then resuming (by clicking the app icon on home screen not recent apps button). After I terminate the app from the recent apps list then opening again, it does not crash anymore using the same instructions above.</p>
  
  <p>Please see code below.</p>
  
  <pre><code>public class MainActivity extends Settings {
  
  public Camera camera;
  public Camera.Parameters parameters;
  public ImageButton flashLightButton;
  boolean isFlashLightOn = false;
  MediaPlayer mySound;
  
  
  
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      flashLightButton = (ImageButton)findViewById(R.id.flashlight_button);
      flashLightButton.setOnClickListener(new FlashOnOffListener());
  
  
      registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
  
      mySound = MediaPlayer.create(this, R.raw.balloon_snap);
  
      if (isFlashSupported()) {
          camera = Camera.open();
          parameters = camera.getParameters();
      } else {
          showNoFlashAlert();
      }
  
      Settings.active = false;
  
      //super.onCreate(savedInstanceState);
      //Set layout we created
      //setContentView(R.layout.activity_main);
      //Register the receiver which triggers event
      //when battery charge is changed
  
  
  
  }
  
  public void settings(View view)
  {
  
      Intent intent = new Intent(MainActivity.this, Settings.class);
      startActivity(intent);
      this.finish();
  }
  
  
  private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
      @Override
      //When Event is published, onReceive method is called
      public void onReceive(Context c, Intent i) {
          //Get Battery %
          int level = i.getIntExtra("level", 0);
          //Find the progressbar creating in main.xml
          ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
          //Set progress level with battery % value
          pb.setProgress(level);
          //Find textview control created in main.xml
          TextView tv = (TextView) findViewById(R.id.textfield);
          //Set TextView with text
          tv.setText("" + Integer.toString(level) + "");
      }
  
  };
  
  public class FlashOnOffListener implements View.OnClickListener{
  
  
      SharedPreferences sharedPrefs = getSharedPreferences("VibrateSettings", MODE_PRIVATE);
      Boolean vibration = sharedPrefs.getBoolean("VibrateSet", false);
  
      SharedPreferences sharedPrefs2 = getSharedPreferences("SoundSettings", MODE_PRIVATE);
      Boolean sound = sharedPrefs2.getBoolean("SoundSet", false);
  
      @Override
      public void onClick(View v) {
  
          if(isFlashLightOn){
              flashLightButton.setImageResource(R.drawable.flashlight_off);
              parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
              camera.setParameters(parameters);
              camera.stopPreview();
              isFlashLightOn = false;
  
              if(vibration == true){
                  // Get instance of Vibrator from current Context
                  Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                  // Vibrate for 400 milliseconds
                  vib.vibrate(20);
              }
              else {
                  // Get instance of Vibrator from current Context
                  Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                  // Vibrate for 400 milliseconds
                  vib.vibrate(00);
          }
              if (sound == true){
                  mySound.start();
              }
  
          }else{
              flashLightButton.setImageResource(R.drawable.flashlight_on);
              parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
              camera.setParameters(parameters);
              camera.startPreview();
              isFlashLightOn = true;
  
              if(vibration == true){
                  // Get instance of Vibrator from current Context
                  Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                  // Vibrate for 400 milliseconds
                  vib.vibrate(20);
              }
              else {
                  // Get instance of Vibrator from current Context
                  Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                  // Vibrate for 400 milliseconds
                  vib.vibrate(00);
              }
              if (sound == true){
                  mySound.start();
              }
  
          }
  
      }
  
  }
  
  private void showNoFlashAlert() {
      new AlertDialog.Builder(this)
              .setMessage("Your device hardware does not support flashlight!")
              .setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
              .setPositiveButton("Ok", new OnClickListener() {
  
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      dialog.dismiss();
                      finish();
                  }
              }).show();
  }
  
  private boolean isFlashSupported() {
      PackageManager pm = getPackageManager();
      return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
  }
  
  
  
  @Override
  protected void onDestroy() {
      if(camera != null){
          camera.stopPreview();
          camera.release();
          camera = null;
      }
      super.onDestroy();
  }}
  </code></pre>
  
  <p>AndroidManifest.xml</p>
  
  <pre><code>&lt;uses-sdk
      android:minSdkVersion="14"
      android:targetSdkVersion="19" /&gt;
  
  &lt;uses-permission android:name="android.permission.CAMERA" /&gt;
  &lt;uses-feature android:name="android.hardware.camera" /&gt;
  &lt;uses-permission android:name="android.permission.BATTERY_STATS"/&gt;
  &lt;uses-permission android:name="android.permission.BROADCAST_STICKY"/&gt;
  &lt;uses-permission android:name="android.permission.VIBRATE"/&gt;
  
  &lt;application
      android:allowBackup="true"
      android:icon="@drawable/btn_switch_on"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" &gt;
      &lt;activity
          android:name=".MainActivity"
          android:label="@string/app_name" &gt;
          &lt;intent-filter&gt;
              &lt;action android:name="android.intent.action.MAIN" /&gt;
  
              &lt;category android:name="android.intent.category.LAUNCHER" /&gt;
          &lt;/intent-filter&gt;
      &lt;/activity&gt;
      &lt;activity
          android:name=".Settings"
          android:label="@string/app_name"&gt;
      &lt;/activity&gt;
  
  &lt;/application&gt;
  </code></pre>
  
  <p></p>
  
  <p>logcat</p>
  
  <pre><code>E/AndroidRuntime(22941): FATAL EXCEPTION: main
  
  E/AndroidRuntime(22941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.johncarlo.flashlight/com.example.johncarlo.flashlight.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread.access$600(ActivityThread.java:145)
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)
  
  E/AndroidRuntime(22941):    at android.os.Handler.dispatchMessage(Handler.java:99)
  
  E/AndroidRuntime(22941):    at android.os.Looper.loop(Looper.java:137)
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread.main(ActivityThread.java:5099)
  
  E/AndroidRuntime(22941):    at java.lang.reflect.Method.invokeNative(Native Method)
  
  E/AndroidRuntime(22941):    at java.lang.reflect.Method.invoke(Method.java:511)
  
  E/AndroidRuntime(22941):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)
  
  E/AndroidRuntime(22941):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)
  
  E/AndroidRuntime(22941):    at dalvik.system.NativeStart.main(Native Method)
  
  E/AndroidRuntime(22941): Caused by: java.lang.RuntimeException: Fail to connect to camera service
  
  E/AndroidRuntime(22941):    at android.hardware.Camera.native_setup(Native Method)
  
  E/AndroidRuntime(22941):    at android.hardware.Camera.&lt;init&gt;(Camera.java:365)
  
  E/AndroidRuntime(22941):    at android.hardware.Camera.open(Camera.java:338)
  
  E/AndroidRuntime(22941):    at com.example.johncarlo.flashlight.MainActivity.onCreate(MainActivity.java:49)
  
  E/AndroidRuntime(22941):    at android.app.Activity.performCreate(Activity.java:5117)
  
  E/AndroidRuntime(22941):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
  
  E/AndroidRuntime(22941):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)
  
  E/AndroidRuntime(22941):    ... 11 more
  
  W/ActivityManager(  786):   Force finishing activity com.example.johncarlo.flashlight/.MainActivity
  </code></pre>