FileProvider的拍照和打開相冊功能

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.cameraalbumtest">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <provider
            android:name="android.support.v4.content.FileProvider"
            android:authorities="com.example.cameraalbumtest.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true"
            >
            <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/file_paths"
                />
        </provider>
    </application>

</manifest>

res/xml/file_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <root-path name="my_images" path=""/>
</paths>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

   <Button
       android:id="@+id/take_photo"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:text="Take Photo"/>

    <Button
        android:id="@+id/choose_from_album"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Choose From Album"/>

    <ImageView
        android:id="@+id/picture"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"/>

</LinearLayout>

MainActivity.class

public class MainActivity extends AppCompatActivity {

    public static final int TAKE_PHOTO = 1;

    public static final int CHOOSE_PHOTO = 2;

    private ImageView picture;

    private Uri imageUri;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final Button takePhoto = (Button) findViewById(R.id.take_photo);
        picture = (ImageView) findViewById(R.id.picture);
        Button chooseFromAlbum = (Button) findViewById(R.id.choose_from_album);

        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //創建File對象,用於存儲拍照後的照片
                //安卓6.0 讀寫sd被稱爲危險權限 所以存到緩存目錄 而getExternalCacheDir 就可以得到這個緩存目錄
                File fileDir = getExternalCacheDir();
                File imageDir = new File(fileDir,"images");
                if(!imageDir.exists()){
                    imageDir.mkdirs();
                }
                File imageFile = new File(imageDir,"picture.jpg");

                try{
                    //判斷文件是否存在
                    if(imageFile.exists()){
                        //文件存在就刪除
                        imageFile.delete();
                    }
                    //創建圖片
                    imageFile.createNewFile();
                }catch (Exception e){
                    e.printStackTrace();
                }

                if(Build.VERSION.SDK_INT >= 24){
                    //如果設備版本大於7.0

                    imageUri = FileProvider.getUriForFile(MainActivity.this,
                            "com.example.cameraalbumtest.fileprovider",imageFile);
                } else {

                    imageUri = Uri.fromFile(imageFile);
                }

                //IMAGE_CAPTURE:圖片捕獲
                //MediaStore:媒體商店
                //EXTRA_OUTPUT:額外輸出
                Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
                intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
                startActivityForResult(intent,TAKE_PHOTO);
            }

        });

        chooseFromAlbum.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(ContextCompat.checkSelfPermission(MainActivity.this,
                   Manifest.permission.WRITE_EXTERNAL_STORAGE)!= PackageManager.PERMISSION_GRANTED){

                   ActivityCompat.requestPermissions(MainActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);

                } else {
                    openAlbum();
                }
            }
        });

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        //requestCode 發出去的請求碼   resultCode 返回的參數
        switch (requestCode){
            case 1:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    openAlbum();
                } else {
                    Toast.makeText(this,"You denied the permission",Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void openAlbum(){
        Intent intent = new Intent("android.intent.action.GET_CONTENT");
        intent.setType("image/*");
        startActivityForResult(intent,CHOOSE_PHOTO);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case TAKE_PHOTO:
                if(resultCode == RESULT_OK){
                    try{
                        //將拍攝的照片顯示出來
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageUri));
                        picture.setImageBitmap(bitmap);

                    } catch (Exception e){
                        e.printStackTrace();
                    }
                }
                break;
            case CHOOSE_PHOTO:
                if(resultCode == RESULT_OK){
                    if(Build.VERSION.SDK_INT >= 19){
                        //4.4 及以上系統使用這個方法處理圖片
                        handleImageOnKitKat(data);
                    }else{
                        //4.4 及以下系統使用這個方法處理圖片
                        handleImageBeforeKitKat(data);
                    }
                }
                break;
            default:
                break;
        }
    }

    private void handleImageOnKitKat(Intent data){
        String imagePath = null;
        Uri uri = data.getData();
        //data是從相冊返回的數據
        //android 7.1.1
        //uri == content://com.android.providers.media.documents/document/image%3A75
        //uri.getAuthority() == com.android.providers.media.documents
        //uri.getPath() == /document/image:75
        //DocumentsContract.getDocumentId(uri) == image:75
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI == content://media/external/images/media
        //真實路徑 path == /storage/emulated/0/Download/picture.jpg

        //android4.4
        //uri == content://com.android.providers.media.documents/document/image%3A28
        //uri.getAuthority() == com.android.providers.media.documents
        //uri.getPath() == /document/image:28
        //DocumentsContract.getDocumentId(uri) == image:28
        //MediaStore.Images.Media.EXTERNAL_CONTENT_URI == content://media/external/images/media
        //真實路徑 path == /storage/sdcard/images/picture.jpg

        //相冊存了圖片的id,並沒有存實際路徑。
        //Authority就是相冊數據庫的標識符,這裏有兩個數據庫,他們的標識符分別爲
        //com.android.providers.media.documents
        //com.android.providers.downloads.documents
        //當點擊一張照片它會返回document封裝了的uri,然後進行解析出資源id,
        //然後根據id在MediaStore數據庫中獲取真實URL路徑

        //判斷該Uri是否是document封裝過的
        if(DocumentsContract.isDocumentUri(this,uri)){
            //如果是document類型的Uri,則通過document id 處理
            String docId = DocumentsContract.getDocumentId(uri);
            if("com.android.providers.media.documents".equals(uri.getAuthority())){

                String id = docId.split(":")[1];
                String selection = MediaStore.Images.Media._ID + "=" +id;
                imagePath = getImagePath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, selection);

            }else if("com.android.providers.downloads.documents".equals(uri.getAuthority())){
                //這個方法負責把id和contentUri連接成一個新的Uri
                Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"),
                       Long.valueOf(docId));
                imagePath = getImagePath(contentUri, null);
            }
        }else if ("content".equalsIgnoreCase(uri.getScheme())){
            //如果是content類型的Uri,則使用普通方式處理
            imagePath =getImagePath(uri,null);

        }else if("file".equalsIgnoreCase(uri.getScheme())){
            //如果是file類型的Uri,直接獲取圖片路徑即可
            imagePath = uri.getPath();
        }

        displayImage(imagePath);
    }

    private void handleImageBeforeKitKat(Intent data) {
        Uri uri = data.getData();
        String imagePath = getImagePath(uri, null);
        displayImage(imagePath);
    }

    private String getImagePath(Uri uri, String selection){
        String path = null;
        //通過Uri和selection來獲取真實路徑
        //Android系統提供了MediaScanner,MediaProvider,MediaStore等接口,並且提供了一套數據庫
        //表格,通過Content Provider的方式提供給用戶。當手機開機或者有SD卡插拔等事件發生時,系統
        //將會自動掃描SD卡和手機內存上的媒體文件,如audio,video,圖片等,將相應的信息放到定義好
        //的數據庫表格中。在這個程序中,我們不需要關心如何去掃描手機中的文件,只要瞭解如何查詢和使
        //用這些信息就可以了。MediaStore中定義了一系列的數據表格,通過ContentResolver提供的查詢
        //接口,我們可以得到各種需要的信息。
        //EXTERNAL_CONTENT_URI 爲查詢外置內存卡的,INTERNAL_CONTENT_URI爲內置內存卡。
        //MediaStore.Audio獲取音頻信息的類
        //MediaStore.Images獲取圖片信息
        //MediaStore.Video獲取視頻信息
        Cursor cursor = getContentResolver().query(uri,null,selection,null,null);
        if(cursor != null){
            if(cursor.moveToNext()){
                path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
            }
            cursor.close();
        }
        return  path;
    }

    private void displayImage(String imagePath){
        if(imagePath != null){
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            picture.setImageBitmap(bitmap);
        } else {
            Toast.makeText(this,"failed to get image",Toast.LENGTH_SHORT);
        }
    }
}

拍照
這裏寫圖片描述

這裏寫圖片描述

這裏寫圖片描述

打開相冊
這裏寫圖片描述

這裏寫圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章