Android自定义相机应用程序崩溃,因为它开始“不幸停止”

时间:2014-04-04 09:04:31

标签: java android eclipse camera

我正在尝试构建自己的自定义相机应用程序我已经通过Android开发人员小组了解了如何编写整个应用程序的代码但是一旦我启动相机就会崩溃我不知道这里有什么问题是我的代码:

package com.example.tapeit;

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

import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Files.FileColumns;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;

public class CameraActivity extends Activity implements Camera.PictureCallback {

private Camera mCamera;
private CameraPreview mPreview;
String TAG = "TapeIt";
public static final int MEDIA_TYPE_IMAGE = 1;
Button captureButton;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.preview_layout);

    mCamera = getCameraInstance();

    mPreview = new CameraPreview(this, mCamera);

    FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
    preview.addView(preview);

    captureButton = (Button) findViewById(R.id.button_capture);
    captureButton.setOnClickListener(
            new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {
                    // TODO Auto-generated method stub
                    mCamera.takePicture(null, null, mPicture);
                }
            });

}


private boolean checkCameraHardware(Context context){
    if(context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA)){
        return true;
    }else{
        return false;
    }
}


public static Camera getCameraInstance() {
    // TODO Auto-generated method stub
    Camera c = null;
    try {
        c = Camera.open();
    } catch (Exception e) {

    }
    return c;
}


private PictureCallback mPicture  = new PictureCallback() {

    @Override
    public void onPictureTaken(byte[] data, Camera camera) {
        // TODO Auto-generated method stub
        File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
        if (pictureFile == null){
            Log.d(TAG, "Error creating media file, check storage permissions: " );
            return;
        }

        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            fos.write(data);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }
    }
};


private static File getOutputMediaFile(int mediaTypeImage) {
    // TODO Auto-generated method stub
    File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "CameraApp");

    if(! mediaStorageDir.exists()){
        if(! mediaStorageDir.mkdirs()){
             Log.d("MyCameraApp", "failed to create directory");
             return null;
        }
    }

    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    File mediaFile = new File(mediaStorageDir.getPath() + File.separator +"IMG_"+ timeStamp + ".jpg");
    return mediaFile;
}


@Override
public void onPictureTaken(byte[] data, Camera camera) {
    // TODO Auto-generated method stub
    File pictureFile = getOutputMediaFile(MEDIA_TYPE_IMAGE);
    if (pictureFile == null){
        Log.d(TAG, "Error creating media file, check storage permissions: " );
        return;
    }

    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        fos.write(data);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }
}


private void releaseCamera(){
    if (mCamera != null){
        mCamera.release();        // release the camera for other applications
        mCamera = null;
    }
}

}

这是我的预览课程:

package com.example.tapeit;

import java.io.IOException;

import android.content.Context;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.hardware.Camera;

public class CameraPreview extends SurfaceView implements SurfaceHolder.Callback{
private Camera mCamera;
private SurfaceHolder mHolder;
String TAG = "TapeIt";

public CameraPreview (Context context, Camera camera){
    super(context);
    mCamera = camera;
    mHolder = getHolder();
    mHolder.addCallback(this);
}

public void surfaceCreated(SurfaceHolder holder){
    try{
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    }catch(IOException e){
        Log.d(TAG, "Error setting camera preview" + e.getMessage());
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
    // TODO Auto-generated method stub
    if(mHolder.getSurface() == null){
        return;
    }

    try{
        mCamera.stopPreview();
    }catch(Exception e){

    }
    //You should make here changes when the device is rotated or when any other change
    // set preview size and make any resize, rotate or
    // reformatting changes here

    //mCamera.getParameters().getSupportedPreviewSizes();


    try{
        mCamera.setPreviewDisplay(holder);
        mCamera.startPreview();
    }catch(IOException e){
        Log.d(TAG, "Error setting camera preview" + e.getMessage());
    }


}

@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
    // TODO Auto-generated method stub

}

}

我的清单在这里使用了所有的权限:

<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-feature android:name="android.hardware.camera" />       

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.example.tapeit.CameraActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

我在控制台中的logcat发布在这里:

04-04 11:19:32.010: D/AndroidRuntime(21270): Shutting down VM
04-04 11:19:32.010: W/dalvikvm(21270): threadid=1: thread exiting with uncaught exception (group=0x40eb72a0)
04-04 11:19:32.010: E/AndroidRuntime(21270): FATAL EXCEPTION: main
04-04 11:19:32.010: E/AndroidRuntime(21270): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tapeit/com.example.tapeit.CameraActivity}: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2092)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread.access$700(ActivityThread.java:134)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.os.Handler.dispatchMessage(Handler.java:99)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.os.Looper.loop(Looper.java:137)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread.main(ActivityThread.java:4867)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at java.lang.reflect.Method.invokeNative(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at java.lang.reflect.Method.invoke(Method.java:511)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at dalvik.system.NativeStart.main(Native Method)
04-04 11:19:32.010: E/AndroidRuntime(21270): Caused by: java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.view.ViewGroup.addViewInner(ViewGroup.java:3439)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.view.ViewGroup.addView(ViewGroup.java:3310)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.view.ViewGroup.addView(ViewGroup.java:3255)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.view.ViewGroup.addView(ViewGroup.java:3231)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at com.example.tapeit.CameraActivity.onCreate(CameraActivity.java:39)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.Activity.performCreate(Activity.java:5047)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
04-04 11:19:32.010: E/AndroidRuntime(21270):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
04-04 11:19:32.010: E/AndroidRuntime(21270):    ... 11 more

1 个答案:

答案 0 :(得分:0)

preview.addView(preview);

您正在尝试将FrameLayout添加到自身。这不起作用。

据推测,参数应为mPreview

您可能希望为变量使用更多不同的名称,例如不同时使用previewmPreview