我制作了一个非常简单的应用程序,我可以通过菜单中的按钮打开摄像机和照相机。以下是此应用的代码:
private static final int VIDEO_REQUEST_CODE=1;
private static final int IMAGE_REQUEST_CODE=2;
public void startRecord(){
Intent videoIntent= new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MOVIES);
Uri fileUri=Uri.fromFile(new File(dir,"myVideo1.mp4"));
videoIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
videoIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(videoIntent,VIDEO_REQUEST_CODE);
}
public void capturePhoto(){
Intent imageIntent= new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File dir=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Uri fileUri=Uri.fromFile(new File(dir,"myImage1.jpg"));
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(imageIntent,IMAGE_REQUEST_CODE);
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_capture:
capturePhoto();
case R.id.action_record:
startRecord();
return true;
}
return false;
}
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode==VIDEO_REQUEST_CODE){
if(resultCode==RESULT_OK){
Toast.makeText(this,"Video saved to: "+data.getData(),Toast.LENGTH_LONG).show();
}else if(resultCode==RESULT_CANCELED){
Toast.makeText(this,"Record canceled",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Record failed",Toast.LENGTH_LONG).show();
}
}else if(requestCode==IMAGE_REQUEST_CODE){
if(resultCode==RESULT_OK){
Toast.makeText(this,"Image saved to: "+data.getData(),Toast.LENGTH_LONG).show();
}else if(resultCode==RESULT_CANCELED){
Toast.makeText(this,"Image capture canceled",Toast.LENGTH_LONG).show();
}else{
Toast.makeText(this,"Image capture failed",Toast.LENGTH_LONG).show();
}
}
}
现在视频效果很好,但是当我尝试打开相机拍摄图像时,它也会自动打开视频摄像机。当我按"返回"之后图像相机打开,但是当我想拍照时,应用程序因运行时错误而关闭。它说failure delivering results to activity... ...attempt to invoke Uri on null object
。我无法找到我的Uri的错误,所以任何人都可以解释我做错了什么?
答案 0 :(得分:0)
那么有人可以解释我做错了什么吗?
您的switch
写错了:
switch(item.getItemId()){
case R.id.action_capture:
capturePhoto();
case R.id.action_record:
startRecord();
return true;
}
选择R.id.action_capture
后,您会同时拨打capturePhoto()
和 startRecord()
,因为case R.id.action_capture
部分并未以{{1}结尾}或break
。
另请注意,return
应该为data.getData()
返回null
。您正在设置ACTION_IMAGE_CAPTURE
;看那里的照片。