1、在AndroidManifest.xml中添加如下代码
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.INTERNET"/><uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" />
<application
<provider android:authorities="${applicationId}.provider" android:name="android.support.v4.content.FileProvider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/provider_paths"> </meta-data></provider>
</application> </manifest>
2、在res目录下新建一个xml文件夹,并且新建一个provider_paths的xml文件
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <external-path name="external_files" path="."/> </paths>
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方法
@Overrideprotected 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截图
原文地址:https://www.cnblogs.com/maoliyy/p/9284847.html
时间: 2024-10-10 19:03:40