1. 程式人生 > >Android拍照,選擇本地圖片

Android拍照,選擇本地圖片

Android 6.0之後對許可權做出了改變,所以很多時候發現無法正常呼叫系統的功能,所以需要進行許可權的動態獲取。這裡我寫拍照和獲取本地圖片,就獲取拍照的許可權。


    /**
     * 檢查許可權
     */
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
            /**
             * 給使用者一個申請許可權的解釋,該方法只有在使用者在上一次已經拒絕過你的這個許可權申請
             */
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                toast("拍照需要得到系統的拍照許可權");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA
                        , Manifest.permission.WRITE_SETTINGS}, CHECKPERMISSION);
            } else {
                /**
                 * 申請許可權
                 */
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA
                        , Manifest.permission.WRITE_SETTINGS}, CHECKPERMISSION);
            }
        } else {
            其他處理
        }
    }
然後是拍照和獲取本地的程式碼

package com.not.getimage;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    private final static int CHECKPERMISSION = 100;

    private final static int TAKE_PHOTO = 201;
    private final static int GET_PHOTO = 202;

    Bitmap photo = null;

    ImageView imageView;

    int imagetype = 0;

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

        imageView = (ImageView) findViewById(R.id.image);

        findViewById(R.id.pz).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imagetype = 0;
                checkIsSdCard();
            }
        });
        findViewById(R.id.xz).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                imagetype = 1;
                checkPermission();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        photo = null;
        if (data != null) {
            switch (requestCode) {
                case TAKE_PHOTO:
                    if (data.getData() != null || data.getExtras() != null) {
                        Uri uri = data.getData();
                        if (uri != null) {
                            photo = BitmapFactory.decodeFile(uri.getPath());//拿到圖片
                        }
                        if (photo == null) {
                            Bundle bundle = data.getExtras();
                            if (bundle != null) {
                                photo = (Bitmap) bundle.get("data");
                            } else {
                                toast("找不到圖片");
                            }
                        }
                        imageView.setImageBitmap(photo);
                    }else {
                        toast("獲取圖片失敗");
                    }
                    break;
                case GET_PHOTO:
                    if (data.getData() != null) {
                        Uri uri = data.getData();
                        ContentResolver cr = getContentResolver();
                        if (uri != null) {
                            try {
                                photo = BitmapFactory.decodeStream(cr.openInputStream(uri));
                            } catch (Exception e) {
                                e.printStackTrace();
                                toast("獲取圖片失敗");
                            }
                        }
                        imageView.setImageBitmap(photo);
                    }else {
                        toast("獲取圖片失敗");
                    }

                    break;
            }
        }
    }

    /**
     * 檢查許可權
     */
    private void checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED
                && ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_SETTINGS) != PackageManager.PERMISSION_GRANTED) {
            /**
             * 給使用者一個申請許可權的解釋,該方法只有在使用者在上一次已經拒絕過你的這個許可權申請
             */
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
                toast("拍照需要得到系統的拍照許可權");
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA
                        , Manifest.permission.WRITE_SETTINGS}, CHECKPERMISSION);
            } else {
                /**
                 * 申請許可權
                 */
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA
                        , Manifest.permission.WRITE_SETTINGS}, CHECKPERMISSION);
            }
        } else {
            switch (imagetype) {
                case 0:
                    imageCapture();
                    break;
                case 1:
                    getPicture();
                    break;
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case CHECKPERMISSION:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
                        && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                    switch (imagetype) {
                        case 0:
                            imageCapture();
                            break;
                        case 1:
                            getPicture();
                            break;
                    }
                } else {
                    checkPermission();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void imageCapture() {
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        startActivityForResult(intent, TAKE_PHOTO);
    }

    private void getPicture() {
        Intent intent = new Intent();
        if (Build.VERSION.SDK_INT < 19) {
            intent.setAction(Intent.ACTION_GET_CONTENT);
        } else {
            intent.setAction(Intent.ACTION_OPEN_DOCUMENT);
        }
        intent.setType("image/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, GET_PHOTO);
    }

    /**
     * 檢查sd卡是否可用
     */
    private void checkIsSdCard() {
        //獲取sd卡是否可用狀態碼
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            checkPermission();
        } else {
            toast("SD卡不可用");
        }
    }

    /**
     * 通知
     *
     * @param message
     */
    private void toast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }
}