Flash灯应用

时间:2014-10-24 12:28:55

标签: android flash android-camera

我正在使用开关按钮制作简单的火炬应用程序。点击开关按钮闪光模式开启但没有关闭。

我的代码:

package com.shibli.torch;

import android.os.Bundle;
import android.app.Activity;
import android.hardware.Camera.Parameters;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Switch;

 public class MainActivity extends Activity {
Switch  s;
android.hardware.Camera cam;
Parameters params;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    s=(Switch) findViewById(R.id.switch1);
    s.setOnCheckedChangeListener(new OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton arg0, boolean v) {


  if( s.isChecked()){
try {
    cam = android.hardware.Camera.open();
    params = cam.getParameters();
} catch (RuntimeException e) {
}
finally{
    params.setFlashMode(Parameters.FLASH_MODE_TORCH);
    cam.setParameters(params);
    cam.startPreview();
    ;
}} 
 else
 {
 params = cam.getParameters();
 params.setFlashMode(Parameters.FLASH_MODE_OFF);
 cam.setParameters(params);
 cam.stopPreview();
 }



        }
    });

}


}

xml布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:tools="http://schemas.android.com/tools"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:background="#000000"  >

    <Switch
        android:id="@+id/switch1"
        android:layout_width="fill_parent"
        android:layout_height="45dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:gravity="center"
      />

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

首先,在这种情况下,finaly()不是一个好主意,因为如果cam无法初始化,你将得到一个NullPointerException。其次,使用checkedChangeListener中的boolean值。我会这样做(没有经过测试,但应该指向正确的方向):

      s.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean isChecked) {


    if(isChecked==true){
          try {
           cam = android.hardware.Camera.open();
           params = cam.getParameters();
           params.setFlashMode(Parameters.FLASH_MODE_TORCH);
           cam.setParameters(params);
           cam.startPreview();

          } catch (RuntimeException e) {
               //Toast for the user, that it doesn´t work
          }    
        }else{

      if(cam!=null){
      params = cam.getParameters();
      params.setFlashMode(Parameters.FLASH_MODE_OFF);
      cam.setParameters(params);
      cam.stopPreview();
    }
 }