溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

Android7.0實現(xiàn)拍照和相冊選取圖片功能

發(fā)布時間:2020-10-11 12:05:17 來源:腳本之家 閱讀:190 作者:cf8833 欄目:移動開發(fā)

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

實現(xiàn)效果圖:

Android7.0實現(xiàn)拍照和相冊選取圖片功能

(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();
   }
 }
 }
}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI