Android7.0实现拍照和相册选取图片功能

由于android 7.0新增了动态权限,所以我们在做拍照和相册选取功能的时候,需要申请添加动态权限

实现效果图:

(1)在res目录下,新建xml文件夹 ,在xml文件夹中新建一个filepaths.xml

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

(2)去清单文件里面添加权限  AndroidManifest.xml,拍照和选照片权限只加这一个即可,多加错加均会导致程序报错

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

(3)添加provider,注意provider红色部分为当前项目包名,黑色部分为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中动态申请权限,并且调用系统相机和相册

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);
  //添加权限
  intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
  intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
  startActivityForResult(intent, REQUEST_CAMERA);
 }

 private void getPhoto(){
  //在这里跳转到手机系统相册里面
  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]);
   // 权限是否已经 授权 GRANTED---授权 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 {
   // 没有获取 到权限,从新请求,或者关闭app
   Toast.makeText(this, "需要存储权限", 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()));
   //在手机相册中显示刚拍摄的图片
   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(); //获取系统返回的照片的Uri
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(selectedImage,
      filePathColumn, null, null, null);//从系统表中查询指定Uri对应的照片
    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();
   }
 }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持菜鸟教程(cainiaojc.com)。

声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。