我有一个非常奇怪的错误试图通过意图拍照.
活动代码(稍微简化):
private voID startCapture() throws IOException { // Create output file final file photofile = makePhotofile(); _photopath = photofile.getabsolutePath(); Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); /* important NOTE TO READERS * As of AndroID N (which went out shortly after I posted this question), * you cannot use Uri.fromfile this way anymore. * You should use a fileProvIDer. */ cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromfile(photofile)); if (cameraIntent.resolveActivity(getPackageManager()) != null) { startActivityForResult(cameraIntent, REQUEST_CODE_IMAGE_CAPTURE); } else { deleteCurrentPhoto(); }}private file makePhotofile() throws IOException { String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.ENGliSH).format(new Date()); String imagefilename = "MyPhoto_" + timeStamp + "_"; file storageDir = getExternalfilesDir(Environment.DIRECTORY_PICTURES); return file.createTempfile(imagefilename, ".jpg", storageDir);}@OverrIDeprotected voID onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if(requestCode == REQUEST_CODE_IMAGE_CAPTURE) { if(resultCode == RESulT_OK) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); final byte[] buffer = new byte[2048]; int read; byte[] photoBytes; try(fileinputStream fis = new fileinputStream(_photopath)) { for(int i=0; i<10; i++) { // Always working after first iteration though if( (read = fis.read(buffer)) <= 0) { // Why does this get printed once ?? Log.w("my.package.my.app", "Empty for Now..."); } else { Log.w("my.package.my.app", "Working Now !"); bos.write(buffer, 0, read); break; } } while((read = fis.read(buffer)) >= 0) { bos.write(buffer, 0, read); } photoBytes = bos.toByteArray(); } // Catch clauses removed for simplicity // Everything working OK after that (photoBytes decodes fine with the BitmapFactory) } }}
@H_419_9@并且日志输出:
03-01 16:32:34.139 23414-23414/my.package.my.app W/my.package.my.app:
Empty for Now… 03-01 16:32:34.139 23414-23414/my.package.my.app
W/my.package.my.app: Working Now !正如您所看到的,在拍摄照片后的onActivityResult中,第一次调用fileinputStream.read时文件为空……然后就可以正确读取了!
我认为当相机意图返回到调用活动时,文件将被写入.有什么延迟吗?我也惊讶地发现它在for循环中只进行了一次迭代后总是工作.请注意,如果我在onActivityResult的开头放置一个断点,它会延迟执行一点,并且一切正常(在第一次尝试时正确读取文件).
我在AndroID 6.0.1下使用股票相机应用程序的股票Nexus 6P.
重要编辑:对于AndroID N,你应该像我之前一样使用fileProvIDer而不是Uri.fromfile.见this blog post和these explanations from the Android team.
解决方法:
file.createTempfile.不要创建该文件.您唯一需要的是文件名.文件路径. Camera应用程序将创建该文件.因此,重命名您的函数以创建新文件名.
总结以上是内存溢出为你收集整理的android – 在onActivityResult中使用相机意图捕获的图片文件空了一段时间全部内容,希望文章能够帮你解决android – 在onActivityResult中使用相机意图捕获的图片文件空了一段时间所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)