Android-相机意图导致应用崩溃

时间:2018-12-01 09:33:43

标签: android android-studio android-intent android-camera android-camera-intent

我正在尝试通过以下代码激活摄像机:

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
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 {
    private static final String TAG = "MainActivity";
    private ImageView mImageView;
    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_TAKE_PHOTO = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button button = (Button) findViewById(R.id.button);
        mImageView = findViewById(R.id.imageView);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "clicked", Toast.LENGTH_SHORT).show();
                dispatchTakePictureIntent();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult: 0");
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Log.d(TAG, "onActivityResult: 1");

            Bundle extras = data.getExtras();
            Bitmap imageBitmap = (Bitmap) extras.get("data");
            mImageView.setImageBitmap(imageBitmap);
        }
    }

    private void dispatchTakePictureIntent() {
        Log.d(TAG, "dispatchTakePictureIntent: 0");
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            Log.d(TAG, "dispatchTakePictureIntent: 1");
            startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
        }
    }
}

每当我单击按钮(应该打开相机)时,应用程序就会崩溃。我可以从logcat中获得“ dispatchTakePictureIntent:1”,因此takePictureIntent.resolveActivity(getPackageManager())不会返回null。我认为是startActivityForResult(takePictureIntent,REQUEST_IMAGE_CAPTURE)导致应用崩溃。

这些代码是从官方文档https://developer.android.com/training/camera/photobasics#java中复制的。

我尝试了dispatchTakePictureIntent(View v),但该应用程序仍然崩溃。我还用下面的方法替换了dispatchTakePictureIntent(),它仍然崩溃了。

private void TakePicture(){
    Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
    startActivityForResult(intent, 0);
}

我一直在尝试在互联网上找到的其他解决方案,但没有一个提供帮助。可能是导致我的应用崩溃的问题?

3 个答案:

答案 0 :(得分:1)

我认为您尚未使用任何权限检查,因为对于低于23岁的android设备无需请求权限,但是对于高于23岁的android设备,则需要声明或要求用户访问android的功能。

如果设备运行的是Android 6.0(API级别23)或更高版本,并且应用程序的targetSdkVersion为23或更高版本,则在安装时不会通知用户任何应用程序权限。您的应用程序必须要求用户在运行时授予危险权限。当您的应用请求权限时,用户会看到一个系统对话框(如图1左所示),告诉用户您的应用正在尝试访问哪个权限组。该对话框包括“拒绝”和“允许”按钮。

根据此文档。

https://developer.android.com/guide/topics/permissions/overview


 if (ContextCompat.checkSelfPermission(thisActivity,    Manifest.permission.WRITE_CALENDAR)
        != PackageManager.PERMISSION_GRANTED) {
    // Permission is not granted
}


    // Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
        Manifest.permission.READ_CONTACTS)
        != PackageManager.PERMISSION_GRANTED) {

    // Permission is not granted
    // Should we show an explanation?
    if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
            Manifest.permission.READ_CONTACTS)) {
        // Show an explanation to the user *asynchronously* -- don't block
        // this thread waiting for the user's response! After the user
        // sees the explanation, try again to request the permission.
    } else {
        // No explanation needed; request the permission
        ActivityCompat.requestPermissions(thisActivity,
                new String[]{Manifest.permission.READ_CONTACTS},
                MY_PERMISSIONS_REQUEST_READ_CONTACTS);

        // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
        // app-defined int constant. The callback method gets the
        // result of the request.
    }
} else {
    // Permission has already been granted
}

Android文档中的示例代码 https://developer.android.com/training/permissions/requesting#java

答案 1 :(得分:1)

请尝试在android清单文件中授予相机权限。 <uses-permission android:name="android.permission.CAMERA"> </uses-permission>。 然后尝试用此Intent intent = new Intent("android.media.action.IMAGE_CAPTURE"); startActivity(intent);

替换您的意图代码

如果您不想使用设备相机,则还可以借助此库https://github.com/natario1/CameraView

使自己拥有自定义相机

答案 2 :(得分:0)

你可以这样使用

public static final int REQUEST_PICTURE_FROM_GALLERY = 10001;
public static final int REQUEST_PICTURE_FROM_CAMERA = 10002;

private File tempFileFromSource = null;
private Uri tempUriFromSource = null;
    
public void selectImageFromGallery() {
        
        try {

            tempFileFromSource  = File.createTempFile("choose", "png", context.getExternalCacheDir());
            tempUriFromSource   = Uri.fromFile(tempFileFromSource);

            Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUriFromSource);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            context.startActivityForResult(intent, REQUEST_PICTURE_FROM_GALLERY);

        } catch (IOException e) {
            e.printStackTrace();
        }

    }

 
    public void takePhotoWithCamera() {
        
        try {

            tempFileFromSource  = File.createTempFile("choose_", ".png", context.getExternalCacheDir());
            tempUriFromSource = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", tempFileFromSource);

            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, tempUriFromSource);
            intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            
            context.startActivityForResult(intent, REQUEST_PICTURE_FROM_CAMERA);

        } catch (IOException e) {
            e.printStackTrace();
        }


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if ((requestCode == REQUEST_PICTURE_FROM_GALLERY) && (resultCode == Activity.RESULT_OK)) {
            Log.d(TAG, "Image selected from gallery");
            prepareImage(data.getData(), tempFileFromSource);
        } else if ((requestCode == REQUEST_PICTURE_FROM_CAMERA) && (resultCode == Activity.RESULT_OK)) {
            Log.d(TAG, "Image selected from camera");
            prepareImage(tempUriFromSource, tempFileFromSource);
        }
    }

    private void prepareImage(Uri uri, File imageFile) {
        try {

            if (uri == null)
                return;

            Bitmap bitmap = BitmapUtils.decodeBitmap(context, uri, 300, 300);

            if (bitmap == null)
                return;
            
            // now you have bitmap
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static Bitmap decodeBitmap(Context context, Uri uri, int maxWidth, int maxHeight) throws IOException {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        InputStream imageStream = context.getContentResolver().openInputStream(uri);
        BitmapFactory.decodeStream(imageStream, null, options);
        if (imageStream != null)
            imageStream.close();

        // Calculate inSampleSize
        options.inSampleSize = calculateSize(options, maxWidth, maxHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        imageStream = context.getContentResolver().openInputStream(uri);
        Bitmap img = BitmapFactory.decodeStream(imageStream, null, options);

        img = rotateImageIfRequired(context, img, uri);
        return img;
    }