【发布时间】:2016-04-04 08:31:37
【问题描述】:
所以,我有一个应用程序,我想在其中拍照,将其存储到内部存储中,然后能够稍后检索它(可能是通过它的 Uri)。到目前为止,这是我所拥有的: 按下我的自定义相机按钮时会触发此代码。
cameraButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final Intent takePic = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File file = herp(MEDIA_TYPE_IMAGE);
if (file != null) {
fileUri = getOutputMediaFileUri(file);
Log.d("AddRecipeActivity", fileUri.toString());
takePic.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(takePic, CAMERA_REQUEST);
}
}
});
接下来,我稍后在代码中定义了两个方法(主要取自 android 开发者网站):
/** Create a file Uri for saving an image or video */
private static Uri getOutputMediaFileUri(File file){
return Uri.fromFile(file);
}
/** Create a File for saving an image or video */
public File herp(int type){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
Boolean a = false;
String externalDirectory= getFilesDir().getAbsolutePath();
File folder= new File(externalDirectory + "/NewFolder");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (!folder.exists()){
a = folder.mkdirs();
Log.d("AddRecipeActivity", String.valueOf(a));
}
// Create a media file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE){
mediaFile = new File(folder.getPath() + File.separator +
"IMG_"+ timeStamp + ".jpg");
} else {
return null;
}
if(mediaFile == null){
Log.d("AddRecipeActivity", "Media file is null");
}
return mediaFile;
}
当我打印我的 Uri 时(就在触发意图之前),我得到以下输出。
04-04 04:22:40.757 22402-22402/scissorkick.com.project2 D/AddRecipeActivity: file:///data/user/0/scissorkick.com.project2/files/NewFolder/IMG_20160404_042240.jpg
此外,当我检查目录是否已创建时,布尔值为真。 但是,当我的相机意图的 onActivityResult 运行时,结果代码为 0。
为什么它会在这一点上失败?我已经在清单中定义了适当的权限,并且还在运行时请求了外部存储写入权限。
编辑:添加 onActivityResult:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
if(requestCode == CAMERA_REQUEST){
Log.d("AddRecipe", String.valueOf(resultCode));
if(resultCode == RESULT_OK){
photo = (Bitmap) data.getExtras().get("data");
thumb = ThumbnailUtils.extractThumbnail(photo, 240, 240);
photoView.setImageBitmap(thumb);
//Toast.makeText(getApplicationContext(), "image saved to:\n" + data.getData(), Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Fail", Toast.LENGTH_SHORT).show();
}
}
}
onActivityResult里面有一些乱码,关键是resultCode = 0,不知道为什么。
【问题讨论】:
-
显示您的 onActivityResult 代码
-
已添加。我认为它连接正确,但我不是 100%
-
你的问题解决了吗??
标签: android android-intent android-camera