我做了应用程序flasshlight但不幸地告诉我应用程序停止工作

时间:2016-10-09 09:58:35

标签: java android-studio

我有模拟器但速度超慢(AMD CPU)

好的,这里是代码

import android.app.Activity;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn = (Button)findViewById(R.id.btnpower);
private Camera cam1;
Camera.Parameters params;
private boolean isOn;

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

    cam1 = Camera.open();
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (isOn) {
                params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                cam1.setParameters(params);
                cam1.stopPreview();
                isOn = false;
                btn.setBackgroundResource(R.drawable.off);


            } else {
                params = cam1.getParameters();
                params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                cam1.setParameters(params);
                cam1.stopPreview();
                isOn = true;
                btn.setBackgroundResource(R.drawable.on);
            }
        }

    });
}

}

1 个答案:

答案 0 :(得分:0)

您需要在onCreate内和setContentView下方声明按钮。此外,在您的其他条件中,您应该cam1.stopPreview();而不是cam1.startPreview();。在 if 条件下,请确保放置cam1.release(); } cam1.stopPreview();以下。确保你已添加

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

这在manifest.xml中