1、在AndroidManifest.xml中添加如下代码
tools:ignore="ProtectedPermissions" />
android:authorities="${applicationId}.provider"
android:name="android.support.v4.content.FileProvider"
android:exported="false"
android:grantUriPermissions="true">
android:resource="@xml/provider_paths">
2、在res目录下新建一个xml文件夹,并且新建一个provider_paths的xml文件
3、主文件中打开相机
Intent intent=new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
try {
//fileUri=Uri.fromFile(createMediaFile());如果这样写会报错
fileUri= FileProvider.getUriForFile(CameraVideoActivity.this,getApplicationContext().getPackageName() + ".provider",createMediaFile());//这是正确的写法
} catch (IOException e) {
e.printStackTrace();
}
intent.putExtra(MediaStore.EXTRA_OUTPUT,fileUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY,1);
startActivityForResult(intent,1);
4、创建并保存视频的方法
private File createMediaFile() throws IOException {
if(Utils.checkSDCardAvaliable()) {
if ((Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))) {
// 选择自己的文件夹
String path = Environment.getExternalStorageDirectory().getPath() + "/myvideo/";
// Constants.video_url 是一个常量,代表存放视频的文件夹
File mediaStorageDir = new File(path);
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.e("TAG", "文件夹创建失败");
return null;
}
}
// 文件根据当前的毫秒数给自己命名
String timeStamp = String.valueOf(System.currentTimeMillis());
timeStamp = timeStamp.substring(7);
String imageFileName = "V" + timeStamp;
String suffix = ".mp4";
File mediaFile = new File(mediaStorageDir + File.separator + imageFileName + suffix);
return mediaFile;
}
}
return null;
}
}
5、重写onActivityResult方法
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode==1)
{
if(resultCode==RESULT_OK)
{
Toast.makeText(this, "Video saved to:\n" +
data.getData(), Toast.LENGTH_LONG).show();
vv_play.setVideoURI(fileUri);
vv_play.requestFocus();
}
}
}
6、DDMS截图