Android - 应用程序仅在首次启动时崩溃,但第二次运行

时间:2016-07-16 07:49:14

标签: java android

我的Android手电筒应用程序出现问题。当我尝试在应用程序打开时按下设备的主页按钮然后恢复(通过单击主屏幕上的应用程序图标而不是最近的应用程序按钮),应用程序崩溃。在我从最近的应用程序列表中终止应用程序然后再次打开之后,它不再使用上述相同的说明崩溃。

请参阅以下代码。

public class MainActivity extends Settings {

public Camera camera;
public Camera.Parameters parameters;
public ImageButton flashLightButton;
boolean isFlashLightOn = false;
MediaPlayer mySound;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    flashLightButton = (ImageButton)findViewById(R.id.flashlight_button);
    flashLightButton.setOnClickListener(new FlashOnOffListener());


    registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    mySound = MediaPlayer.create(this, R.raw.balloon_snap);

    if (isFlashSupported()) {
        camera = Camera.open();
        parameters = camera.getParameters();
    } else {
        showNoFlashAlert();
    }

    Settings.active = false;

    //super.onCreate(savedInstanceState);
    //Set layout we created
    //setContentView(R.layout.activity_main);
    //Register the receiver which triggers event
    //when battery charge is changed



}

public void settings(View view)
{

    Intent intent = new Intent(MainActivity.this, Settings.class);
    startActivity(intent);
    this.finish();
}


private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver() {
    @Override
    //When Event is published, onReceive method is called
    public void onReceive(Context c, Intent i) {
        //Get Battery %
        int level = i.getIntExtra("level", 0);
        //Find the progressbar creating in main.xml
        ProgressBar pb = (ProgressBar) findViewById(R.id.progressbar);
        //Set progress level with battery % value
        pb.setProgress(level);
        //Find textview control created in main.xml
        TextView tv = (TextView) findViewById(R.id.textfield);
        //Set TextView with text
        tv.setText("" + Integer.toString(level) + "");
    }

};

public class FlashOnOffListener implements View.OnClickListener{


    SharedPreferences sharedPrefs = getSharedPreferences("VibrateSettings", MODE_PRIVATE);
    Boolean vibration = sharedPrefs.getBoolean("VibrateSet", false);

    SharedPreferences sharedPrefs2 = getSharedPreferences("SoundSettings", MODE_PRIVATE);
    Boolean sound = sharedPrefs2.getBoolean("SoundSet", false);

    @Override
    public void onClick(View v) {

        if(isFlashLightOn){
            flashLightButton.setImageResource(R.drawable.flashlight_off);
            parameters.setFlashMode(Parameters.FLASH_MODE_OFF);
            camera.setParameters(parameters);
            camera.stopPreview();
            isFlashLightOn = false;

            if(vibration == true){
                // Get instance of Vibrator from current Context
                Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                // Vibrate for 400 milliseconds
                vib.vibrate(20);
            }
            else {
                // Get instance of Vibrator from current Context
                Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                // Vibrate for 400 milliseconds
                vib.vibrate(00);
        }
            if (sound == true){
                mySound.start();
            }

        }else{
            flashLightButton.setImageResource(R.drawable.flashlight_on);
            parameters.setFlashMode(Parameters.FLASH_MODE_TORCH);
            camera.setParameters(parameters);
            camera.startPreview();
            isFlashLightOn = true;

            if(vibration == true){
                // Get instance of Vibrator from current Context
                Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                // Vibrate for 400 milliseconds
                vib.vibrate(20);
            }
            else {
                // Get instance of Vibrator from current Context
                Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
                // Vibrate for 400 milliseconds
                vib.vibrate(00);
            }
            if (sound == true){
                mySound.start();
            }

        }

    }

}

private void showNoFlashAlert() {
    new AlertDialog.Builder(this)
            .setMessage("Your device hardware does not support flashlight!")
            .setIcon(android.R.drawable.ic_dialog_alert).setTitle("Error")
            .setPositiveButton("Ok", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finish();
                }
            }).show();
}

private boolean isFlashSupported() {
    PackageManager pm = getPackageManager();
    return pm.hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
}



@Override
protected void onDestroy() {
    if(camera != null){
        camera.stopPreview();
        camera.release();
        camera = null;
    }
    super.onDestroy();
}}

的AndroidManifest.xml

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="19" />

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

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".Settings"
        android:label="@string/app_name">
    </activity>

</application>

logcat的

E/AndroidRuntime(22941): FATAL EXCEPTION: main

E/AndroidRuntime(22941): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.johncarlo.flashlight/com.example.johncarlo.flashlight.MainActivity}: java.lang.RuntimeException: Fail to connect to camera service

E/AndroidRuntime(22941):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2186)

E/AndroidRuntime(22941):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2236)

E/AndroidRuntime(22941):    at android.app.ActivityThread.access$600(ActivityThread.java:145)

E/AndroidRuntime(22941):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1238)

E/AndroidRuntime(22941):    at android.os.Handler.dispatchMessage(Handler.java:99)

E/AndroidRuntime(22941):    at android.os.Looper.loop(Looper.java:137)

E/AndroidRuntime(22941):    at android.app.ActivityThread.main(ActivityThread.java:5099)

E/AndroidRuntime(22941):    at java.lang.reflect.Method.invokeNative(Native Method)

E/AndroidRuntime(22941):    at java.lang.reflect.Method.invoke(Method.java:511)

E/AndroidRuntime(22941):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:803)

E/AndroidRuntime(22941):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:570)

E/AndroidRuntime(22941):    at dalvik.system.NativeStart.main(Native Method)

E/AndroidRuntime(22941): Caused by: java.lang.RuntimeException: Fail to connect to camera service

E/AndroidRuntime(22941):    at android.hardware.Camera.native_setup(Native Method)

E/AndroidRuntime(22941):    at android.hardware.Camera.<init>(Camera.java:365)

E/AndroidRuntime(22941):    at android.hardware.Camera.open(Camera.java:338)

E/AndroidRuntime(22941):    at com.example.johncarlo.flashlight.MainActivity.onCreate(MainActivity.java:49)

E/AndroidRuntime(22941):    at android.app.Activity.performCreate(Activity.java:5117)

E/AndroidRuntime(22941):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)

E/AndroidRuntime(22941):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2150)

E/AndroidRuntime(22941):    ... 11 more

W/ActivityManager(  786):   Force finishing activity com.example.johncarlo.flashlight/.MainActivity

1 个答案:

答案 0 :(得分:1)

从onCreate中删除以下行并将其写入onResume,这样做后可能不会崩溃。

@Override
protected void onResume() {
    super.onResume();
    registerReceiver(mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}