某些设备存在Android摄像头意图问题

某些设备存在Android摄像头意图问题,android,android-intent,Android,Android Intent,我试图做的是使用相机拍摄照片,记下URI(稍后我将通过Firebase存储上传图像),如果需要,旋转图像,然后在ImageView中显示图像。我现在就是这样做的,它在AVD和运行棉花糖6.0.1的索尼Xperia Z2上运行正常。但是,当在运行棒棒糖5.0.1的三星Galaxy S4上进行测试时,我遇到了一些问题。代码在指定的文件路径中找不到映像。我还尝试过使用photoURI设置ImageView,我还尝试过在创建相机意图时注释额外的内容,只是通过data.getData()-这些方法都不起作

我试图做的是使用相机拍摄照片,记下URI(稍后我将通过
Firebase
存储上传图像),如果需要,旋转图像,然后在
ImageView
中显示图像。我现在就是这样做的,它在AVD和运行
棉花糖6.0.1
索尼Xperia Z2
上运行正常。但是,当在运行棒棒糖5.0.1的三星Galaxy S4上进行测试时,我遇到了一些问题。代码在指定的文件路径中找不到映像。我还尝试过使用photoURI设置
ImageView
,我还尝试过在创建相机意图时注释额外的内容,只是通过
data.getData()
-这些方法都不起作用。我只需要一种方法,从这个设备获得这个图像,而不会崩溃,理想情况下不会影响设备的兼容性

编辑:在相机意图接管之前,两个photoFilepath 和photoURI都有值。当我到达活动结果的
时,
两者都返回null

当我到达onActivityResult时,两者都返回null

最有可能的情况是,当你的应用程序在后台,而相机应用程序在前台时,进程被终止。这是完全正常的,尽管它是否发生在任何给定的
ACTION\u IMAGE\u CAPTURE
请求上都会有所不同

确保在保存的实例状态
Bundle
中保留相关内容,如
Uri
和/或
文件
,例如:

/***
版权所有(c)2008-2016 Commonware,LLC
根据Apache许可证2.0版(以下简称“许可证”)获得许可;你不可以
除非符合许可证,否则请使用此文件。你可以得到一份
许可证的有效期在http://www.apache.org/licenses/LICENSE-2.0. 除非需要
根据适用法律或书面同意,根据
许可证按“原样”分发,无任何保证或条件
任何形式的,无论是明示的还是暗示的。请参阅许可证以了解具体的信息
管理许可证下的权限和限制的语言。
从《忙碌的程序员指南》到Android开发_
https://commonsware.com/Android
*/
包com.commonware.android.camcon;
导入android.app.Activity;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.content.pm.ResolveInfo;
导入android.net.Uri;
导入android.os.Build;
导入android.os.Bundle;
导入android.provider.MediaStore;
导入android.support.v4.content.FileProvider;
导入java.io.File;
导入java.util.List;
公共类CameraContentDemoActivity扩展活动{
私有静态最终字符串额外\u文件名=
“com.commonware.android.camcon.EXTRA_文件名”;
私有静态最终字符串FILENAME=“CameraContentDemo.jpeg”;
私有静态最终int-CONTENT_请求=1337;
私有静态最终字符串权限=
BuildConfig.APPLICATION_ID+“.provider”;
私有静态最终字符串PHOTOS=“PHOTOS”;
私有文件输出=null;
私有Uri输出Uri=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
意向i=新意向(MediaStore.ACTION\u IMAGE\u CAPTURE);
如果(savedInstanceState==null){
输出=新文件(新文件(getFilesDir(),照片),文件名);
if(output.exists()){
output.delete();
}
否则{
output.getParentFile().mkdirs();
}
}
否则{
output=(文件)savedInstanceState.getSerializable(额外的文件名);
}
outputUri=FileProvider.getUriForFile(此、权限、输出);
如果(savedInstanceState==null){
i、 putExtra(MediaStore.EXTRA_输出,outputUri);
if(Build.VERSION.SDK\u INT>=Build.VERSION\u code.LOLLIPOP){
i、 addFlags(Intent.FLAG\u GRANT\u WRITE\u URI\u PERMISSION);
}
否则{
列表重信息列表=
getPackageManager()
.QueryInputActivities(i,PackageManager.MATCH_DEFAULT_仅限);
对于(ResolveInfo ResolveInfo:ResInfo列表){
字符串packageName=resolveInfo.activityInfo.packageName;
grantUriPermission(packageName、outputUri、,
Intent.FLAG\授予\写入\ URI\权限|
意图。标志(授予读取权限);
}
}
startActivityForResult(一、内容请求);
}
}
@凌驾
SaveInstanceState上受保护的无效(束超出状态){
super.onSaveInstanceState(超出状态);
putSerializable(额外的文件名,输出);
}
@凌驾
ActivityResult上受保护的void(int请求代码、int结果代码、,
意图(数据){
if(requestCode==CONTENT\u请求){
if(resultCode==RESULT\u OK){
意向i=新意向(意向.行动\视图);
i、 setDataAndType(输出URI,“图像/jpeg”);
i、 addFlags(意图、标志、授予、读取、URI、权限);
星触觉(i);
完成();
}
}
}
}
当我到达onActivityResult时,两者都返回null

最有可能的情况是,当你的应用程序在后台,而相机应用程序在前台时,进程被终止。这是完全正常的,尽管它是否发生在任何给定的
ACTION\u IMAGE\u CAPTURE
请求上都会有所不同

确保在保存的实例状态
Bundle
中保留相关内容,如
Uri
和/或
文件
,例如:

/***
版权所有(c)2008-2016 Commonware,LLC
根据Apache许可证2.0版(以下简称“许可证”)获得许可;你不可以
除非符合许可证,否则请使用此文件。你可以得到一份
许可证的有效期在http://www.apache.org/licenses/LICENSE-2.0. 除非需要
根据适用法律或书面同意,根据
许可证按“原样”分发,无任何保证或条件
任何一种,艾未未
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    BitmapFactory.Options opt = new BitmapFactory.Options();
    opt.inSampleSize = 8;
    if (resultCode == RESULT_OK) {
        if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE){
            try {
                Bitmap bit = BitmapFactory.decodeFile(photoFilepath, opt);
                Bitmap rotated = rotateImg(bit, photoFilepath);
                userPhoto.setImageBitmap(rotated);
                contentsOfImageView = rotated;
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(this, "Error retrieving photo, please try again", Toast.LENGTH_LONG).show();
                contentsOfImageView = null;
            }
        } // else if here for handling getting images from gallery
        addBtn.setVisibility(View.INVISIBLE);
        clearBtn.setVisibility(View.VISIBLE);
    } else { // Result was a failure
        //Toast.makeText(this, "Picture wasn't taken!", Toast.LENGTH_SHORT).show();
    }

}

private void dispatchTakePictureIntent() {
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    // Ensure that there's a camera activity to handle the intent
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        // Create the File where the photo should go
        File photoFile = null;
        try {
            photoFile = createImageFile();
        } catch (IOException ex) {
            // Error occurred while creating the File
            Log.d(TAG, ex.toString());
        }
        // Continue only if the File was successfully created
        if (photoFile != null) {
            photoURI = FileProvider.getUriForFile(this,
                    "com.example.intheactualcodethisismypackagename",
                    photoFile);
            takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
            startActivityForResult(takePictureIntent, CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE);
        }
    }
}

private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // Save a file: path for use with ACTION_VIEW intents
    photoFilepath = image.getAbsolutePath();
    return image;
}

private Bitmap rotateImg(Bitmap before, String path) {
    ExifInterface exif = null;
    try {
        exif = new ExifInterface(path);
    } catch (IOException e) {
        e.printStackTrace();
    }
    int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED);
    Matrix matrix = new Matrix();
    switch (orientation) {
        case ExifInterface.ORIENTATION_ROTATE_90:
            matrix.setRotate(90);
            break;
        case ExifInterface.ORIENTATION_ROTATE_180:
            matrix.setRotate(180);
            break;
        case ExifInterface.ORIENTATION_ROTATE_270:
            matrix.setRotate(270);
            break;
        default:
            break;

    }
    return Bitmap.createBitmap(before, 0, 0, before.getWidth(), before.getHeight(), matrix, true);
}
/***
 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();
      }
    }
  }
}