我正在尝试在我的应用程序中包含一个相机,它将文件本地保存在 SD 卡上。相机应用程序启动,但 resultCode 始终为 0。我在 Manifest 中添加了以下权限:
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
这是我的相机的代码:
@SuppressLint("SimpleDateFormat")
private void takePicture(){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/resources/resources/WI1");
SimpleDateFormat timeStampFormat = new SimpleDateFormat("MM/dd/yyyy");
String image_name =username +"-"+ timeStampFormat.format(new Date())+".png";
File image = new File(imagesFolder, image_name);
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
int request_code = 100;
startActivityForResult(imageIntent, request_code);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Toast.makeText(this, "Image Saved", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(this,"Error Saving Image, please throw device at wall", Toast.LENGTH_SHORT).show();
} // end on activity result
是什么导致了这个错误?谢谢!
编辑:我删除了之前发布的 logcat 信息,因为它与这个问题无关。编辑2:
我解决了一半的问题,如果我使用此代码,相机就可以正常工作。有人能告诉我是什么原因造成的吗?
private void takePicture(){
Intent imageIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
File imagesFolder = new File(Environment.getExternalStorageDirectory(), "/resources/resources/WI1");
String image_name = "matt"+image_count+".png";
image_count+=1; // this is at the moment useless.
File image = new File(imagesFolder, image_name);
Uri uriSavedImage = Uri.fromFile(image);
imageIntent.putExtra(MediaStore.EXTRA_OUTPUT, uriSavedImage);
int request_code = 100;
startActivityForResult(imageIntent, request_code);
}
编辑3:问题在于timeStampFormat,如果我排除它,相机就可以正常工作。有人可以解释为什么吗?如果我没记错的话,那是因为我选择的日期格式中有正斜杠。