直接上代码吧,就不再多说了。。。。。
具体实现
在res下新建xml文件夹,新建file_paths.xml文件
<?xml version="1.0" encoding="utf-8"?>
<resources>
<paths>
<external-path
name="camera_photos"
path="." />
</paths>
</resources>
复制代码
AndroidManifest文件中添加provider
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.example.mvptest.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/file_paths" />
</provider>
复制代码
判断权限方法
/**
* 获取权限
* @return
*/
private boolean hasPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED
|| ContextCompat.checkSelfPermission(this,Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.CAMERA}, PERMISSIONS_REQUEST_CODE);
return false;
}else {
return true;
}
}
复制代码
权限回调判断
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case PERMISSIONS_REQUEST_CODE:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//takePhoto();
selectImg();
}
break;
}
}
复制代码
调用相机方法
/**
* 调用相机
*/
private void takePhoto(){
if (!hasPermission()){
return;
}
Intent intent = new Intent();
intent.setAction(MediaStore.ACTION_IMAGE_CAPTURE);
String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/img";
if (new File(path).exists()) {
try {
new File(path).createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressLint("SimpleDateFormat")
String filename = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
mTmpFile = new File(path, filename + ".jpg");
mTmpFile.getParentFile().mkdirs();
Uri imageUri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
String authority = getPackageName() + ".provider";
imageUri = FileProvider.getUriForFile(this, authority, mTmpFile);
} else {
imageUri = Uri.fromFile(mTmpFile);
}
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
startActivityForResult(intent, CAMERA_REQUEST_CODE);
}
复制代码
得到照片进行处理
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case CAMERA_REQUEST_CODE:
if (resultCode == RESULT_OK){
Bitmap photo = BitmapFactory.decodeFile(mTmpFile.getAbsolutePath());
imageView.setImageBitmap(photo);
}
break;
}
}
复制代码
具体方法如上所示,若有什么问题,希望大家及时指正??