在android中使用相机应用程序时出错

时间:2017-01-01 13:01:27

标签: android android-camera android-camera-intent android-camera2

以下是在我的应用中使用相机拍照的代码。在按下imgButton时,应该拍摄一张照片并显示在imageView

当我按下按钮时,会打开相机。但是,拍摄的图像不会显示在image view

在调试时,方法if (imgFile.exists())中的onActivityResult()显示为false,if内的语句未执行。

MainActivity.java

package com.example.nirvan.cameraexample3;

import android.content.Intent;
import android.graphics.Bitmap; 
import android.graphics.BitmapFactory;
import android.media.Image;
import android.net.Uri;
import android.os.Environment;  
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MainActivity extends AppCompatActivity   
{

private String pictureImagePath = "";

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button imgButton=(Button) findViewById(R.id.imgButton);


    View.OnClickListener imgButtonClickListener=new View.OnClickListener()
    {
        @Override
        public void onClick(View view)
        {
            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
            String imageFileName = timeStamp + ".jpg";
            File storageDir = Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_PICTURES);
            pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
            File file = new File(pictureImagePath);
            Uri outputFileUri = Uri.fromFile(file);
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
            startActivityForResult(cameraIntent, 1);
        }
    };
    imgButton.setOnClickListener(imgButtonClickListener);


}



protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
    Log.d("TAG","CUSTOOOM");
    if (requestCode == 1)
    {
        File imgFile = new File(pictureImagePath);
        if (imgFile.exists())
        {
            Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
            ImageView myImage = (ImageView) findViewById(R.id.imageViewTest);
            myImage.setImageBitmap(myBitmap);

        }
    }






}



}

MainActivity.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.nirvan.cameraexample3.MainActivity">

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageViewTest"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true" />

<Button
    style="?android:attr/buttonStyleSmall"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="IMG"
    android:id="@+id/imgButton"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="56dp" />
</RelativeLayout>

1 个答案:

答案 0 :(得分:2)

有一些问题

1。)将您的听众创作移到oncreate

之外

2。)使用已创建的图像文件uri而不是创建新图像文件

3。)确认RESULT_OK确认

public class MainActivity extends AppCompatActivity {

    private String pictureImagePath = "";
    private Uri outputFileUri;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button imgButton=(Button) findViewById(R.id.imgButton);
        imgButton.setOnClickListener(imgButtonClickListener);
    }

    View.OnClickListener imgButtonClickListener=new View.OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
                String imageFileName = timeStamp + ".jpg";
                File storageDir = Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES);
                pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;
                File file = new File(pictureImagePath);

                outputFileUri = Uri.fromFile(file);
                // It's global to class now

                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                startActivityForResult(cameraIntent, 1);
            }
        };


        protected void onActivityResult(int requestCode, int resultCode, Intent data)
        {
            Log.d("TAG","CUSTOOOM");
            if (requestCode == 1 && resultCode == RESULT_OK)
            {
                 //RESULT_OK mean ,image taken successfully
                 // you can put a file exist check if you want

                 Bitmap myBitmap = BitmapFactory.decodeFile(outputFileUri);
                 ImageView myImage = (ImageView) findViewById(R.id.imageViewTest);
                 myImage.setImageBitmap(myBitmap);
            }
        }
}

您还需要在清单中添加权限

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
...>

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

或者,如果您的应用支持Marshmallow及以上,那么您需要实施

Implement Run-time permission