我有一个简单的应用程序,button
可以打开/关闭camera flash
:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button)findViewById(R.id.btnFlash);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!isLight)
{
switchON();
}
else
{
switchOFF();
}
}
});
}
如果闪光灯关闭,它将打开,否则,关闭。是的,效果很好。
问题是:
- 首先,我按下button
打开,之后,我旋转设备,然后再次按下关闭 - >应用程序崩溃。
致命异常:主要 - 运行时异常:无法连接到摄像头 服务
这两个功能可以打开/关闭
public void switchON()
{
camera = Camera.open();
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
camera.startPreview();
isLight = true;
}
public void switchOFF()
{
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
camera.release();
isLight = false;
}
答案 0 :(得分:1)
试试这个(我重写了代码):
public class YourClass extends Activity {
private Button button;
private Camera camera;
private boolean isLight=false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.btnFlash);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!isLight)
{
switchON();
}
else
{
switchOFF();
}
}
});
}
@Override
protected void onResume() {
super.onResume();
try{
camera = Camera.open();
} catch( Exception e ){
e.printStackTrace();
}
}
@Override
protected void onPause() {
if( camera != null ){
camera.release();
camera = null;
}
super.onPause();
}
private void switchOFF(){
if( mCamera != null ){
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
isLight = false;
}
}
private void switchON(){
if( mCamera != null ){
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_TORCH);
camera.setParameters(p);
isLight=true;
}
}
}
答案 1 :(得分:0)
尝试:
public void switchOFF()
{
if(camera == null)
{
camera = Camera.open();
}
Parameters p = camera.getParameters();
p.setFlashMode(Parameters.FLASH_MODE_OFF);
camera.setParameters(p);
camera.stopPreview();
camera.release();
isLight = false;
}