Android不一致的图片保存与getExternalFilesDir [英] Android inconsistent picture saving with getExternalFilesDir

查看:701
本文介绍了Android不一致的图片保存与getExternalFilesDir的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程式中,我尝试拍摄图片,储存它,并将它加入ImageView中,并附上这段程式码: Android开发人员教程

In my app, I am trying to take a picture, save it, and add it to an ImageView with this code I got from the Android Developers tutorial

private static final int REQUEST_IMAGE_CAPTURE = 1;
private String lastImagePath;

//Create temporary image file using getExternalFilesDir()
private File createImageFile() throws IOException{
    String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timestamp + "_";
    File storageDir = getActivity().getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(imageFileName, ".jpg", storageDir);
    lastImagePath = image.getAbsolutePath();
    return image;
}

//Start picture intent and save to file
private void takePicture(){
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    File photoFile = null;
    if(takePictureIntent.resolveActivity(getActivity().getPackageManager())!= null){
        try{
            photoFile = createImageFile();
        }catch (IOException e){
            Log.e(TAG, "Error Creating image file");
            e.printStackTrace();
        }
        if (photoFile !=null){
            Log.e(TAG, photoFile.getAbsolutePath());
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == Activity.RESULT_OK){

        //Ensure the path has been set
        if(lastImagePath !=null){
            Log.e(TAG, "LastImagePath: " + lastImagePath);

            //DEBUG:see if it actually created the file
            File file = new File(lastImagePath);
            if(file.exists()){
                Log.e(TAG, "File exists");
            }

            //Decode file
            Bitmap image = BitmapFactory.decodeFile(lastImagePath);

            //DEBUG: see if image is null
            if(image == null){
                Log.e(TAG, "Image is null");
            }else{
                Log.e(TAG, "Image is not null");
            }

            //convert full sized image to thumbnail and add it to imageView
            Bitmap thumbnail = ThumbnailUtils.extractThumbnail(image, 200, 200);
            image1.setImageBitmap(thumbnail);
        }else{
            Log.e(TAG, "lastImagePath is null");
        }
    }
}

并拍摄图像,保存,将其加载回程序并将其添加到图像视图。但其他时候,它根本不工作,似乎无法采取的形象。

Sometimes this code works as expected and takes an image, saves it, loads it back into the program and adds it to the image view. But other times, it doesn't work at all and seems to fail to take the image.

这里是一个成功的图像捕获的logcat输出,其中图像显示在ImageView中

Here is the logcat output for a successful image capture where the image appears in the ImageView

05-04 17:27:49.218 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: /storage/emulated/0/Android/data/com.noah.stickynotes_clientside/files/Pictures/JPEG_20160504_172748_-1847663626.jpg
05-04 17:28:03.886 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: LastImagePath: /storage/emulated/0/Android/data/com.noah.stickynotes_clientside/files/Pictures/JPEG_20160504_172748_-1847663626.jpg
05-04 17:28:04.359 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: File exists
05-04 17:28:04.825 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: Image is not null

ImageView中没有图像的图像捕获

And here is the logcat output for a failed image capture where there is no image in the ImageView

05-04 17:29:00.070 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: /storage/emulated/0/Android/data/com.noah.stickynotes_clientside/files/Pictures/JPEG_20160504_172900_-1359930406.jpg
05-04 17:29:06.581 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: LastImagePath: /storage/emulated/0/Android/data/com.noah.stickynotes_clientside/files/Pictures/JPEG_20160504_172900_-1359930406.jpg
05-04 17:29:06.583 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: File exists
05-04 17:29:06.583 4964-4964/com.noah.stickynotes_clientside E/SUBMIT_FRAGMENT: Image is null

这似乎是随机工作,80%的时间失败。我使用getExternalFilesDir,因为我想要的照片是私人的应用程序。我还为我的Manifest文件添加了WRITE_EXTERNAL_STORAGE权限。

This seems to work randomly and fails 80% of the time. I'm using getExternalFilesDir because I want the photos to be private to the application. I also added the WRITE_EXTERNAL_STORAGE permission to my Manifest file.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

我也明白我可以使用图片中的缩略图,

I also understand that I could use the thumbnail from the image but I want to have the full sized image because I will be adding it to a class later on.

任何人都对错误有什么想法?

Anyone have any ideas on whats going wrong?

推荐答案

您的过程正在终止,而您的应用程序在后台。这是Android的正常现象,虽然你可能不会在这里。您需要在保存的实例状态 Bundle 中保存您的 EXTRA_OUTPUT

Your process is being terminated while your app is in the background. This is normal for Android, though you may not be expecting it here. You need to hold onto your EXTRA_OUTPUT in the saved instance state Bundle.

另请注意,由于文件: Uri 值已被禁止,您应考虑切换到使用 FileProvider

Also note that since file: Uri values are being banned, you should consider switching to using FileProvider.

这个示例应用程序演示了这两个事情。不可否认,代码更复杂:

This sample app demonstrates both of those things. Admittedly, the code is more complicated:

/***
 Copyright (c) 2008-2016 CommonsWare, LLC
 Licensed under the Apache License, Version 2.0 (the "License"); you may not
 use this file except in compliance with the License. You may obtain a copy
 of the License at http://www.apache.org/licenses/LICENSE-2.0. Unless required
 by applicable law or agreed to in writing, software distributed under the
 License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS
 OF ANY KIND, either express or implied. See the License for the specific
 language governing permissions and limitations under the License.

 From _The Busy Coder's Guide to Android Development_
 https://commonsware.com/Android
 */

package com.commonsware.android.camcon;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import java.io.File;
import java.util.List;

public class CameraContentDemoActivity extends Activity {
  private static final String EXTRA_FILENAME=
    "com.commonsware.android.camcon.EXTRA_FILENAME";
  private static final String FILENAME="CameraContentDemo.jpeg";
  private static final int CONTENT_REQUEST=1337;
  private static final String AUTHORITY=
    BuildConfig.APPLICATION_ID+".provider";
  private static final String PHOTOS="photos";
  private File output=null;
  private Uri outputUri=null;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent i=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);

    if (savedInstanceState==null) {
      output=new File(new File(getFilesDir(), PHOTOS), FILENAME);

      if (output.exists()) {
        output.delete();
      }
      else {
        output.getParentFile().mkdirs();
      }
    }
    else {
      output=(File)savedInstanceState.getSerializable(EXTRA_FILENAME);
    }

    outputUri=FileProvider.getUriForFile(this, AUTHORITY, output);

    if (savedInstanceState==null) {
      i.putExtra(MediaStore.EXTRA_OUTPUT, outputUri);

      if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.LOLLIPOP) {
        i.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
      }
      else {
        List<ResolveInfo> resInfoList=
          getPackageManager()
            .queryIntentActivities(i, PackageManager.MATCH_DEFAULT_ONLY);

        for (ResolveInfo resolveInfo : resInfoList) {
          String packageName = resolveInfo.activityInfo.packageName;
          grantUriPermission(packageName, outputUri,
            Intent.FLAG_GRANT_WRITE_URI_PERMISSION |
              Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
      }

      startActivityForResult(i, CONTENT_REQUEST);
    }
  }

  @Override
  protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    outState.putSerializable(EXTRA_FILENAME, output);
  }

  @Override
  protected void onActivityResult(int requestCode, int resultCode,
                                  Intent data) {
    if (requestCode == CONTENT_REQUEST) {
      if (resultCode == RESULT_OK) {
        Intent i=new Intent(Intent.ACTION_VIEW);

        i.setDataAndType(outputUri, "image/jpeg");
        i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startActivity(i);
        finish();
      }
    }
  }
}

对于你的问题,我把输出位置保存在 Bundle onSaveInstanceState() code> onCreate()如果我有一个 Bundle 正在恢复。

With respect to your problem, I am saving my output location in the Bundle in onSaveInstanceState() and using it again in onCreate() if I have a Bundle that is being restored.

这篇关于Android不一致的图片保存与getExternalFilesDir的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆