相机无法正常工作?

时间:2018-01-05 07:30:59

标签: java android debugging

我正在开发一款应用程序,只是为了打开相机并拍摄图像。我是新手,我无法理解我做错了什么。请有人帮我这个,我在这里发布我的java代码和XML代码:

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
    android:id="@+id/textView2"
    android:layout_width="206dp"
    android:layout_height="172dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:text="2nd activity" />

    <Button
    android:id="@+id/button"
    android:layout_width="100dp"
    android:layout_height="100dp"
    android:layout_alignParentBottom="true"
    android:layout_marginBottom="69dp"
    android:layout_toEndOf="@+id/textView2"
    android:text="Camera"
    app:layout_constraintBottom_toTopOf="@+id/textView2"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0" />

    <ImageView
    android:id="@+id/camera"
    android:layout_width="100dp"
    android:layout_height="92dp"
    android:layout_above="@+id/button"
    android:layout_alignParentEnd="true"
    android:layout_marginBottom="119dp"
    android:layout_marginEnd="31dp"
    app:layout_constraintBottom_toTopOf="@+id/textView2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/button"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.0"
    app:srcCompat="@android:drawable/ic_menu_camera" />
    </RelativeLayout>

Java代码

    package com.chiragsharmaengineer.linked_layouts;

    import android.app.Activity;
    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.os.Bundle;
    import android.provider.MediaStore;
    import android.view.View;
    import android.widget.Button;
    import android.widget.ImageView;



    public class newActivity extends Activity {

    final int CAMERA_PIC_REQUEST = 1888;

    @Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Get the view from new_activity.xml
    setContentView(R.layout.activity_new);

    //Camera
    Button camera = (Button) findViewById(R.id.button);
    camera.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent cameraIntent = new 
        Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

           }
         });

        }

        protected void onActivityResult(int requestCode, int resultCode, 
        Intent data) {
        if (requestCode == CAMERA_PIC_REQUEST) {
        Bitmap image = (Bitmap) data.getExtras().get("data");
        ImageView imageview = findViewById(R.id.camera); //sets imageview as 
        the bitmap
        imageview.setImageBitmap(image);

            }
          } 
        } 

ImageView选项未显示在布局上,每当我单击相机按钮时,它只会打开之前的布局。应用程序没有崩溃,但没有做任何事情。如果您提供详细的解决方案,我将不胜感激。

3 个答案:

答案 0 :(得分:0)

试试这个

package com.chiragsharmaengineer.linked_layouts;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;



public class newActivity extends Activity {

final int CAMERA_PIC_REQUEST = 1888;
ImageView imageview ;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get the view from new_activity.xml
setContentView(R.layout.activity_new);

//Camera
 imageview = findViewById(R.id.camera); //sets imageview as 
Button camera = (Button) findViewById(R.id.button);
camera.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent cameraIntent = new 
    Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);

       }
     });

    }

    @Override
   public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
   if (requestCode == CAMERA_PIC_REQUEST ) {
    Bitmap image = (Bitmap) data.getExtras().get("data");
    imageview.setImageBitmap(image);
    } 
 }

答案 1 :(得分:0)

你忘了要求permisssions,因为Marshmallow你需要在运行时请求它们:

1)创建一个新的java类 PermissionUtils 并粘贴此代码:

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.v4.app.ActivityCompat;

public class PermissionUtils {

    public static final int REQUEST_EXTERNAL_STORAGE = 1000;
    public static final int REQUEST_CAMERA = 2000;



    public static void requestExternal(Activity context) {
        if (!checkExternal(context)) {
            ActivityCompat.requestPermissions(context, new String[]{
                            Manifest.permission.READ_EXTERNAL_STORAGE,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    REQUEST_EXTERNAL_STORAGE);
        }
    }


    public static void requestCamera(Activity context) {
        if (!checkCamera(context)) {
            ActivityCompat.requestPermissions(context, new String[]{
                            Manifest.permission.CAMERA},
                    REQUEST_CAMERA);
        }
    }


    public static boolean checkExternal(Context context) {
        return !(ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED);
    }


    public static boolean checkCamera(Context context) {
        return !(ActivityCompat.checkSelfPermission(context, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED);
    }
}

2)然后在 newActivity 类中,在 onCreate()方法中添加这两行

@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Get the view from new_activity.xml 
    // Premission check lines go here!
    PermissionUtils.requestCamera(this);
    PermissionUtils.requestExternal(this);

现在,应用程序会在启动时询问您是否获得权限,相机意图是否有效。我还获得了EXTERNAL_STORAGE权限,因为我想你想稍后保存图片,对吗?

答案 2 :(得分:0)

public void capturePhoto() {
        String myTargetImageFilePath = Environment.getExternalStorageDirectory().toString() + "/test.jpg";

        File cameraPhotoFile = new File(myTargetImageFilePath);
        Uri CameraFileUri = null;
        if (cameraPhotoFile == null) {
            Toast.makeText(this,
                    "01 - Error: While getting the storage Name file for Camera ... ",
                    Toast.LENGTH_LONG).show();
        } else {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                CameraFileUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName()
                                + ".provider",
                        cameraPhotoFile);
            } else {
                CameraFileUri = Uri.fromFile(cameraPhotoFile);
            }
            callToCamera(this,
                    CameraFileUri);

        }
    }

    public static void callToCamera(Activity theActivity, final Uri theCameraFileUri) {

            System.out.println("theCameraFileUri:" + theCameraFileUri);
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, theCameraFileUri); // set the image file name
            theActivity.startActivityForResult(intent, SELECT_IMAGE_FROM_CAMERA_CODE);
    }


        @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SELECT_IMAGE_FROM_CAMERA_CODE) {
            //Here data is null because we are selecting image from camera
            if (data == null) {
                myImageViewSelected.setImageBitmap(createBitmap(myTargetImageFilePath.toString(), 300, 300));
            }
        }
    }


    public static Bitmap createBitmap(String theTargetFile, int theReqHight, int theReqWidth) {
        BitmapFactory.Options bmOptions = new BitmapFactory.Options();
        Bitmap bitmap = BitmapFactory.decodeFile(theTargetFile, bmOptions);
        bitmap = Bitmap.createScaledBitmap(bitmap, theReqWidth, theReqHight, true);
        return bitmap;
    }