Android 调用系统相册,系统相机,选择图片(不推荐)


Git地址
https://gitee.com/olleh/MySysAlbum.git

在这里插入图片描述

public class MainActivity extends AppCompatActivity {

    private TextView tvSelectPic;
    private final int REQUEST_CODE_PERMISSION = 33;
    private final int REQUEST_CODE_GET_IMAGE_ALBUM = 111;
    private final int REQUEST_CODE_GET_IMAGE_CAMERA = 112;
    private final int REQUEST_CODE_GET_IMAGE_CROPED = 222;

    private static final String TAG = "MainActivity";
    private ImageView imageView;

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

    public void requestAllPower2() {
        //判断是否已经赋予权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            //申请
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.CAMERA
                    },
                    REQUEST_CODE_PERMISSION);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_PERMISSION: {
                // If request is cancelled, the result arrays are empty.
                boolean isGranted = true;
                for (int i = 0; i < grantResults.length; i++) {
                    //有一个失败则失败。
                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        isGranted = false;
                        break;
                    }
                }
                if (isGranted) {
                    Log.i(TAG, "onRequestPermissionsResult granted");
                    // permission was granted, yay! Do the
                    // contacts-related task you need to do.


                } else {
                    Log.i(TAG, "onRequestPermissionsResult denied");
                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.
                    showWaringDialog();
                }
                return;
            }

            // other 'case' lines to check for other
            // permissions this app might request
        }
    }

    private void showWaringDialog() {
        AlertDialog dialog = new AlertDialog.Builder(this)
                .setTitle("警告!")
                .setMessage("请前往设置->应用->PermissionDemo->权限中打开相关权限,否则功能无法正常运行!")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 一般情况下如果用户不授权的话,功能是无法运行的,做退出处理
                        finish();
                    }
                }).show();
    }

    private void initView() {
        tvSelectPic = (TextView) findViewById(R.id.tvSelectPic);
        tvSelectPic.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myDialog();
            }
        });
        imageView = (ImageView) findViewById(R.id.imageView);
    }

    private void myDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        //设置标题
        builder.setTitle("图片来源");
        //底部的取消按钮
        builder.setNegativeButton("取消", null);
        builder.setItems(new String[]{"拍照", "相册"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    //从相机拍照
                    case 0:
                        openCamera();
                        break;
                    //从图库选择
                    case 1:
                        openAlbum();
                        break;
                }
            }
        });
        builder.create().show();
    }

    /**
     * 打开相册
     */
    private void openAlbum() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, REQUEST_CODE_GET_IMAGE_ALBUM);
    }


    File cameraFile;

    /**
     * 打开相机
     */
    private void openCamera() {
        String fileName = System.currentTimeMillis() + ".jpg";
        String dir = FileManager.get().getExternalAppFilesPath() + "/111";
        Log.e(TAG, "openCamera: " + dir);
        if (!new File(dir).exists()) {
            new File(dir).mkdirs();
        }
        cameraFile = new File(dir, fileName);
        Uri uri = UriUtils.file2Uri(cameraFile);
        //打开相机的Intent
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CODE_GET_IMAGE_CAMERA);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            //图库
            case REQUEST_CODE_GET_IMAGE_ALBUM:
                if (data != null) {
                    Uri uri = data.getData();
                    File file = UriUtils.uri2File(uri);
                    if (file != null) {
                        String absolutePath = file.getAbsolutePath();
                        Bitmap bitmap = BitmapFactory.decodeFile(absolutePath);
                        imageView.setImageBitmap(bitmap);
                    }
                }
                break;
            //相机
            case REQUEST_CODE_GET_IMAGE_CAMERA:
                if (cameraFile != null) {
                    Bitmap bitmap = BitmapFactory.decodeFile(cameraFile.getAbsolutePath());
                    if (bitmap != null) {
                        imageView.setImageBitmap(bitmap);
                    }
                }
                break;
        }
    }

}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值