安卓相机调用适配

项目中IM发送图片拍照时调用相机崩溃,也没有报错,最后排查为系统问题需要进行适配

调用相机在6.0版本上需要进行适配

1、AndroidManifest.xml 内操作

<!-- FileProvider配置访问路径,适配7.0及其以上 -->
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.yulin.merchant.fileprovider"//注意:
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
//注意:com.yulin.merchant为你的包名、    .fileprovider这个后面有用到不能随意改

2、创建file_paths.xml文件
在 项目 res 下面创建 xml 文件夹,xml文件夹下创建 file_paths.xml 文件,文件内写如下:内容
<?xml version="1.0" encoding="utf-8"?>
<paths>
    <external-path path="Android/data/com.yulin.merchant" name="files_root" />
    <external-path path="." name="external_storage_root" />
</paths>
3、记得求权限获取
 if (rxPermissions != null) {
                                rxPermissions.request(Manifest.permission.CAMERA/*, Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE*/).subscribe(new Consumer<Boolean>() {
                                    @Override
                                    public void accept(Boolean granted) throws Exception {
                                        if (granted) {
                                            chatView.sendPhoto();
                                        }
                                    }
                                });
                            }

  注意:权限动态获取

4、正儿八经的调用开始
 
private File tempFile;

@Override public void sendPhoto() { Intent intent_photo = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); if (intent_photo.resolveActivity(getPackageManager()) != null) { tempFile = FileUtil.getTempFile(FileUtil.FileType.IMG); if (tempFile != null) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { //第二个参数为 包名.fileprovider fileUri = FileProvider.getUriForFile(ChatActivity.this, "com.yulin.merchant.fileprovider", tempFile); intent_photo.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); } else { fileUri = Uri.fromFile(tempFile); } } intent_photo.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); startActivityForResult(intent_photo, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE); } }
com.yulin.merchant.fileprovider 这句话现在和清单文件必须对应

  


if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
            if (resultCode == RESULT_OK && fileUri != null) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    showImagePreview(String.valueOf(tempFile));
                } else {
                    showImagePreview(fileUri.getPath());
                }

            }
        }

 

private void showImagePreview(String path) {
    if (path == null) return;
    Intent intent = new Intent(this, ImagePreviewActivity.class);
    intent.putExtra("path", path);
    startActivityForResult(intent, IMAGE_PREVIEW);
}

 

  

 

回来接收
String path在7.0之上为
String.valueOf(tempFile)
其他为
fileUri.getPath()
有了path剩下的你就自由发挥吧


by leileitua
posted @ 2019-06-28 11:42  WidgetBox  阅读(360)  评论(0编辑  收藏  举报