一、拍照
(1)申请权限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
(2)设置布局
这里做了一个简单的布局:添加了一个按钮和一个ImageView控件用于显示拍摄的图像。
(3)为按钮添加点击事件监听
点击按钮时,调用系统相机进行拍照,并在确定后将图像显示在ImageView控件中。
mButton_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Bitmap map = (Bitmap) data.getExtras().get("data");
mImageView.setImageBitmap(map);
}
}
}
二、视频录制
(1)申请权限
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
(2)设置布局
添加了一个按钮和一个VideoView控件用于显示录制的视频。
(3)为按钮添加点击事件监听
同前面一样,点击按钮后调用系统相机进行录制视频,录制完成后点击确定即可将录制的视频显示在VideoView控件中。
mButton_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, 1);
}
});
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == 1){
if(resultCode == RESULT_OK){
Uri uri = data.getData();
Cursor cursor = this.getContentResolver().query(uri, null, null, null, null);
if(cursor.moveToFirst()){
String videoPath = cursor.getString(cursor.getColumnIndex("_data"));
mVideoView.setVideoURI(Uri.parse(videoPath));
mVideoView.setMediaController(new MediaController(this));
mVideoView.start(); //播放视频
}
}
}
}
三、注意
对于Android11.0的版本,在调用系统相近进行视频录制的时候,即使在AndroidMenifest.xml中申请了CAMERA权限,还是会在程序运行时报错:Permission Denial, ......... with revoked permission android.permission.CAMERA
解决方法是在程序中动态申请权限:
mButton_audio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (Build.VERSION.SDK_INT >= 23) {
int checkCallPhonePermission = ContextCompat.checkSelfPermission(ActivityAudio.this, Manifest.permission.CAMERA);
if(checkCallPhonePermission != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(ActivityAudio.this, new String[]{Manifest.permission.CAMERA}, 1);
return;
}else{
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, 1);
}
} else {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
startActivityForResult(intent, 1);
}
}
});
写在最后:文章是在学习过程中做的学习笔记,同时与志同道合者分享,文章内容均经过我自己实验证实可行,如有问题欢迎留言,很高兴一起交流讨论,共同进步!