Launch camera and take a picture - Android Phone

Android examples for Phone:Camera

Description

Launch camera and take a picture

Demo Code


import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.MediaStore;
import android.provider.Settings;
import android.text.TextUtils;
import java.io.File;

public class Main{
    /**//w w w  .ja va 2  s. co  m
     * Launch camera and take a picture
     *
     * @param activity Activity
     * @param dir      The dir to store the picture
     * @param filename The file name of the picture
     * @param code     The code used in startActivityForResult
     * @return True if the camera start successfully, false otherwise
     */
    public static boolean takePhoto(Activity activity, String dir,
            String filename, int code) {
        String filePath = dir + filename;

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File cameraDir = new File(dir);
        LogUtils.d("filePath", filePath);
        LogUtils.d("cameraDir exist", cameraDir.exists() + "");
        if (!cameraDir.exists()) {
            return false;
        }

        File file = new File(filePath);
        Uri outputFileUri = Uri.fromFile(file);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
        try {
            activity.startActivityForResult(intent, code);
        } catch (ActivityNotFoundException e) {
            return false;
        }
        return true;
    }
}

Related Tutorials