當(dāng)前位置:首頁 > IT技術(shù) > 移動平臺 > 正文

Android7.0拍照和相冊選取圖片
2021-09-16 11:53:20

由于android 7.0新增了動態(tài)權(quán)限,所以我們在做拍照和相冊選取功能的時候,需要申請?zhí)砑觿討B(tài)權(quán)限

實現(xiàn)效果圖:

Android7.0拍照和相冊選取圖片_ide

(1)在res目錄下,新建xml文件夾 ,在xml文件夾中新建一個filepaths.xml

?

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <external-path
        name="images"
        path="test/"/>
</resources>

(2)去清單文件里面添加權(quán)限 ?AndroidManifest.xml,拍照和選照片權(quán)限只加這一個即可,多加錯加均會導(dǎo)致程序報錯

?

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

?

(3)添加provider,注意provider紅色部分為當(dāng)前項目包名,黑色部分為xml文件夾中filepaths文件名

?

<provider
    android:name="android.support.v4.content.FileProvider"
    android:authorities="com.gjp.activity.teste.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/filepaths"/>
</provider>

(4)主界面的布局 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">

    <ImageView
        android:src="@mipmap/ic_launcher"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:id="@+id/ivView"/>

    <Button
        android:text="拍照"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/button"/>
    <Button
        android:text="從相冊選取圖片"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/take_button"/>
</LinearLayout>

(5)在MainActivity中動態(tài)申請權(quán)限,并且調(diào)用系統(tǒng)相機(jī)和相冊

?

public class MainActivity extends Activity{
    private static int REQUEST_CAMERA =1;
    private static int IMAGE_REQUEST_CODE =2;
    private File file;
    private Button button,take_button;
    private ImageView imageView;
    private String paths;

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

        button = (Button)findViewById(R.id.button);
        take_button = (Button)findViewById(R.id.take_button);
        imageView = (ImageView)findViewById(R.id.ivView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                applyWritePermission();

            }
        });

        take_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               getPhoto();
            }
        });

    }

    private void useCamera() {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        file = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                + "/test/" + System.currentTimeMillis() + ".jpg");
        file.getParentFile().mkdirs();
        //改變Uri  com.xykj.customview.fileprovider注意和xml中的一致
        Uri uri = FileProvider.getUriForFile(this, "com.gjp.activity.teste.fileprovider", file);
        //添加權(quán)限
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        startActivityForResult(intent, REQUEST_CAMERA);
    }

    private void getPhoto(){
        //在這里跳轉(zhuǎn)到手機(jī)系統(tǒng)相冊里面
        Intent intent = new Intent(
                Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, IMAGE_REQUEST_CODE);
    }

    public void applyWritePermission() {
        String[] permissions = {Manifest.permission.WRITE_EXTERNAL_STORAGE};
        if (Build.VERSION.SDK_INT >= 23) {
            int check = ContextCompat.checkSelfPermission(this, permissions[0]);
            // 權(quán)限是否已經(jīng) 授權(quán) GRANTED---授權(quán)  DINIED---拒絕
            if (check == PackageManager.PERMISSION_GRANTED) {
                    useCamera();
            } else {
                requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
            }
        } else {
                useCamera();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            useCamera();
        } else {
            // 沒有獲取 到權(quán)限,從新請求,或者關(guān)閉app
            Toast.makeText(this, "需要存儲權(quán)限", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CAMERA && resultCode == RESULT_OK) {
            Log.e("TAG", "---------" + FileProvider.getUriForFile(this, "com.gjp.activity.teste.fileprovider", file));
            imageView.setImageBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()));
            //在手機(jī)相冊中顯示剛拍攝的圖片
            Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri contentUri = Uri.fromFile(file);
            mediaScanIntent.setData(contentUri);
            sendBroadcast(mediaScanIntent);
        }
        if (requestCode == IMAGE_REQUEST_CODE && resultCode == RESULT_OK) {
            try {
                Uri selectedImage = data.getData(); //獲取系統(tǒng)返回的照片的Uri
                String[] filePathColumn = {MediaStore.Images.Media.DATA};
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);//從系統(tǒng)表中查詢指定Uri對應(yīng)的照片
                cursor.moveToFirst();
                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                paths = cursor.getString(columnIndex);  //獲取照片路徑
                cursor.close();
                Bitmap bitmap = BitmapFactory.decodeFile(paths);
                imageView.setImageBitmap(bitmap);
            } catch (Exception e) {
                e.printStackTrace();
            }
    }
    }
}

?


本文摘自 :https://blog.51cto.com/u

開通會員,享受整站包年服務(wù)立即開通 >