android - 每5秒在android中拍照

标签 android android-camera countdowntimer

使用相机 API,我能够成功拍摄照片并将其保存到文件夹中。这是我正在使用的代码:

主.xml:

<FrameLayout
        android:id="@+id/camera_preview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1" />

    <Button
        android:id="@+id/button_capture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:text="Capture" />

辅助类:

import java.io.IOException;

import android.content.Context;
import android.hardware.Camera;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

public class CameraPreview extends SurfaceView implements
        SurfaceHolder.Callback {
    private SurfaceHolder mSurfaceHolder;
    private Camera mCamera;

    // Constructor that obtains context and camera
    @SuppressWarnings("deprecation")
    public CameraPreview(Context context, Camera camera) {
        super(context);
        this.mCamera = camera;
        this.mSurfaceHolder = this.getHolder();
        this.mSurfaceHolder.addCallback(this);
        this.mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
    }

    @Override
    public void surfaceCreated(SurfaceHolder surfaceHolder) {
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.setDisplayOrientation(90);
            mCamera.startPreview();
        } catch (IOException e) {
            // left blank for now
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
        mCamera.stopPreview();
        mCamera.release();
    }

    @Override
    public void surfaceChanged(SurfaceHolder surfaceHolder, int format,
            int width, int height) {
        // start preview with new settings
        try {
            mCamera.setPreviewDisplay(surfaceHolder);
            mCamera.startPreview();
        } catch (Exception e) {
            // intentionally left blank for a test
        }
    }

}

Activity 类:

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class MyCamera extends Activity {
    private Camera mCamera;
    private CameraPreview mCameraPreview;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mCamera = getCameraInstance();
        mCameraPreview = new CameraPreview(this, mCamera);
        FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
        preview.addView(mCameraPreview);

        Button captureButton = (Button) findViewById(R.id.button_capture);
        captureButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mCamera.takePicture(null, null, mPicture);
            }
        });
    }

    /**
     * Helper method to access the camera returns null if it cannot get the
     * camera or does not exist
     * 
     * @return
     */
    private Camera getCameraInstance() {
        Camera camera = null;
        try {
            camera = Camera.open();
        } catch (Exception e) {
            // cannot get camera or does not exist
        }
        return camera;
    }

    PictureCallback mPicture = new PictureCallback() {
        @Override
        public void onPictureTaken(byte[] data, Camera camera) {
            File pictureFile = getOutputMediaFile();
            if (pictureFile == null) {
                return;
            }
            try {
                FileOutputStream fos = new FileOutputStream(pictureFile);
                fos.write(data);
                fos.close();
            } catch (FileNotFoundException e) {

            } catch (IOException e) {
            }
        }

    };

    private static File getOutputMediaFile() {
        File mediaStorageDir = new File(
                Environment
                        .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                "MyCameraApp");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                Log.d("MyCameraApp", "failed to create directory");
                return null;
            }
        }
        // Create a media file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss")
                .format(new Date());
        File mediaFile;
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + ".jpg");

        return mediaFile;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.my_camera, menu);
        return true;
    }

}

我还在 list 文件中添加了以下内容:

<uses-feature android:name="android.hardware.camera" />
    <uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

我有以下问题:

我想做以下事情:

  1. 按下拍摄按钮后,我希望相机使用倒计时器每 5 秒自动继续拍摄照片。所以我添加了以下内容:

    while(true){
       new CountDownTimer(5000,1000){
    
                @Override
                public void onFinish() {
                    mCamera.takePicture(null, null, mPicture);
                }
    
                @Override
                public void onTick(long millisUntilFinished) {
    
                }
    
            }.start();
    }
    

但是,我不再拍照片了。我添加了 while(true) 以使代码重复它的 not。我在没有 while(true) 的情况下尝试过,正如预期的那样,图像捕获延迟了 5 秒

第二件事是:如何改变拍摄图片的质量?

任何帮助将不胜感激。

最佳答案

删除while(true),您不需要它并且会创建无限的倒数计时器。

将您的倒计时开始更改为此

new CountDownTimer(5000,1000){

    @Override
    public void onFinish() {

    }

    @Override
    public void onTick(long millisUntilFinished) {
        mCamera.startPreview();
        mCamera.takePicture(null, null, mPicture);
    }

}.start();

onTick 在这种情况下每 1000 毫秒调用一次,而 onFinish 在 Timer 倒计时结束时调用。

如果您想每 5 秒重复一次,我认为 CountDownTimer 不符合您的需求……Timer 会更好。

Timer timer = new Timer();
timer.schedule(new TimerTask()
{
    @Override
    public void run()
    {
        mCamera.startPreview();
        mCamera.takePicture(null, null, mPicture);
    }
}, 0, 1000);

记得保存 Timer 实例来停止它!

关于android - 每5秒在android中拍照,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23045291/

相关文章:

java - 无法更新用户界面(使用 openCV)CalledFromWrongThreadException

android - 如何在动态 View 中添加/获取数据?

android - 在 Android 上写入 USB 笔驱动器需要什么权限?

android - 强制相机始终在 android 中以纵向模式打开

jquery - 创建一个 jQuery 倒数计时器,它会在间隔后重置

ios - 当我退出 View Controller 时,如何在不按停止按钮的情况下终止倒计时计时器?

Android 多联系人选择(带显示名称)

Android 前置摄像头录制视频但播放颠倒...!

android - 为什么带 handle 的连续自动对焦相机不允许切换相机闪光灯?

javascript - 如果关闭标签页,倒计时不会继续运行