android 拍照
- 一、布局:使用RecyclerView横向滑动显示。
- 二、拍照、系统适配
- 1、动态判断权限
- 2、FileProvider适配
-
<provider android:name="android.support.v4.content.FileProvider" android:authorities="包名.FileProvider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/rc_file_path" /> </provider>
xml文件
-
<?xml version="1.0" encoding="utf-8"?> <paths> <external-path name="test" path="Android/data/com/test" /> <external-path name="external_storage_root" path="." /> </paths>
自定义path路径
-
3、拍照
private void startDeviceCamera() {
Intent mIntent = new Intent();
mIntent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
setSavePath();
deviceFile = new File(saveFile, System.currentTimeMillis() + ".jpg");
Uri uri = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkPermission()) {
requestPermission();
} else {
mIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(this, "包名.FileProvider", deviceFile);
} else {
uri = Uri.fromFile(deviceFile);
}
}
} else {
//6.0以下直接转换Uri
uri = Uri.fromFile(deviceFile);
}
mIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
startActivityForResult(mIntent, 101);
}
private void setSavePath() {
saveFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/test"); // 自定义路径
if (!saveFile.exists()) {
saveFile.mkdirs();
}
}
三、设置数据
Bean类 声明图片为Object类型
private Object imgPath;
向List添加数据
AuthDeviceBean deviceBean = new AuthDeviceBean();
deviceBean.setImgPath(R.mipmap.ic_apply_add);
authDeviceList.add(deviceBean);
为Adapter设置点击事件
authDeviceAdapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
@Override
public void onItemClick(View view, int position) {
if (position == authDeviceList.size() - 1) {
startDeviceCamera();
}
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == 101) {
if (deviceFile.exists() && deviceFile.isFile()) {
String imgPath = deviceFile.getAbsolutePath();
AuthDeviceBean authDeviceBean = new AuthDeviceBean();
authDeviceBean.setImgPath(imgPath);
authDeviceList.add(authDeviceList.size(), authDeviceBean);
authDeviceAdapter.notifyDataSetChanged();
}
}
}
}
四、问题
此时,连续拍照功能初步完成。运行发现,2个问题。
问题1:拍第1张照片后,“+”号显示在照片前面。
解决:onActivityResult() 方法中,向List添加数据
authDeviceList.add(authDeviceList.size(), authDeviceBean);
// 改为
authDeviceList.add(authDeviceList.size() - 1, authDeviceBean);
//注:通过add()方法,List长度减去1解决。
问题2:未限制拍照个数。
解决:adapter 点击事件中,进行判断。
if (position == authDeviceList.size() - 1) {
startDeviceCamera();
}
// 例如:连续拍3张。通过List下标处理。
if (position == authDeviceList.size() - 1) {
if (authDeviceList.size() <= 3) {
startDeviceCamera();
} else {
Toast.makeText(mContext, "最多3张", Toast.LENGTH_SHORT).show();
}
}
连续拍照功能完成。