构建应用以拍照和上传,但意图数据为空

时间:2018-08-22 00:57:30

标签: java android

我正在尝试制作一个可以拍摄高质量照片并上传照片的应用程序,但是最重要的部分之一将无法使用,即相机。意向数据为空,因此没有图像显示。我从https://developer.android.com/training/camera/photobasics#TaskPath获取了信息。 我尝试了不同的方法,但没有任何效果。

package com.example.gn.nextcamtest;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

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

public class MainActivity extends AppCompatActivity {

 TextView txt_Test;
 Button btn_Cam;
 ImageView iv_image;
 static final int REQUEST_IMAGE_CAPTURE = 1;
 String mCurrentPhotoPath;
 public static final int RequestPermissionCode = 1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  btn_Cam = (Button) findViewById(R.id.btn_Cam);
  iv_image = (ImageView) findViewById(R.id.iv_Test);
  txt_Test = (TextView) findViewById(R.id.txt_test);
  EnableRuntimePermissionToAccessCamera();

  Bundle bundle = getIntent().getExtras();
  if (bundle != null) {
   txt_Test.setText(" " + bundle.getString("test"));
  }

  btn_Cam.setOnClickListener(new View.OnClickListener() {
   @Override
   public void onClick(View view) {
    dispatchTakePictureIntent();
   }
  });
 }

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {

   if (data.getExtras() != null && data.getExtras().get("data") instanceof Bitmap) {
    Bundle extras = data.getExtras();
    Bitmap imageBitmap = (Bitmap) extras.get("data");
    iv_image.setImageBitmap(imageBitmap);
    // iv_image.setImageBitmap((Bitmap)data.getExtras().get("data"));
   } else {
    iv_image.setImageResource(R.drawable.ic_launcher_background);
    Toast.makeText(this, "Fail to load image", Toast.LENGTH_LONG).show();
   }
  }
 }

 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
  mCurrentPhotoPath = image.getAbsolutePath();
  return image;
 }

 static final int REQUEST_TAKE_PHOTO = 1;

 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

   }

   // Continue only if the File was successfully created
   if (photoFile != null) {
    Uri photoURI = FileProvider.getUriForFile(this, "com.example.gn.nextcamtest.fileprovider", photoFile);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
    startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
   }
  }
 }

 // Requesting runtime permission to access camera.
 public void EnableRuntimePermissionToAccessCamera() {
  if (ContextCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
   ActivityCompat.requestPermissions(this, new String[] {
    android.Manifest.permission.ACCESS_FINE_LOCATION, android.Manifest.permission.ACCESS_COARSE_LOCATION
   }, 101);
  }

  if (ActivityCompat.shouldShowRequestPermissionRationale(this,
    Manifest.permission.CAMERA)) {
   // Printing toast message after enabling runtime permission.
   Toast.makeText(this, "CAMERA permission allows us to Access CAMERA app", Toast.LENGTH_LONG).show();
  } else {
   ActivityCompat.requestPermissions(this, new String[] {
    Manifest.permission.CAMERA
   }, RequestPermissionCode);

  }
 }


 @Override
 public void onRequestPermissionsResult(int RC, String per[], int[] PResult) {
  switch (RC) {
   case RequestPermissionCode:
    if (PResult.length > 0 && PResult[0] == PackageManager.PERMISSION_GRANTED) {
     Toast.makeText(this, "Permission Granted, Now your application can access CAMERA.", Toast.LENGTH_LONG).show();
    } else {
     Toast.makeText(this, "Permission Canceled, Now your application cannot access CAMERA.", Toast.LENGTH_LONG).show();
    }

    break;
  }
 }
}

1 个答案:

答案 0 :(得分:0)

几天前我也尝试过,不得不付出很多努力。然后我自己想通了。

这是我的代码的外观:

1)在onCreate中:

capture.setOnClickListener(new View.OnClickListener() {

        @RequiresApi(api = Build.VERSION_CODES.M)
        @Override
        public void onClick(View v) {
            if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {
                if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, storagePermissionCode);
                }
                requestPermissions(new String[]{Manifest.permission.CAMERA}, cameraPermissionCode);
            } else {

                ContentValues values = new ContentValues();
                imageUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);

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

2)在onActivityResult中:

@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {

    if (requestCode == cameraRequestCode) {
        if (resultCode == Activity.RESULT_OK) {

            FileOutputStream stream = null;

            try {

                Bitmap photo = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);

                String saveFilePath = getRealPathFromURI(imageUri);

                stream = new FileOutputStream(saveFilePath);
                photo.compress(Bitmap.CompressFormat.JPEG, 25, stream);

            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Can't save image !", Toast.LENGTH_SHORT).show();
            } finally {
                try {
                    if (stream != null) {

                        stream.close();
                        Toast.makeText(getApplicationContext(), "Image saved successfully !", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(getApplicationContext(), "Can't save image, try again !", Toast.LENGTH_SHORT).show();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        } else if (resultCode == Activity.RESULT_CANCELED) {
            Toast.makeText(getApplicationContext(), "Cancelled", Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Can't capture image !", Toast.LENGTH_SHORT).show();
        }

    }
}

3)getRealPathFromURI函数:

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}