Android应用程序崩溃,无法理解logcat找到原因

时间:2012-11-14 20:13:02

标签: android android-camera logcat

我在主要活动中有这段代码:

package flash.light.pro;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.graphics.Color;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.view.View.OnLongClickListener;


public class MainActivity extends Activity {
    private boolean isBlack = false;
    private boolean isLedOn = false;
    private boolean supportsCamera = true;
    private Camera camera;
    final Parameters p = camera.getParameters();
    protected void onStop() {
        super.onStop();

        if (camera != null) {
            camera.release();
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        final Button screen = (Button) findViewById (R.id.screen);
        Context context = this;
        PackageManager pm = context.getPackageManager();

        isBlack = false;
        setBrightness(255);

        if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
            Log.e("err", "Device has no camera!");
            supportsCamera = false;
        }


        try{
            camera = Camera.open();
        } catch (Exception e){
            Log.e(getString(R.string.app_name), "failed to open Camera");
            e.printStackTrace();
        }

        screen.setOnClickListener(new Button.OnClickListener(){  
            public void onClick(View v) { 
                if (isBlack){ 
                    screen.setBackgroundColor(Color.WHITE);
                    isBlack = false;
                    setBrightness(255);
                }
                else{
                    screen.setBackgroundColor(Color.BLACK);
                    isBlack = true;
                    setBrightness(0);
                }
            }
        });

        if(supportsCamera){
            screen.setOnLongClickListener(new OnLongClickListener() {
                public boolean onLongClick(View v) {
                    if(isLedOn){
                        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                        camera.setParameters(p);
                        camera.startPreview();
                        return true;
                    }
                    else{
                        p.setFlashMode(Parameters.FLASH_MODE_OFF);
                        camera.setParameters(p);
                        camera.stopPreview();
                        return true;
                    }
                }
            });
        }
    }

    private void setBrightness(int brightness) {
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.screenBrightness = brightness / 100.0f;
        getWindow().setAttributes(layoutParams);
    }
}

和这个androidManifest.xml代码:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="flash.light.pro"
    android:versionCode="1"
    android:versionName="1.0" >

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

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
     <permission android:name="android.permission.FLASHLIGHT"
             android:permissionGroup="android.permission-group.HARDWARE_CONTROLS"
             android:protectionLevel="normal"
             android:label="string/permlab_flashlight"/>

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

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

这是LogCat日志:

11-14 20:05:06.772: D/AndroidRuntime(380): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
11-14 20:05:06.772: D/AndroidRuntime(380): CheckJNI is ON
11-14 20:05:07.371: D/AndroidRuntime(380): Calling main entry com.android.commands.pm.Pm
11-14 20:05:07.392: D/AndroidRuntime(380): Shutting down VM
11-14 20:05:07.400: I/AndroidRuntime(380): NOTE: attach of thread 'Binder Thread #3' failed
11-14 20:05:07.411: D/dalvikvm(380): GC_CONCURRENT freed 101K, 71% free 297K/1024K, external 0K/0K, paused 1ms+1ms
11-14 20:05:07.411: D/dalvikvm(380): Debugger has detached; object registry had 1 entries
11-14 20:05:07.830: D/AndroidRuntime(390): >>>>>> AndroidRuntime START com.android.internal.os.RuntimeInit <<<<<<
11-14 20:05:07.830: D/AndroidRuntime(390): CheckJNI is ON
11-14 20:05:08.390: D/AndroidRuntime(390): Calling main entry com.android.commands.am.Am
11-14 20:05:08.420: I/ActivityManager(61): Starting: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] 

flg=0x10000000 cmp=flash.light.pro/.MainActivity } from pid 390
11-14 20:05:08.450: I/ActivityManager(61): Start proc flash.light.pro for activity flash.light.pro/.MainActivity: pid=398 uid=10040 gids={1006}
11-14 20:05:08.480: D/AndroidRuntime(390): Shutting down VM
11-14 20:05:08.490: D/dalvikvm(390): GC_CONCURRENT freed 102K, 69% free 319K/1024K, external 0K/0K, paused 1ms+3ms
11-14 20:05:08.500: D/dalvikvm(390): Debugger has detached; object registry had 1 entries
11-14 20:05:09.270: D/AndroidRuntime(398): Shutting down VM
11-14 20:05:09.270: W/dalvikvm(398): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-14 20:05:09.330: E/AndroidRuntime(398): FATAL EXCEPTION: main
11-14 20:05:09.330: E/AndroidRuntime(398): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

{flash.light.pro/flash.light.pro.MainActivity}: java.lang.NullPointerException
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1569)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.os.Looper.loop(Looper.java:123)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread.main(ActivityThread.java:3683)
11-14 20:05:09.330: E/AndroidRuntime(398):  at java.lang.reflect.Method.invokeNative(Native Method)
11-14 20:05:09.330: E/AndroidRuntime(398):  at java.lang.reflect.Method.invoke(Method.java:507)
11-14 20:05:09.330: E/AndroidRuntime(398):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-14 20:05:09.330: E/AndroidRuntime(398):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-14 20:05:09.330: E/AndroidRuntime(398):  at dalvik.system.NativeStart.main(Native Method)
11-14 20:05:09.330: E/AndroidRuntime(398): Caused by: java.lang.NullPointerException
11-14 20:05:09.330: E/AndroidRuntime(398):  at flash.light.pro.MainActivity.<init>(MainActivity.java:22)
11-14 20:05:09.330: E/AndroidRuntime(398):  at java.lang.Class.newInstanceImpl(Native Method)
11-14 20:05:09.330: E/AndroidRuntime(398):  at java.lang.Class.newInstance(Class.java:1409)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
11-14 20:05:09.330: E/AndroidRuntime(398):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1561)
11-14 20:05:09.330: E/AndroidRuntime(398):  ... 11 more
11-14 20:05:09.410: W/ActivityManager(61):   Force finishing activity flash.light.pro/.MainActivity
11-14 20:05:09.940: W/ActivityManager(61): Activity pause timeout for HistoryRecord{4060c450 flash.light.pro/.MainActivity}
11-14 20:05:20.739: W/ActivityManager(61): Activity destroy timeout for HistoryRecord{4060c450 flash.light.pro/.MainActivity}
11-14 20:06:00.031: I/dalvikvm(61): Jit: resizing JitTable from 1024 to 2048
11-14 20:06:19.377: D/SntpClient(61): request time failed: java.net.SocketException: Address family not supported by protocol
11-14 20:08:35.071: I/Process(398): Sending signal. PID: 398 SIG: 9
11-14 20:08:35.081: I/ActivityManager(61): Process flash.light.pro (pid 398) has died.
11-14 20:08:35.111: W/InputManagerService(61): Window already focused, ignoring focus gain of: com.android.internal.view.IInputMethodClient$Stub

$Proxy@4051a740

应用程序在启动时崩溃,没有错误,日志对我来说不明确。我该怎么做才能解决它。为什么应用程序应该是某种FlashLight。谢谢你的帮助。

2 个答案:

答案 0 :(得分:10)

private Camera camera;
final Parameters p = camera.getParameters();

camera尚未初始化

我能够通过查看你的第22行来找到它,因为logcat输出显示。 不要被logcat中的信息量所淹没,通常会找到包名的第一个实例来指示问题的原因/位置。

编辑:作为旁注,您的包名称应该是反向域名顺序。因此,例如,如果您的应用程序名为flashlightpro,并且您的域名是example.com,则您的程序包名称应为com.example.flashlightpro。这不是必需的,但它是标准惯例。

编辑2:将摄像机声明更改为:Camera camera = Camera.open();

编辑3:Android文档涉及拍照,但在您的情况下,步骤1,2,3,10非常重要:

Obtain an instance of Camera from open(int).
Get existing (default) settings with getParameters().
If necessary, modify the returned Camera.Parameters object and call setParameters(Camera.Parameters).
...
Important: Call release() to release the camera for use by other applications. Applications should release the camera immediately in onPause() (and re-open()it in onResume()).

http://developer.android.com/reference/android/hardware/Camera.html

答案 1 :(得分:2)

您正在尝试访问未初始化的内容,这就是获取Null Pointer Exception的原因。日志清楚地说明了这一点。

检查您的活动第22行,您正在尝试访问尚未初始化的相机。

Caused by: java.lang.NullPointerException
11-14 20:05:09.330: E/AndroidRuntime(398):  at flash.light.pro.MainActivity.<init>    (MainActivity.java:22)