title: How to Initialize camera again in Fragment?
body: <p>I am using this barcode reader code and it freezes when the app gets into onPause() phase and then back to onResume(). The camera is released when the app enters the onPause() phase so that's why it freezes. I tried to initialize camera again in onResume() but that's also called when the fragment is first called so how can I initialize my camera again? I also adviced to use onPostResume() but I couldn't use it in fragment. So can you please guide me?</p>
  
  <p>Here's the fragment:</p>
  
  <pre><code>public class BarcodeReaderFragment extends Fragment {
  
      private Camera mCamera;
      private CameraPreview mPreview;
      private Handler autoFocusHandler;
  
      TextView scanText, refreshbarcode;
      Button scanButton, homeButton;
      ImageScanner scanner;
  
      private boolean barcodeScanned = false;
      private boolean previewing = true;
  
      static {
          System.loadLibrary("iconv");
      }
      FragmentManager fragmentManager;
      FrameLayout preview;
      Typeface font;
  
      @Override
      public void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          font = Typeface.createFromAsset(getActivity().getAssets(),
                  "fontello.ttf");
      }
  
      @Override
      public View onCreateView(LayoutInflater inflater, ViewGroup container,
              Bundle savedInstanceState) {
  
          View view = inflater.inflate(R.layout.barcodereader_fragment,
                  container, false);
          getActivity().setRequestedOrientation(
                  ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
  
          ((MainActivity) getActivity()).getMenuListView()
                  .setItemChecked(0, true);
          ((MainActivity) getActivity()).getMenuListView().setSelection(0);
  
          refreshbarcode = (TextView) view.findViewById(R.id.refreshbarcode);
          refreshbarcode.setTypeface(font);
          refreshbarcode.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  fragmentManager = getActivity().getSupportFragmentManager();
                  FragmentTransaction fragmentTransaction = fragmentManager
                          .beginTransaction();
                  fragmentTransaction.replace(R.id.frame_container,
                          new BarcodeReaderFragment());
                  fragmentTransaction.commit();
              }
          });
  
          homeButton = (Button) view.findViewById(R.id.homebutton);
          homeButton.setOnClickListener(new View.OnClickListener() {
  
              @Override
              public void onClick(View v) {
                  fragmentManager = getActivity().getSupportFragmentManager();
                  FragmentTransaction fragmentTransaction = fragmentManager
                          .beginTransaction();
                  fragmentTransaction.replace(R.id.frame_container,
                          HomeFragment.newInstance());
                  fragmentTransaction.commit();
              }
          });
  
          autoFocusHandler = new Handler();
          mCamera = getCameraInstance();
  
          /* Instance barcode scanner */
          scanner = new ImageScanner();
          scanner.setConfig(0, Config.X_DENSITY, 3);
          scanner.setConfig(0, Config.Y_DENSITY, 3);
  
          mPreview = new CameraPreview(getActivity(), mCamera, previewCb,
                  autoFocusCB);
          preview = (FrameLayout) view.findViewById(R.id.cameraPreview);
          preview.addView(mPreview);
  
          scanText = (TextView) view.findViewById(R.id.scanText);
  
          fragmentManager = getActivity().getSupportFragmentManager();
  
          return view;
      }
  
      @Override
      public void onPause() {
          super.onPause();
          releaseCamera();
      }
  
      @Override
      public void onResume() {
          Log.i("DEBUG", "onResume of HomeFragment");
          getActivity().setRequestedOrientation(
                  ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
          autoFocusHandler = new Handler();
          mCamera = getCameraInstance();
  
          /* Instance barcode scanner */
          scanner = new ImageScanner();
          scanner.setConfig(0, Config.X_DENSITY, 3);
          scanner.setConfig(0, Config.Y_DENSITY, 3);
  
          mPreview = new CameraPreview(getActivity(), mCamera, previewCb,
                  autoFocusCB);
          preview.removeAllViews();
          preview.addView(mPreview);
  
          super.onResume();
      }
  
      /** A safe way to get an instance of the Camera object. */
      public static Camera getCameraInstance() {
          Camera c = null;
          try {
              c = Camera.open();
          } catch (Exception e) {
          }
          return c;
      }
  
      private void releaseCamera() {
          if (mCamera != null) {
              previewing = false;
              mCamera.setPreviewCallback(null);
              mCamera.release();
              mCamera = null;
          }
      }
  
      private Runnable doAutoFocus = new Runnable() {
          public void run() {
              if (previewing)
                  mCamera.autoFocus(autoFocusCB);
          }
      };
  
      PreviewCallback previewCb = new PreviewCallback() {
          public void onPreviewFrame(byte[] data, Camera camera) {
              Camera.Parameters parameters = camera.getParameters();
              Size size = parameters.getPreviewSize();
  
              Image barcode = new Image(size.width, size.height, "Y800");
              barcode.setData(data);
  
              int result = scanner.scanImage(barcode);
  
              if (result != 0) {
  
                  SymbolSet syms = scanner.getResults();
                  for (Symbol sym : syms) {
                      scanText.setText("Barkod Sonucu: " + sym.getData());
                      scanText.setTextColor(Color.parseColor("#00AF03"));
                      barcodeScanned = true;
                      releaseCamera();
                      Intent intent = new Intent();
                      intent.putExtra("SCAN_RESULT", sym.getData());
                      getActivity().setResult(getActivity().RESULT_OK, intent);
                  }
              }
          }
      };
  
      // Mimic continuous auto-focusing
      AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
          public void onAutoFocus(boolean success, Camera camera) {
              autoFocusHandler.postDelayed(doAutoFocus, 1000);
          }
      };
  
  }
  </code></pre>
  
  <p>CameraPreview code:</p>
  
  <pre><code>/*
   * Barebones implementation of displaying camera preview.
   * 
   * Created by lisah0 on 2012-02-24
   */
  
  
  /** A basic Camera preview class */
  public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback {
      private SurfaceHolder mHolder;
      private Camera mCamera;
      private PreviewCallback previewCallback;
      private AutoFocusCallback autoFocusCallback;
  
      public CameraPreview(Context context, Camera camera,
                           PreviewCallback previewCb,
                           AutoFocusCallback autoFocusCb) {
          super(context);
          mCamera = camera;
          previewCallback = previewCb;
          autoFocusCallback = autoFocusCb;
  
          /* 
           * Set camera to continuous focus if supported, otherwise use
           * software auto-focus. Only works for API level &gt;=9.
           */
  
          Camera.Parameters parameters = camera.getParameters();
          for (String f : parameters.getSupportedFocusModes()) {
              if (f == Parameters.FOCUS_MODE_CONTINUOUS_PICTURE) {
                  mCamera.autoFocus(autoFocusCb);
  
                  //mCamera.setFocusMode(Parameters.FOCUS_MODE_CONTINUOUS_PICTURE);
                  autoFocusCallback = null;
                  break;
              }
          }
  
  
          // Install a SurfaceHolder.Callback so we get notified when the
          // underlying surface is created and destroyed.
          mHolder = getHolder();
          mHolder.addCallback(this);
  
          // deprecated setting, but required on Android versions prior to 3.0
          mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
      }
  
      public void surfaceCreated(SurfaceHolder holder) {
          // The Surface has been created, now tell the camera where to draw the preview.
          try {
              mCamera.setPreviewDisplay(holder);
          } catch (IOException e) {
              Log.d("DBG", "Error setting camera preview: " + e.getMessage());
          }
      }
  
      public void surfaceDestroyed(SurfaceHolder holder) {
          // Camera preview released in activity
      }
  
      public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
          /*
           * If your preview can change or rotate, take care of those events here.
           * Make sure to stop the preview before resizing or reformatting it.
           */
          if (mHolder.getSurface() == null){
            // preview surface does not exist
            return;
          }
  
          // stop preview before making changes
          try {
              mCamera.stopPreview();
          } catch (Exception e){
            // ignore: tried to stop a non-existent preview
          }
  
          try {
              if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                  mCamera.setDisplayOrientation(90);              
              }
              else if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                  mCamera.setDisplayOrientation(0);
              }
  
              mCamera.setPreviewDisplay(mHolder);
              mCamera.setPreviewCallback(previewCallback);
              mCamera.startPreview();
              mCamera.autoFocus(autoFocusCallback);
          } catch (Exception e){
              Log.d("DBG", "Error starting camera preview: " + e.getMessage());
          }
      }
  }
  </code></pre>