我的相机应用程序无法在kitkat上运行,但可以在其他手机上运行

时间:2018-07-17 04:59:30

标签: android

在我的kitkat设备中捕获图像后,代码会直接转到elseif条件,其中显示User cancelled image capture,而在其他api设备上也可以正常工作。

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

// key to store image path in savedInstance state
public static final String KEY_IMAGE_STORAGE_PATH = "image_path";

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

// Bitmap sampling size
public static final int BITMAP_SAMPLE_SIZE = 8;

// Gallery directory name to store the images or videos
public static final String GALLERY_DIRECTORY_NAME = "Hello Camera";

// Image and Video file extensions
public static final String IMAGE_EXTENSION = "jpg";
public static final String VIDEO_EXTENSION = "mp4";

private static String imageStoragePath;

private TextView txtDescription;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Checking availability of the camera
    if (!CameraUtils.isDeviceSupportCamera(getApplicationContext())) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device doesn't have camera
        finish();
    }

    txtDescription = findViewById(R.id.txt_desc);
    imgPreview = findViewById(R.id.imgPreview);
    videoPreview = findViewById(R.id.videoPreview);
    btnCapturePicture = findViewById(R.id.btnCapturePicture);
    btnRecordVideo = findViewById(R.id.btnRecordVideo);

    /**
     * Capture image on button click
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (CameraUtils.checkPermissions(getApplicationContext())) {
                captureImage();
            } else {
                requestCameraPermission(MEDIA_TYPE_IMAGE);
            }
        }
    });

    /**
     * Record video on button click
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (CameraUtils.checkPermissions(getApplicationContext())) {
                captureVideo();
            } else {
                requestCameraPermission(MEDIA_TYPE_VIDEO);
            }
        }
    });

    // restoring storage image path from saved instance state
    // otherwise the path will be null on device rotation
    restoreFromBundle(savedInstanceState);
}

/**
 * Restoring store image path from saved instance state
 */
private void restoreFromBundle(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_IMAGE_STORAGE_PATH)) {
            imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
            if (!TextUtils.isEmpty(imageStoragePath)) {
                if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + IMAGE_EXTENSION)) {
                    previewCapturedImage();
                } else if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + VIDEO_EXTENSION)) {
                    previewVideo();
                }
            }
        }
    }
}

/**
 * Requesting permissions using Dexter library
 */
private void requestCameraPermission(final int type) {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {

                        if (type == MEDIA_TYPE_IMAGE) {
                            // capture picture
                            captureImage();
                        } else {
                            captureVideo();
                        }

                    } else if (report.isAnyPermissionPermanentlyDenied()) {
                        showPermissionsAlert();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
}


/**
 * Capturing Camera Image will launch camera app requested image capture
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_IMAGE);
    if (file != null) {
        imageStoragePath = file.getAbsolutePath();
    }

    Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/**
 * Saving stored image path to saved instance state
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
}

/**
 * Restoring image path from saved instance state
 */
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
}

/**
 * Launching camera app to record video
 */
private void captureVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_VIDEO);
    if (file != null) {
        imageStoragePath = file.getAbsolutePath();
    }

    Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file

    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
 * Activity result method will be called after closing the camera
 */
**@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // if the result is capturing Image
    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Refreshing the gallery
            CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);
            // successfully captured the image
            Toast.makeText(this, "Image saved to:\n" +
                    data.getExtras().get("data"), Toast.LENGTH_LONG).show();
            // display it in image view
            previewCapturedImage();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Refreshing the gallery
            CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);
            // video successfully recorded
            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:\n" +
                    data.getExtras().get("data"), Toast.LENGTH_LONG).show();
            // preview the recorded video
            previewVideo();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}**

/**
 * Display image from gallery
 */
private void previewCapturedImage() {
    try {
        // hide video preview
        txtDescription.setVisibility(View.GONE);
        videoPreview.setVisibility(View.GONE);

        imgPreview.setVisibility(View.VISIBLE);

        Bitmap bitmap = CameraUtils.optimizeBitmap(BITMAP_SAMPLE_SIZE, imageStoragePath);

        imgPreview.setImageBitmap(bitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

/**
 * Displaying video in VideoView
 */
private void previewVideo() {
    try {
        // hide image preview
        txtDescription.setVisibility(View.GONE);
        imgPreview.setVisibility(View.GONE);

        videoPreview.setVisibility(View.VISIBLE);
        videoPreview.setVideoPath(imageStoragePath);
        // start playing
        videoPreview.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Alert dialog to navigate to app settings
 * to enable necessary permissions
 */
private void showPermissionsAlert() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Permissions required!")
            .setMessage("Camera needs few permissions to work properly. Grant them in settings.")
            .setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    CameraUtils.openSettings(MainActivity.this);
                }
            })
            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
}
}

2 个答案:

答案 0 :(得分:0)

  

onActivityResult当您启动的活动退出时调用,   您启动它的requestCode,返回的resultCode,   以及其中的任何其他数据。 resultCode将为   如果活动明确返回RESULT_CANCELED,则不是   返回任何结果,或在操作过程中崩溃。 RESULT_CANCELED   值是0,可能是在KitKat上未设置结果值,并且   默认返回一个。

作为KitKat的一种解决方法,您可以尝试在触发onActivityResult时检查您的应用是否为默认应用。

Android文档:Click here

有关代码,请检查以下链接:https://stackoverflow.com/a/29876919/6672577

startActivityForResult

        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // start the image capture Intent
        startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);

OnActivityResult

if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {


            Toast.makeText(this, "Image saved to:\n" +
                    data.getExtras().get("data"), Toast.LENGTH_LONG).show();
            // display it in image view
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            previewCapturedImage(photo); // pass bitmap to the method so you can preview it.
        }

previewCapturedImage

private void previewCapturedImage(Bitmap bitmap) {
    try {
        // hide video preview
        txtDescription.setVisibility(View.GONE);
        videoPreview.setVisibility(View.GONE);

        imgPreview.setVisibility(View.VISIBLE);
        imgPreview.setImageBitmap(bitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

答案 1 :(得分:0)

@星期五 让我清除所有疑问:首先,我想为每个设备(最小api 19 )和

创建一个应用

第二,我无法将previewCapturedImage()更改为previewCapturedImage(Bitmap bitmap),因为我无法通过photo作为参数,因为我必须在previewCapturedImage()中调用restoreFromBundle

package info.androidhive.androidcamera;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Telephony;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;

import com.karumi.dexter.Dexter;
import com.karumi.dexter.MultiplePermissionsReport;
import com.karumi.dexter.PermissionToken;
import com.karumi.dexter.listener.PermissionRequest;
import com.karumi.dexter.listener.multi.MultiplePermissionsListener;

import java.io.File;
import java.util.List;

public class MainActivity extends AppCompatActivity {

// Activity request codes
private static final int CAMERA_CAPTURE_IMAGE_REQUEST_CODE = 100;
private static final int CAMERA_CAPTURE_VIDEO_REQUEST_CODE = 200;

// key to store image path in savedInstance state
public static final String KEY_IMAGE_STORAGE_PATH = "image_path";

public static final int MEDIA_TYPE_IMAGE = 1;
public static final int MEDIA_TYPE_VIDEO = 2;

// Bitmap sampling size
public static final int BITMAP_SAMPLE_SIZE = 8;

// Gallery directory name to store the images or videos
public static final String GALLERY_DIRECTORY_NAME = "Hello Camera";

// Image and Video file extensions
public static final String IMAGE_EXTENSION = "jpg";
public static final String VIDEO_EXTENSION = "mp4";

private static String imageStoragePath;

private TextView txtDescription;
private ImageView imgPreview;
private VideoView videoPreview;
private Button btnCapturePicture, btnRecordVideo;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    // Checking availability of the camera
    if (!CameraUtils.isDeviceSupportCamera(getApplicationContext())) {
        Toast.makeText(getApplicationContext(),
                "Sorry! Your device doesn't support camera",
                Toast.LENGTH_LONG).show();
        // will close the app if the device doesn't have camera
        finish();
    }

    txtDescription = findViewById(R.id.txt_desc);
    imgPreview = findViewById(R.id.imgPreview);
    videoPreview = findViewById(R.id.videoPreview);
    btnCapturePicture = findViewById(R.id.btnCapturePicture);
    btnRecordVideo = findViewById(R.id.btnRecordVideo);

    /**
     * Capture image on button click
     */
    btnCapturePicture.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (CameraUtils.checkPermissions(getApplicationContext()) ||
                    Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
                captureImage();
            } else {
                requestCameraPermission(MEDIA_TYPE_IMAGE);
            }
        }
    });

    /**
     * Record video on button click
     */
    btnRecordVideo.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (CameraUtils.checkPermissions(getApplicationContext())) {
                captureVideo();
            } else {
                requestCameraPermission(MEDIA_TYPE_VIDEO);
            }
        }
    });

    // restoring storage image path from saved instance state
    // otherwise the path will be null on device rotation
    restoreFromBundle(savedInstanceState);
}

/**
 * Restoring store image path from saved instance state
 */
private void restoreFromBundle(Bundle savedInstanceState) {
    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY_IMAGE_STORAGE_PATH)) {
            imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
            if (!TextUtils.isEmpty(imageStoragePath)) {
                if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + IMAGE_EXTENSION)) {
                    previewCapturedImage(photo);
                } else if (imageStoragePath.substring(imageStoragePath.lastIndexOf(".")).equals("." + VIDEO_EXTENSION)) {
                    previewVideo();
                }
            }
        }
    }
}

/**
 * Requesting permissions using Dexter library
 */
private void requestCameraPermission(final int type) {
    Dexter.withActivity(this)
            .withPermissions(Manifest.permission.CAMERA,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE,
                    Manifest.permission.RECORD_AUDIO)
            .withListener(new MultiplePermissionsListener() {
                @Override
                public void onPermissionsChecked(MultiplePermissionsReport report) {
                    if (report.areAllPermissionsGranted()) {

                        if (type == MEDIA_TYPE_IMAGE) {
                            // capture picture
                            captureImage();
                        } else {
                            captureVideo();
                        }

                    } else if (report.isAnyPermissionPermanentlyDenied()) {
                        showPermissionsAlert();
                    }
                }

                @Override
                public void onPermissionRationaleShouldBeShown(List<PermissionRequest> permissions, PermissionToken token) {
                    token.continuePermissionRequest();
                }
            }).check();
}


/**
 * Capturing Camera Image will launch camera app requested image capture
 */
private void captureImage() {
    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    /*File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_IMAGE);
    if (file != null) {
        imageStoragePath = file.getAbsolutePath();
    }

    Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);*/

    // start the image capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_IMAGE_REQUEST_CODE);
}

/**
 * Saving stored image path to saved instance state
 */
@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    // save file url in bundle as it will be null on screen orientation
    // changes
    outState.putString(KEY_IMAGE_STORAGE_PATH, imageStoragePath);
}

/**
 * Restoring image path from saved instance state
 */
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);

    // get the file url
    imageStoragePath = savedInstanceState.getString(KEY_IMAGE_STORAGE_PATH);
}

/**
 * Launching camera app to record video
 */
private void captureVideo() {
    Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);

    File file = CameraUtils.getOutputMediaFile(MEDIA_TYPE_VIDEO);
    if (file != null) {
        imageStoragePath = file.getAbsolutePath();
    }

    Uri fileUri = CameraUtils.getOutputMediaFileUri(getApplicationContext(), file);

    // set video quality
    intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);

    intent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file

    // start the video capture Intent
    startActivityForResult(intent, CAMERA_CAPTURE_VIDEO_REQUEST_CODE);
}

/**
 * Activity result method will be called after closing the camera
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == CAMERA_CAPTURE_IMAGE_REQUEST_CODE) {

        /*if (Build.VERSION.SDK_INT == android.os.Build.VERSION_CODES.KITKAT ||
                Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && resultCode == Activity.RESULT_OK) {*/
            // if the result is capturing Image
            // Refreshing the gallery
            CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

            if (resultCode == RESULT_OK) {
            // successfully captured the image
            // display it in image view
                Bitmap photo = (Bitmap) data.getExtras().get("data");
            previewCapturedImage(photo);
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled Image capture
            Toast.makeText(getApplicationContext(),
                    "User cancelled image capture", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to capture image
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to capture image", Toast.LENGTH_SHORT)
                    .show();
        }
    } else if (requestCode == CAMERA_CAPTURE_VIDEO_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            // Refreshing the gallery
            CameraUtils.refreshGallery(getApplicationContext(), imageStoragePath);

            // video successfully recorded
            // Video captured and saved to fileUri specified in the Intent
            Toast.makeText(this, "Video saved to:\n" +
                    data.getExtras().get("data"), Toast.LENGTH_LONG).show();
            // preview the recorded video
            previewVideo();
        } else if (resultCode == RESULT_CANCELED) {
            // user cancelled recording
            Toast.makeText(getApplicationContext(),
                    "User cancelled video recording", Toast.LENGTH_SHORT)
                    .show();
        } else {
            // failed to record video
            Toast.makeText(getApplicationContext(),
                    "Sorry! Failed to record video", Toast.LENGTH_SHORT)
                    .show();
        }
    }
}


@TargetApi(Build.VERSION_CODES.KITKAT)
public static boolean isDefaultSmsApp(Context context) {
    return context.getPackageName().equals(Telephony.Sms.getDefaultSmsPackage(context));
}

/**
 * Display image from gallery
 */
private void previewCapturedImage(Bitmap bitmap) {
    try {
        // hide video preview
        txtDescription.setVisibility(View.GONE);
        videoPreview.setVisibility(View.GONE);

        imgPreview.setVisibility(View.VISIBLE);

        //Bitmap bitmap = CameraUtils.optimizeBitmap(BITMAP_SAMPLE_SIZE, imageStoragePath);

        imgPreview.setImageBitmap(bitmap);

    } catch (NullPointerException e) {
        e.printStackTrace();
    }
}

/**
 * Displaying video in VideoView
 */
private void previewVideo() {
    try {
        // hide image preview
        txtDescription.setVisibility(View.GONE);
        imgPreview.setVisibility(View.GONE);

        videoPreview.setVisibility(View.VISIBLE);
        videoPreview.setVideoPath(imageStoragePath);
        // start playing
        videoPreview.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

/**
 * Alert dialog to navigate to app settings
 * to enable necessary permissions
 */
private void showPermissionsAlert() {
    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Permissions required!")
            .setMessage("Camera needs few permissions to work properly. Grant them in settings.")
            .setPositiveButton("GOTO SETTINGS", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    CameraUtils.openSettings(MainActivity.this);
                }
            })
            .setNegativeButton("CANCEL", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            }).show();
}

}

这是 CameraUtils.java 活动,我想在其中显示捕获的图像的预览,或者可能是galleryView。

package info.androidhive.androidcamera;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Environment;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.FileProvider;
import android.util.Log;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CameraUtils {

/**
 * Refreshes gallery on adding new image/video. Gallery won't be refreshed
 * on older devices until device is rebooted
 */

public static void refreshGallery(Context context, String filePath) {
    // ScanFile so it will be appeared on Gallery
    MediaScannerConnection.scanFile(context,
            new String[]{filePath}, null,
            new MediaScannerConnection.OnScanCompletedListener() {
                public void onScanCompleted(String path, Uri uri) {
                }
            });
}

public static boolean checkPermissions(Context context) {
    return ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
            && ActivityCompat.checkSelfPermission(context, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
}

/**
 * Downsizing the bitmap to avoid OutOfMemory exceptions
 */
public static Bitmap optimizeBitmap(int sampleSize, String filePath) {
    // bitmap factory
    BitmapFactory.Options options = new BitmapFactory.Options();

    // downsizing image as it throws OutOfMemory Exception for larger
    // images
    options.inSampleSize = sampleSize;

    return BitmapFactory.decodeFile(filePath, options);
}

/**
 * Checks whether device has camera or not. This method not necessary if
 * android:required="true" is used in manifest file
 */
public static boolean isDeviceSupportCamera(Context context) {
    if (context.getPackageManager().hasSystemFeature(
            PackageManager.FEATURE_CAMERA)) {
        // this device has a camera
        return true;
    } else {
        // no camera on this device
        return false;
    }
}

/**
 * Open device app settings to allow user to enable permissions
 */
public static void openSettings(Context context) {
    Intent intent = new Intent();
    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
    intent.setData(Uri.fromParts("package", BuildConfig.APPLICATION_ID, null));
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(intent);
}

public static Uri getOutputMediaFileUri(Context context, File file) {
    return FileProvider.getUriForFile(context, context.getPackageName() + ".provider", file);
}

/**
 * Creates and returns the image or video file before opening the camera
 */
public static File getOutputMediaFile(int type) {

    // External sdcard location
    File mediaStorageDir = new File(
            Environment
                    .getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
            MainActivity.GALLERY_DIRECTORY_NAME);

    // Create the storage directory if it does not exist
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            Log.e(MainActivity.GALLERY_DIRECTORY_NAME, "Oops! Failed create "
                    + MainActivity.GALLERY_DIRECTORY_NAME + " directory");
            return null;
        }
    }

    // Preparing media file naming convention
    // adds timestamp
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
            Locale.getDefault()).format(new Date());
    File mediaFile;
    if (type == MainActivity.MEDIA_TYPE_IMAGE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "IMG_" + timeStamp + "." + MainActivity.IMAGE_EXTENSION);
    } else if (type == MainActivity.MEDIA_TYPE_VIDEO) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator
                + "VID_" + timeStamp + "." + MainActivity.VIDEO_EXTENSION);
    } else {
        return null;
    }

    return mediaFile;
}