在不打开“相机”应用程序的情况下拍照

时间:2019-12-06 15:11:06

标签: java android android-camera

我目前有一个带有用于拍照的按钮的应用程序。但是,当我单击该按钮时,将打开默认的相机应用程序,然后您必须手动拍照。如何使相机应用程序无法打开,仅自动拍照并通过按应用程序中的按钮将其保存?我想按下我创建的按钮,它会拍照并自动保存。

MainActivity.java

public class MainActivity extends AppCompatActivity {

    //for taking photos
    static final int REQUEST_IMAGE_CAPTURE = 1;
    String currentPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }

    @Override
    public void onResume(){
        super.onResume();

    }

//button to start image capturing process
    public void startImageCapture(View view){

        dispatchTakePictureIntent();
        galleryAddPic();

    }

//method for taking a photo
    public void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        //Ensure that there is a camera activity to handle the intent
        if(takePictureIntent.resolveActivity(getPackageManager()) != null){
            //create the file where the photo should go
            File photoFile = null;
            try{
                photoFile = createImageFile();
            }catch(IOException e){
                Log.i("ERROR","Error in trying to create file for image");
            }
            //continue only if the file was successfully created
            if (photoFile != null){
                Uri photoURI = FileProvider.getUriForFile(this,"com.example.MyProject.provider",photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoURI);
                startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE);
            }

        }
    }


    private File createImageFile() throws IOException{
        //Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName, //prefix
                ".jpg", //suffix
                storageDir //directory
        );

        //Save a file: path for use with ACTION_VIEW intents
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void galleryAddPic(){
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(currentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    }

}

1 个答案:

答案 0 :(得分:1)

对我来说,最简单的解决方案是在应用程序内部使用相机视图(您自己的Camera2 API封装程序或现有的CameraView),使其不可见或在其上方放置一些视图。
CameraView API很简单(CameraView Getting Started):只需将视图添加到布局中,设置LifecycleOwner,在拍照时设置回调,并在需要拍照时调用 camera.takePicture()