SoFunction
Updated on 2025-04-09

Android no preview photo function

I recently got a requirement to take photos and save them in the background

public void onTakePhotoClicked() {
   final SurfaceView preview = new SurfaceView(this);
   SurfaceHolder holder = ();
   // deprecated setting, but required on Android versions prior to 3.0
(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
 (new () {
     @Override
     //The preview must happen at or after this point or takePicture fails
     public void surfaceCreated(SurfaceHolder holder) {
       (TAG, "Surface created");
        camera = null;
       try {
         camera = (.CAMERA_FACING_BACK);
         (TAG, "Opened camera");
         try {
           (holder);
         } catch (IOException e) {
           throw new RuntimeException(e);
         }
         ();
         (TAG, "Started preview");
      //Time-lapse photo shooting         (new Runnable() {
           @Override
           public void run() {
             ("zgj","Start taking pictures");
             (null, null, );
           }
         },5000);
       } catch (Exception e) {
         if (camera != null)
           ();
         throw new RuntimeException(e);
       }
     }
     @Override
     public void surfaceDestroyed(SurfaceHolder holder) {}
     @Override
     public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
   });
   WindowManager wm = (WindowManager)getSystemService(Context.WINDOW_SERVICE);
    params = new (
       1, 1, //Must be at least 1x1
       .TYPE_SYSTEM_OVERLAY,
       0,
       //Don't know if this is a safe default
       );
   //Don't set the preview visibility to GONE or INVISIBLE
   (preview, params);
 }
 @Override
 public void onPictureTaken(byte[] bytes, Camera camera) {
   ("zgj", "Photo ends");
   File pictureDir = ();
   if (pictureDir == null) {
     ("zgj",
         "Error creating media file, check storage permissions!");
     return;
   }
   try {
     String pictureName = "";
     File file = new File(pictureDir + "/pic/");
     if (!()) {
       ();
     }
     file = new File(pictureDir + "/pic/" + pictureName);
     FileOutputStream fos = new FileOutputStream(file);
     (bytes);
     ();
   } catch (FileNotFoundException e) {
     ("zgj", "File not found: " + ());
   } catch (IOException e) {
     ("zgj", "Error accessing file: " + ());
   }
 }

Summarize

The above is the Android no preview and photography feature introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!