Android 拍照时,结果代码始终为0/结果\u在startActivityForResult取消

Android 拍照时,结果代码始终为0/结果\u在startActivityForResult取消,android,image,Android,Image,我想拍一张不带裁剪的照片,我按照教程中的内容进行操作。这是我的班级: 首先,我制作了一个对话框来显示和获取图片 public void uploadPO() { final Dialog d = new Dialog(TransDetailActivity.this); d.requestWindowFeature(Window.FEATURE_NO_TITLE); d.getWindow().setBackgroundDrawable(new ColorDrawable

我想拍一张不带裁剪的照片,我按照教程中的内容进行操作。这是我的班级:

首先,我制作了一个对话框来显示和获取图片

public void uploadPO() {
    final Dialog d = new Dialog(TransDetailActivity.this);
    d.requestWindowFeature(Window.FEATURE_NO_TITLE);
    d.getWindow().setBackgroundDrawable(new ColorDrawable((Color.TRANSPARENT)));
    d.setContentView(R.layout.upload_po);

    final ImageView ivImage1 = (ImageView) d.findViewById(R.id.iv_image1);
    final ImageView ivImage2 = (ImageView) d.findViewById(R.id.iv_image2);
    final ImageView ivImage3 = (ImageView) d.findViewById(R.id.iv_image3);
    final ImageView ivImage4 = (ImageView) d.findViewById(R.id.iv_image4);
    ivImage1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImagePO();
            statusOnUpload = 1;
        }
    });
    ivImage2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImagePO();
            statusOnUpload = 2;
        }
    });
    ivImage3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImagePO();
            statusOnUpload = 3;
        }
    });
    ivImage4.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImagePO();
            statusOnUpload = 4;
        }
    });
    d.show();
}
下一步,我会选择拍照或从图库中选择的方法

private void selectImagePO() {
    final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Add Photo PO!");
    builder.setItems(options, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int item) {
            if (options[item].equals("Take Photo")) {
                selectFrom(PICK_FROM_CAMERA);
                /*Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                startActivityForResult(intent, 1);*/
            } else if (options[item].equals("Choose from Gallery")) {
                selectFrom(PICK_FROM_GALLERY);
                /*Intent intent = new   Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 2);*/
            } else if (options[item].equals("Cancel")) {
                dialog.dismiss();
            }
        }
    });
    builder.show();
}
接下来,基于前面的选择,我根据选择做了一个函数

    private void selectFrom(int from) {
    if (from == PICK_FROM_CAMERA) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            startActivityForResult(takePictureIntent, PICK_FROM_CAMERA);
        }
    } else {
        if(Build.VERSION.SDK_INT <19) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
        }else{
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_PICK);
            startActivityForResult(Intent.createChooser(intent, "Complete action using"), from);
        }
    }
}

我的开发有什么问题?

首先确保您在清单中拥有正确的权限。我知道您正在使用摄像头应用程序作为服务,但我认为您可能需要:

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

如果这对你没有帮助,你可以尝试使用下面的这个类。处理像照相机这样的硬件从来都不简单。我建议使用这个基本活动。我很久以前在这里的某个地方找到的。它处理一些碎片问题

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

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

public abstract class BaseCameraIntentActivity extends BaseActivity
{
    private static final String PACKAGE_NAME = "com.your.package";
    private static final String DATE_CAMERA_INTENT_STARTED_STATE =
            PACKAGE_NAME+"dateCameraIntentStarted";
    private static final String CAMERA_PIC_URI_STATE =
            PACKAGE_NAME+"CAMERA_PIC_URI_STATE";
    private static final String PHOTO_URI_STATE =
            PACKAGE_NAME+"PHOTO_URI_STATE";
    private static final String ROTATE_X_DEGREES_STATE =
            PACKAGE_NAME+"ROTATE_X_DEGREES_STATE";


    /**
     * Date and time the camera intent was started.
     */
    protected static Date dateCameraIntentStarted = null;
    /**
     * Default location where we want the photo to be ideally stored.
     */
    protected static Uri preDefinedCameraUri = null;
    /**
     * Potential 3rd location of photo data.
     */
    protected static Uri photoUriIn3rdLocation = null;
    /**
     * Retrieved location of the photo.
     */
    protected static Uri photoUri = null;
    /**
     * Orientation of the retrieved photo.
     */
    protected static int rotateXDegrees = 0;


    private final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    /**
     * Saves the current state of the activity.
     */
    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        if (dateCameraIntentStarted != null) {
            savedInstanceState.putString(
                    DATE_CAMERA_INTENT_STARTED_STATE,
                    DateHelper.dateToString(dateCameraIntentStarted));
        }
        if (preDefinedCameraUri != null) {
            savedInstanceState.putString(
                    CAMERA_PIC_URI_STATE,
                    preDefinedCameraUri.toString());
        }
        if (photoUri != null) {
            savedInstanceState.putString(
                    PHOTO_URI_STATE,
                    photoUri.toString());
        }
        savedInstanceState.putInt(
                ROTATE_X_DEGREES_STATE,
                rotateXDegrees);
    }

    /**
     * Re-initializes a saved state of the activity.
     */
    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.containsKey(DATE_CAMERA_INTENT_STARTED_STATE)) {
            dateCameraIntentStarted = DateHelper.stringToDate(
                    savedInstanceState.getString(DATE_CAMERA_INTENT_STARTED_STATE));
        }
        if (savedInstanceState.containsKey(CAMERA_PIC_URI_STATE)) {
            preDefinedCameraUri = Uri.parse(savedInstanceState.getString(CAMERA_PIC_URI_STATE));
        }
        if (savedInstanceState.containsKey(PHOTO_URI_STATE)) {
            photoUri = Uri.parse(savedInstanceState.getString(PHOTO_URI_STATE));
        }
        rotateXDegrees = savedInstanceState.getInt(ROTATE_X_DEGREES_STATE);
    }

    /**
     * Starts the camera intent depending on the device configuration.
     * <p/>
     * <b>for Samsung and Sony devices:</b>
     * We call the camera activity with the method call to startActivityForResult.
     * We only set the constant CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE. We do NOT set any other intent extras.
     * <p/>
     * <b>for all other devices:</b>
     * We call the camera activity with the method call to startActivityForResult as previously.
     * This time, however, we additionally set the intent extra MediaStore.EXTRA_OUTPUT
     * and provide an URI, where we want the image to be stored.
     * <p/>
     * In both cases we remember the time the camera activity was started.
     */
    public void startCameraIntent()
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                // NOTE: Do NOT SET: intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri)
                // on Samsung Galaxy S2/S3/.. for the following reasons:
                // 1.) it will break the correct picture orientation
                // 2.) the photo will be stored in two locations (the given path and, additionally, in the MediaStore)
                String manufacturer = android.os.Build.MANUFACTURER.toLowerCase(Locale.ENGLISH);
                String model = android.os.Build.MODEL.toLowerCase(Locale.ENGLISH);
                String buildType = android.os.Build.TYPE.toLowerCase(Locale.ENGLISH);
                String buildDevice = android.os.Build.DEVICE.toLowerCase(Locale.ENGLISH);
                String buildId = android.os.Build.ID.toLowerCase(Locale.ENGLISH);
//              String sdkVersion = android.os.Build.VERSION.RELEASE.toLowerCase(Locale.ENGLISH);

                boolean setPreDefinedCameraUri = false;
                if (!(manufacturer.contains("samsung")) && !(manufacturer.contains("sony"))) {
                    setPreDefinedCameraUri = true;
                }
                if (manufacturer.contains("samsung") && model.contains("galaxy nexus")) { //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (manufacturer.contains("samsung") && model.contains("gt-n7000") && buildId.contains("imm76l")) { //TESTED
                    setPreDefinedCameraUri = true;
                }

                if (buildType.contains("userdebug") && buildDevice.contains("ariesve")) {  //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("crespo")) {   //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9100")) { //TESTED
                    setPreDefinedCameraUri = true;
                }

                ///////////////////////////////////////////////////////////////////////////
                // TEST
                if (manufacturer.contains("samsung") && model.contains("sgh-t999l")) { //T-Mobile LTE enabled Samsung S3
                    setPreDefinedCameraUri = true;
                }
                if (buildDevice.contains("cooper")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("t0lte")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("kot49h")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("t03g")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9300")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9195")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("xperia u")) {
                    setPreDefinedCameraUri = true;
                }

                ///////////////////////////////////////////////////////////////////////////


                dateCameraIntentStarted = new Date();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (setPreDefinedCameraUri) {
//                    String filename = ImageConfig.getTempFileName();
                    String filename = System.currentTimeMillis() + ".jpg";
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.TITLE, filename);
                    preDefinedCameraUri = getContentResolver().insert(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            values);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, preDefinedCameraUri);
                }
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
            } catch (ActivityNotFoundException e) {
                logException(e);
                onCouldNotTakePhoto();
            }
        } else {
            onSdCardNotMounted();
        }
    }

    /**
     * Receives all activity results and triggers onCameraIntentResult if
     * the requestCode matches.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE: {
                onCameraIntentResult(requestCode, resultCode, intent);
                break;
            }
        }
    }


    /**
     * On camera activity result, we try to locate the photo.
     * <p/>
     * <b>Mediastore:</b>
     * First, we try to read the photo being captured from the MediaStore.
     * Using a ContentResolver on the MediaStore content, we retrieve the latest image being taken,
     * as well as its orientation property and its timestamp.
     * If we find an image and it was not taken before the camera intent was called,
     * it is the image we were looking for.
     * Otherwise, we dismiss the result and try one of the following approaches.
     * <b>Intent extra:</b>
     * Second, we try to get an image Uri from intent.getData() of the returning intent.
     * If this is not successful either, we continue with step 3.
     * <b>Default photo Uri:</b>
     * If all of the above mentioned steps did not work, we use the image Uri we passed to the camera activity.
     *
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    protected void onCameraIntentResult(int requestCode, int resultCode, Intent intent)
    {
        if (resultCode == RESULT_OK) {
            Cursor myCursor = null;
            Date dateOfPicture = null;
            try {
                // Create a Cursor to obtain the file Path for the large image
                String[] largeFileProjection = {MediaStore.Images.ImageColumns._ID,
                        MediaStore.Images.ImageColumns.DATA,
                        MediaStore.Images.ImageColumns.ORIENTATION,
                        MediaStore.Images.ImageColumns.DATE_TAKEN};
                String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
                myCursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        largeFileProjection,
                        null, null,
                        largeFileSort);
                myCursor.moveToFirst();
                if (!myCursor.isAfterLast()) {
                    // This will actually give you the file path location of the image.
                    String largeImagePath = myCursor.getString(
                            myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
                    );
                    photoUri = Uri.fromFile(new File(largeImagePath));

                    if (photoUri != null) {
                        dateOfPicture = new Date(
                                myCursor.getLong(
                                        myCursor.getColumnIndexOrThrow(
                                                MediaStore.Images.ImageColumns.DATE_TAKEN)));
                        if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) {
                            rotateXDegrees = myCursor.getInt(myCursor
                                    .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
                        } else {
                            photoUri = null;
                        }
                    }

                    if (myCursor.moveToNext() && !myCursor.isAfterLast()) {
                        String largeImagePath3rdLocation = myCursor.getString(myCursor
                                .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                        Date dateOfPicture3rdLocation = new Date(
                                myCursor.getLong(myCursor.getColumnIndexOrThrow(
                                        MediaStore.Images.ImageColumns.DATE_TAKEN))
                        );
                        if (dateOfPicture3rdLocation != null && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) {
                            photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation));
                        }
                    }
                }
            } catch (Exception e) {
                logException(e);
            } finally {
                if (myCursor != null && !myCursor.isClosed()) {
                    myCursor.close();
                }
            }

            if (photoUri == null) {
                try {
                    photoUri = intent.getData();
                } catch (Exception e) {
                }
            }

            if (photoUri == null) {
                photoUri = preDefinedCameraUri;
            }

            try {
                if (photoUri != null && new File(photoUri.getPath()).length() <= 0) {
                    if (preDefinedCameraUri != null) {
                        Uri tempUri = photoUri;
                        photoUri = preDefinedCameraUri;
                        preDefinedCameraUri = tempUri;
                    }
                }
            } catch (Exception e) {
            }

            photoUri = getFileUriFromContentUri(photoUri);
            preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri);
            try {
                if (photoUriIn3rdLocation != null) {
                    if (photoUriIn3rdLocation.equals(photoUri)
                            || photoUriIn3rdLocation.equals(preDefinedCameraUri)) {
                        photoUriIn3rdLocation = null;
                    } else {
                        photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation);
                    }
                }
            } catch (Exception e) {
            }

            if (photoUri != null) {
                onPhotoUriFound();
            } else {
                onPhotoUriNotFound();
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            onCanceled();
        } else {
            onCanceled();
        }
    }

    /**
     * Being called if the photo could be located. The photo's Uri
     * and its orientation could be retrieved.
     */
    protected void onPhotoUriFound()
    {
        logMessage("Your photo is stored under: " + photoUri.toString());
    }

    /**
     * Being called if the photo could not be located (Uri == null).
     */
    protected void onPhotoUriNotFound()
    {
        logMessage("Could not find a photoUri that is != null");
    }

    /**
     * Being called if the camera intent could not be started or something else went wrong.
     */
    protected void onCouldNotTakePhoto()
    {
        Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
    }

    /**
     * Being called if the SD card (or the internal mass storage respectively) is not mounted.
     */
    protected void onSdCardNotMounted()
    {
        Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
    }

    /**
     * Being called if the camera intent was canceled.
     */
    protected void onCanceled()
    {
        logMessage("Camera Intent was canceled");
    }

    /**
     * Logs the passed exception.
     *
     * @param exception
     */
    protected void logException(Exception exception)
    {
        logMessage(exception.toString());
    }

    /**
     * Logs the passed exception messages.
     *
     * @param exceptionMessage
     */
    protected void logMessage(String exceptionMessage)
    {
        Log.d(getClass().getName(), exceptionMessage);
    }

    /**
     * Given an Uri that is a content Uri (e.g.
     * content://media/external/images/media/1884) this function returns the
     * respective file Uri, that is e.g. file://media/external/DCIM/abc.jpg
     *
     * @param cameraPicUri
     * @return Uri
     */
    private Uri getFileUriFromContentUri(Uri cameraPicUri)
    {
        try {
            if (cameraPicUri != null
                    && cameraPicUri.toString().startsWith("content")) {
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(cameraPicUri, proj, null, null, null);
                cursor.moveToFirst();
                // This will actually give you the file path location of the image.
                String largeImagePath = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                cursor.close();
                return Uri.fromFile(new File(largeImagePath));
            }
            return cameraPicUri;
        } catch (Exception e) {
            return cameraPicUri;
        }
    }
}
导入android.app.Activity;
导入android.content.ActivityNotFoundException;
导入android.content.ContentValues;
导入android.content.Intent;
导入android.database.Cursor;
导入android.net.Uri;
导入android.os.Bundle;
导入android.os.Environment;
导入android.provider.MediaStore;
导入android.support.annotation.NonNull;
导入android.util.Log;
导入android.widget.Toast;
导入java.io.File;
导入java.util.Date;
导入java.util.Locale;
公共抽象类BaseCamerainetActivity扩展了BaseActivity
{
私有静态最终字符串包\u NAME=“com.your.PACKAGE”;
私有静态最终字符串日期\u照相机\u意图\u开始\u状态=
软件包名称+“dateCameraIntentStarted”;
私有静态最终字符串摄影机\u图片\u URI\u状态=
软件包名称+“摄像头图片URI状态”;
私有静态最终字符串PHOTO\u URI\u状态=
包名称+“照片URI状态”;
私有静态最终字符串旋转\u X\u度\u状态=
包装名称+“旋转X度状态”;
/**
*照相机意图开始的日期和时间。
*/
受保护的静态日期DateCamerainetStarted=null;
/**
*我们希望照片理想存储的默认位置。
*/
受保护的静态Uri预定义Camerauri=null;
/**
*照片数据的潜在第三位置。
*/
受保护的静态Uri photoUriIn3rdLocation=null;
/**
*检索到照片的位置。
*/
受保护的静态Uri photoUri=null;
/**
*检索到的照片的方向。
*/
受保护静态int rotateXDegrees=0;
私有最终静态整数捕获\图像\活动\请求\代码=100;
/**
*保存活动的当前状态。
*/
@凌驾
SaveInstanceState上受保护的空(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
如果(DateCamerainetEntStarted!=null){
savedInstanceState.putString(
拍摄日期、拍摄意图、开始日期、状态、,
DateHelper.dateToString(DateCamerainetEntStarted));
}
if(预定义的Camerauri!=null){
savedInstanceState.putString(
摄像机,图片,图像,状态,
预定义的camerauri.toString());
}
if(photoUri!=null){
savedInstanceState.putString(
照片(乌里州),
photoUri.toString());
}
savedInstanceState.putInt(
在状态下旋转X度,
旋转度);
}
/**
*重新初始化活动的已保存状态。
*/
@凌驾
RestoreInstanceState(@NonNull Bundle savedInstanceState)上的受保护无效
{
super.onRestoreInstanceState(savedInstanceState);
if(savedInstanceState.containsKey(日期\摄像机\意图\开始\状态)){
DateCamerainentStarted=DateHelper.stringToDate(
获取字符串(日期\照相机\意图\开始\状态));
}
if(savedInstanceState.containsKey(摄像头图片URI状态)){
预定义的camerauri=Uri.parse(savedInstanceState.getString(CAMERA_PIC_Uri_STATE));
}
if(savedInstanceState.containsKey(PHOTO_URI_STATE)){
photoUri=Uri.parse(savedInstanceState.getString(PHOTO_Uri_STATE));
}
rotateXDegrees=savedInstanceState.getInt(ROTATE_X_DEGREES_STATE);
}
/**
*根据设备配置启动摄像头。
*

*对于三星和索尼设备: *我们通过方法调用startActivityForResult来调用摄影机活动。 *我们只设置常量捕获\图像\活动\请求\代码。我们不设置任何其他额外的意图。 *

*对于所有其他设备: *如前所述,我们使用方法调用startActivityForResult来调用摄影机活动。 *但是,这次我们额外设置了intent extra MediaStore.extra_输出 *并提供一个URI,我们希望在其中存储图像。 *

*在这两种情况下,我们都记得相机活动开始的时间。 */ 公共无效开始维护() { if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ 试一试{ //注意:不要设置:intent.putExtra(MediaStore.EXTRA_输出,cameraPicUri) //三星Galaxy S2/S3/。原因如下: //1.)它将破坏正确的图片方向 //2.)照片将存储在两个位置(给定路径和MediaStore中) 字符串manufacturer=android.os.Build.manufacturer.toLowerCase(Locale.ENGLISH); String model=android.os.Build.model.toLowerCase(Locale.ENGLISH); String buildType=android.os.Build.TYPE.toLowerCase(Locale.ENGLISH); String buildDevice=android.os.Build.DEVICE.toLowerCase(Locale.ENGLISH); String buildId=android.os.Build.ID.toLowerCase(Locale.ENGLISH); //字符串sdkVersion=android.os.Bu

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;

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

public abstract class BaseCameraIntentActivity extends BaseActivity
{
    private static final String PACKAGE_NAME = "com.your.package";
    private static final String DATE_CAMERA_INTENT_STARTED_STATE =
            PACKAGE_NAME+"dateCameraIntentStarted";
    private static final String CAMERA_PIC_URI_STATE =
            PACKAGE_NAME+"CAMERA_PIC_URI_STATE";
    private static final String PHOTO_URI_STATE =
            PACKAGE_NAME+"PHOTO_URI_STATE";
    private static final String ROTATE_X_DEGREES_STATE =
            PACKAGE_NAME+"ROTATE_X_DEGREES_STATE";


    /**
     * Date and time the camera intent was started.
     */
    protected static Date dateCameraIntentStarted = null;
    /**
     * Default location where we want the photo to be ideally stored.
     */
    protected static Uri preDefinedCameraUri = null;
    /**
     * Potential 3rd location of photo data.
     */
    protected static Uri photoUriIn3rdLocation = null;
    /**
     * Retrieved location of the photo.
     */
    protected static Uri photoUri = null;
    /**
     * Orientation of the retrieved photo.
     */
    protected static int rotateXDegrees = 0;


    private final static int CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE = 100;

    /**
     * Saves the current state of the activity.
     */
    @Override
    protected void onSaveInstanceState(Bundle savedInstanceState)
    {
        super.onSaveInstanceState(savedInstanceState);
        if (dateCameraIntentStarted != null) {
            savedInstanceState.putString(
                    DATE_CAMERA_INTENT_STARTED_STATE,
                    DateHelper.dateToString(dateCameraIntentStarted));
        }
        if (preDefinedCameraUri != null) {
            savedInstanceState.putString(
                    CAMERA_PIC_URI_STATE,
                    preDefinedCameraUri.toString());
        }
        if (photoUri != null) {
            savedInstanceState.putString(
                    PHOTO_URI_STATE,
                    photoUri.toString());
        }
        savedInstanceState.putInt(
                ROTATE_X_DEGREES_STATE,
                rotateXDegrees);
    }

    /**
     * Re-initializes a saved state of the activity.
     */
    @Override
    protected void onRestoreInstanceState(@NonNull Bundle savedInstanceState)
    {
        super.onRestoreInstanceState(savedInstanceState);
        if (savedInstanceState.containsKey(DATE_CAMERA_INTENT_STARTED_STATE)) {
            dateCameraIntentStarted = DateHelper.stringToDate(
                    savedInstanceState.getString(DATE_CAMERA_INTENT_STARTED_STATE));
        }
        if (savedInstanceState.containsKey(CAMERA_PIC_URI_STATE)) {
            preDefinedCameraUri = Uri.parse(savedInstanceState.getString(CAMERA_PIC_URI_STATE));
        }
        if (savedInstanceState.containsKey(PHOTO_URI_STATE)) {
            photoUri = Uri.parse(savedInstanceState.getString(PHOTO_URI_STATE));
        }
        rotateXDegrees = savedInstanceState.getInt(ROTATE_X_DEGREES_STATE);
    }

    /**
     * Starts the camera intent depending on the device configuration.
     * <p/>
     * <b>for Samsung and Sony devices:</b>
     * We call the camera activity with the method call to startActivityForResult.
     * We only set the constant CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE. We do NOT set any other intent extras.
     * <p/>
     * <b>for all other devices:</b>
     * We call the camera activity with the method call to startActivityForResult as previously.
     * This time, however, we additionally set the intent extra MediaStore.EXTRA_OUTPUT
     * and provide an URI, where we want the image to be stored.
     * <p/>
     * In both cases we remember the time the camera activity was started.
     */
    public void startCameraIntent()
    {
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            try {
                // NOTE: Do NOT SET: intent.putExtra(MediaStore.EXTRA_OUTPUT, cameraPicUri)
                // on Samsung Galaxy S2/S3/.. for the following reasons:
                // 1.) it will break the correct picture orientation
                // 2.) the photo will be stored in two locations (the given path and, additionally, in the MediaStore)
                String manufacturer = android.os.Build.MANUFACTURER.toLowerCase(Locale.ENGLISH);
                String model = android.os.Build.MODEL.toLowerCase(Locale.ENGLISH);
                String buildType = android.os.Build.TYPE.toLowerCase(Locale.ENGLISH);
                String buildDevice = android.os.Build.DEVICE.toLowerCase(Locale.ENGLISH);
                String buildId = android.os.Build.ID.toLowerCase(Locale.ENGLISH);
//              String sdkVersion = android.os.Build.VERSION.RELEASE.toLowerCase(Locale.ENGLISH);

                boolean setPreDefinedCameraUri = false;
                if (!(manufacturer.contains("samsung")) && !(manufacturer.contains("sony"))) {
                    setPreDefinedCameraUri = true;
                }
                if (manufacturer.contains("samsung") && model.contains("galaxy nexus")) { //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (manufacturer.contains("samsung") && model.contains("gt-n7000") && buildId.contains("imm76l")) { //TESTED
                    setPreDefinedCameraUri = true;
                }

                if (buildType.contains("userdebug") && buildDevice.contains("ariesve")) {  //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("crespo")) {   //TESTED
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9100")) { //TESTED
                    setPreDefinedCameraUri = true;
                }

                ///////////////////////////////////////////////////////////////////////////
                // TEST
                if (manufacturer.contains("samsung") && model.contains("sgh-t999l")) { //T-Mobile LTE enabled Samsung S3
                    setPreDefinedCameraUri = true;
                }
                if (buildDevice.contains("cooper")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("t0lte")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("kot49h")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("t03g")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9300")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("gt-i9195")) {
                    setPreDefinedCameraUri = true;
                }
                if (buildType.contains("userdebug") && buildDevice.contains("xperia u")) {
                    setPreDefinedCameraUri = true;
                }

                ///////////////////////////////////////////////////////////////////////////


                dateCameraIntentStarted = new Date();
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                if (setPreDefinedCameraUri) {
//                    String filename = ImageConfig.getTempFileName();
                    String filename = System.currentTimeMillis() + ".jpg";
                    ContentValues values = new ContentValues();
                    values.put(MediaStore.Images.Media.TITLE, filename);
                    preDefinedCameraUri = getContentResolver().insert(
                            MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                            values);
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, preDefinedCameraUri);
                }
                startActivityForResult(intent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
            } catch (ActivityNotFoundException e) {
                logException(e);
                onCouldNotTakePhoto();
            }
        } else {
            onSdCardNotMounted();
        }
    }

    /**
     * Receives all activity results and triggers onCameraIntentResult if
     * the requestCode matches.
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
        super.onActivityResult(requestCode, resultCode, intent);
        switch (requestCode) {
            case CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE: {
                onCameraIntentResult(requestCode, resultCode, intent);
                break;
            }
        }
    }


    /**
     * On camera activity result, we try to locate the photo.
     * <p/>
     * <b>Mediastore:</b>
     * First, we try to read the photo being captured from the MediaStore.
     * Using a ContentResolver on the MediaStore content, we retrieve the latest image being taken,
     * as well as its orientation property and its timestamp.
     * If we find an image and it was not taken before the camera intent was called,
     * it is the image we were looking for.
     * Otherwise, we dismiss the result and try one of the following approaches.
     * <b>Intent extra:</b>
     * Second, we try to get an image Uri from intent.getData() of the returning intent.
     * If this is not successful either, we continue with step 3.
     * <b>Default photo Uri:</b>
     * If all of the above mentioned steps did not work, we use the image Uri we passed to the camera activity.
     *
     * @param requestCode
     * @param resultCode
     * @param intent
     */
    protected void onCameraIntentResult(int requestCode, int resultCode, Intent intent)
    {
        if (resultCode == RESULT_OK) {
            Cursor myCursor = null;
            Date dateOfPicture = null;
            try {
                // Create a Cursor to obtain the file Path for the large image
                String[] largeFileProjection = {MediaStore.Images.ImageColumns._ID,
                        MediaStore.Images.ImageColumns.DATA,
                        MediaStore.Images.ImageColumns.ORIENTATION,
                        MediaStore.Images.ImageColumns.DATE_TAKEN};
                String largeFileSort = MediaStore.Images.ImageColumns._ID + " DESC";
                myCursor = getContentResolver().query(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        largeFileProjection,
                        null, null,
                        largeFileSort);
                myCursor.moveToFirst();
                if (!myCursor.isAfterLast()) {
                    // This will actually give you the file path location of the image.
                    String largeImagePath = myCursor.getString(
                            myCursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA)
                    );
                    photoUri = Uri.fromFile(new File(largeImagePath));

                    if (photoUri != null) {
                        dateOfPicture = new Date(
                                myCursor.getLong(
                                        myCursor.getColumnIndexOrThrow(
                                                MediaStore.Images.ImageColumns.DATE_TAKEN)));
                        if (dateOfPicture != null && dateOfPicture.after(dateCameraIntentStarted)) {
                            rotateXDegrees = myCursor.getInt(myCursor
                                    .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION));
                        } else {
                            photoUri = null;
                        }
                    }

                    if (myCursor.moveToNext() && !myCursor.isAfterLast()) {
                        String largeImagePath3rdLocation = myCursor.getString(myCursor
                                .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                        Date dateOfPicture3rdLocation = new Date(
                                myCursor.getLong(myCursor.getColumnIndexOrThrow(
                                        MediaStore.Images.ImageColumns.DATE_TAKEN))
                        );
                        if (dateOfPicture3rdLocation != null && dateOfPicture3rdLocation.after(dateCameraIntentStarted)) {
                            photoUriIn3rdLocation = Uri.fromFile(new File(largeImagePath3rdLocation));
                        }
                    }
                }
            } catch (Exception e) {
                logException(e);
            } finally {
                if (myCursor != null && !myCursor.isClosed()) {
                    myCursor.close();
                }
            }

            if (photoUri == null) {
                try {
                    photoUri = intent.getData();
                } catch (Exception e) {
                }
            }

            if (photoUri == null) {
                photoUri = preDefinedCameraUri;
            }

            try {
                if (photoUri != null && new File(photoUri.getPath()).length() <= 0) {
                    if (preDefinedCameraUri != null) {
                        Uri tempUri = photoUri;
                        photoUri = preDefinedCameraUri;
                        preDefinedCameraUri = tempUri;
                    }
                }
            } catch (Exception e) {
            }

            photoUri = getFileUriFromContentUri(photoUri);
            preDefinedCameraUri = getFileUriFromContentUri(preDefinedCameraUri);
            try {
                if (photoUriIn3rdLocation != null) {
                    if (photoUriIn3rdLocation.equals(photoUri)
                            || photoUriIn3rdLocation.equals(preDefinedCameraUri)) {
                        photoUriIn3rdLocation = null;
                    } else {
                        photoUriIn3rdLocation = getFileUriFromContentUri(photoUriIn3rdLocation);
                    }
                }
            } catch (Exception e) {
            }

            if (photoUri != null) {
                onPhotoUriFound();
            } else {
                onPhotoUriNotFound();
            }
        } else if (resultCode == Activity.RESULT_CANCELED) {
            onCanceled();
        } else {
            onCanceled();
        }
    }

    /**
     * Being called if the photo could be located. The photo's Uri
     * and its orientation could be retrieved.
     */
    protected void onPhotoUriFound()
    {
        logMessage("Your photo is stored under: " + photoUri.toString());
    }

    /**
     * Being called if the photo could not be located (Uri == null).
     */
    protected void onPhotoUriNotFound()
    {
        logMessage("Could not find a photoUri that is != null");
    }

    /**
     * Being called if the camera intent could not be started or something else went wrong.
     */
    protected void onCouldNotTakePhoto()
    {
        Toast.makeText(getApplicationContext(), getString(R.string.error_could_not_take_photo), Toast.LENGTH_LONG).show();
    }

    /**
     * Being called if the SD card (or the internal mass storage respectively) is not mounted.
     */
    protected void onSdCardNotMounted()
    {
        Toast.makeText(getApplicationContext(), getString(R.string.error_sd_card_not_mounted), Toast.LENGTH_LONG).show();
    }

    /**
     * Being called if the camera intent was canceled.
     */
    protected void onCanceled()
    {
        logMessage("Camera Intent was canceled");
    }

    /**
     * Logs the passed exception.
     *
     * @param exception
     */
    protected void logException(Exception exception)
    {
        logMessage(exception.toString());
    }

    /**
     * Logs the passed exception messages.
     *
     * @param exceptionMessage
     */
    protected void logMessage(String exceptionMessage)
    {
        Log.d(getClass().getName(), exceptionMessage);
    }

    /**
     * Given an Uri that is a content Uri (e.g.
     * content://media/external/images/media/1884) this function returns the
     * respective file Uri, that is e.g. file://media/external/DCIM/abc.jpg
     *
     * @param cameraPicUri
     * @return Uri
     */
    private Uri getFileUriFromContentUri(Uri cameraPicUri)
    {
        try {
            if (cameraPicUri != null
                    && cameraPicUri.toString().startsWith("content")) {
                String[] proj = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(cameraPicUri, proj, null, null, null);
                cursor.moveToFirst();
                // This will actually give you the file path location of the image.
                String largeImagePath = cursor.getString(cursor
                        .getColumnIndexOrThrow(MediaStore.Images.ImageColumns.DATA));
                cursor.close();
                return Uri.fromFile(new File(largeImagePath));
            }
            return cameraPicUri;
        } catch (Exception e) {
            return cameraPicUri;
        }
    }
}