android 进行拍照操作时对 onActivityResult()的封装隔离

在进行调用相机拍照功能时,需要使用到

startActivityForResult 和 onActivityResult

在实际使用时还是略微有些繁琐,比较理想的状态应当是屏蔽拍照、截屏等处理细节,调用拍照功能的Activity页面只需要调用拍照方法并获得照片路径即可

即:如 

getPhoto(params , callback(){
	onImageInfo(String imagePath){
	}
})

处理思路:

建立一个底层的BasicActivity ,调用拍照功能的Sample_Photolib继承自 BasicActivity,从而 onActivityResult操作可以在底层的 BasicActivity中完成

下面进行具体的操作:

1、建立BasicActivity

public class BasicActivity extends AppCompatActivity {


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(resultCode == RESULT_OK){
            if(listener!=null){
                listener.onResult(data);
            }
        }
        listener =null;
    }

    public void startActivityForListener(Intent intent, OnActivityResultListener onActivityResultListener){
        this.listener = onActivityResultListener;
        startActivityForResult(intent,1011);
    }

    private OnActivityResultListener listener;

    public interface  OnActivityResultListener{
        void onResult(Intent result);
    }
}
2、创建Sample_Photolib

public class Sample_Photolib extends BaseActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photolib);
        ButterKnife.bind(this);
    }

    @OnClick(R.id.btn_cropcamera)
    void cropCameraPhoto(){//拍照按钮的触发方法

        XtionPhotoService.cropCameraPhoto(this, true, new PhotoService.OnPhotoListener() {
            @Override
            public void onSelectedAlbum(String[] ids, String[] uris) {

            }

            @Override
            public void onCamera(String pic_name, String uri) {
                Toast.makeText(Sample_Photolib.this,pic_name,Toast.LENGTH_SHORT).show();
            }
        });
    }

}

3、创建PhotoService,拍照工具类

public class XtionPhotoService {

    public static OnPhotoListener listener;

    /**
     * 拍照,返回临时照片地址
     *
     * @param activity  :XtionBaseActivity
     * @param isCrop    :是否截图
     * @param onPhotoListener   :图片信息返回接口
     */
    @TargetApi(Build.VERSION_CODES.M)
    public static void cropCameraPhoto(BasicActivity activity, boolean isCrop, OnPhotoListener onPhotoListener) {
        listener = onPhotoListener;

        //先进入缓冲Activity
        Intent intent =new Intent(activity,CameraActvity.class);
        intent.putExtra("isCrop",isCrop);
        activity.startActivityForListener(intent, new BasicActivity.OnActivityResultListener() {

            @Override
            public void onResult(Intent result) {//具体的信息处理在这里完成
                String pic_name =  result.getStringExtra(PathConstant.ActivityResult_PicName);//文件名
                String pic_ComplePath= PhotoUtils.getPhotoPath(pic_name);//全路径
                listener.onCamera(pic_name,pic_ComplePath);//返回数据
            }
        });

    }

    public static void cropCameraPhoto(XtionBasicActivity activity, OnPhotoListener onPhotoListener) {
        cropCameraPhoto(activity,false,onPhotoListener);
    }

    public interface OnPhotoListener{
        //public void onCropCamera(Bitmap bitmap,FileDALEx fileDALEx);
        //public void onCropAlbum(Bitmap bitmap,FileDALEx fileDALEx);
        public void onSelectedAlbum(String[] ids ,String[] uris);
        public void onCamera(String pic_name,String uri);
    }
}


具体的获取图片操作被封装在了CameraActvity进行

以上即实现了进行拍照获取图片操作时对onActivtiyResult的隔离。


下面是CameraActvity的实现

public class CameraActvity extends Activity {

    //临时照片文件名
    public  static String pic_name = "";
    public final static int ActivityResult_CAMERA_WITH_DATA = 11111;
    public final static int ActivityResult_CAMERA_CROP_WITH_DATA = 12121;
    public final static int ActivityResult_CROP_SMALL_PICTURE = 22222;

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

        Intent intent = getIntent();
        boolean isCrop = intent.getBooleanExtra("isCrop",false);

        pic_name=cropCameraPhoto(isCrop);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        System.out.println("onSaveInstanceState");
        outState.putString("pic_name",pic_name);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        System.out.println("onRestoreInstanceState");
        pic_name=savedInstanceState.getString("pic_name");
    }

    /**
     * 拍照,返回临时照片地址
     *
     * @return String :照片名称
     */
    @TargetApi(Build.VERSION_CODES.M)
    private  String cropCameraPhoto( boolean isCrop) {
        int MaxLimit = 10;
        int retianMB = FileUtil.freeSpaceOnSd();
        if (retianMB < MaxLimit) {
            //onToastErrorMsg("存储空间不足" + MaxLimit + "M,未能获取图片");
            Toast.makeText(this, "存储空间不足" + MaxLimit + "M,未能获取图片", Toast.LENGTH_SHORT).show();
            return "";
        }
        String tempImage = null;

        try {
            tempImage = UUID.randomUUID().toString();
            File root = new File(PathConstant.IMAGEPATH);
            if (!root.exists()) {
                root.mkdir();
            }
            File directory = new File(PhotoUtils.getBasePath());
            if (!directory.exists()) {
                directory.mkdir();
            }
            File picFile = new File(PhotoUtils.getPhotoPath(tempImage));
            if (!picFile.exists()) {
                picFile.createNewFile();
            }
            Uri photoUri=Uri.fromFile(picFile);
            Intent cameraIntent =new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);

            if (Build.VERSION.SDK_INT>13){//4.0以上
                cameraIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,0);//低质量
            }
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT,photoUri);
            if (isCrop){
                startActivityForResult(cameraIntent, CameraActvity.ActivityResult_CAMERA_CROP_WITH_DATA);//拍照返回后跳至裁剪
            }else {
                startActivityForResult(cameraIntent, CameraActvity.ActivityResult_CAMERA_WITH_DATA);//拍照返回
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return tempImage;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case CameraActvity.ActivityResult_CAMERA_CROP_WITH_DATA://拍照返回后跳至裁剪
                if (resultCode==RESULT_OK){
                    Bitmap bitmap = PhotoUtils.decodeUriAsBitmap(PhotoUtils.getPhotoPath(pic_name),200);
                    int degree =PhotoUtils.readPictureDegree(PhotoUtils.getPhotoPath(pic_name));
                    //根据旋转角度,生成旋转矩阵
                    Matrix matrix=new Matrix();
                    matrix.setRotate(degree);
                    //旋转
                    int width=bitmap.getWidth();
                    int height=bitmap.getHeight();
                    bitmap=Bitmap.createBitmap(bitmap,0,0,width,height,matrix,true);
                    PhotoUtils.saveBitmap2file(bitmap,PhotoUtils.getPhotoPath(pic_name));
                    Uri uri=Uri.fromFile(new File(PhotoUtils.getPhotoPath(pic_name)));
                    cropImageUri(uri,250,250, CameraActvity.ActivityResult_CROP_SMALL_PICTURE);
                }
                break;
            /**
             * 裁剪返回
             */
            case CameraActvity.ActivityResult_CROP_SMALL_PICTURE:
                if (resultCode==RESULT_OK){
                    Bitmap bitmap= (Bitmap) data.getExtras().get("data");
                    if (PhotoUtils.saveBitmap2file(bitmap,PhotoUtils.getPhotoPath(pic_name))){//bitmap存储成file
                        setResultBack();//数据返回并关闭页面

                    }
                }
                break;
            default :
                break;
        }
    }
//    protected FileDALEx fileDALEx;

    private void cropImageUri(Uri uri, int outputX, int outputY, int requestCode) {
        Intent intent=new Intent("com.android.camera.action.CROP");//调用系统裁剪功能
        intent.setDataAndType(uri,"image/*");
        intent.putExtra("crop","true");
        intent.putExtra("aspectX",1);
        intent.putExtra("aspectY",1);
        intent.putExtra("outputX",outputX);
        intent.putExtra("outputY",outputY);
        intent.putExtra("scale",true);
        intent.putExtra(MediaStore.EXTRA_OUTPUT,PhotoUtils.getPhotoPath(pic_name));
        intent.putExtra("return-data",true);
        intent.putExtra("outputFormat",Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection",true);
        intent.putExtra("scaleUpIfNeeded", "true");
        startActivityForResult(intent,requestCode);
    }
    private  void setResultBack(){
        Intent intent = new Intent();
        intent.putExtra(PathConstant.ActivityResult_PicName,pic_name);
        setResult(RESULT_OK,intent);
        finish();
    }

}




你可能感兴趣的:(android)