Kolpobilash Kawser Kolpobilash Kawser - 21 days ago 8
Android Question

Camera flash is not working in android

I am trying to make a simple app that will on button click turn the camera flash on and on another click it will turn off so that we can use it as an torch light. But the flash is not turing on. below is my flashfragment

public class FlashFragment extends Fragment {

private boolean isLighOn = false;
private Camera camera;
private Button button;

public FlashFragment() {
// Required empty public constructor
}

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

}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_flash, container, false);
button = (Button) rootView.findViewById(R.id.buttonFlashlight);

Context context = getActivity();
PackageManager pm = context.getPackageManager();

// if device support camera?
if (!pm.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Log.e("err", "Device has no camera!");

}
try{
camera = Camera.open();
final Camera.Parameters p = camera.getParameters();

button.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View arg0) {

if (isLighOn) {

Log.i("info", "torch is turn off!");

p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.stopPreview();
isLighOn = false;

} else {

Log.i("info", "torch is turn on!");

p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.startPreview();
isLighOn = true;

}

}
});
}catch(Exception e){
e.printStackTrace();
}

// Inflate the layout for this fragment
return rootView;
}

@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}

@Override
public void onDetach() {
super.onDetach();
}
}

Answer

You just missed the line to set parameter to the camera

camera.setParameters(p);

So, your code for onClickListener should look something like following

 button.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            if (isLighOn) {

                Log.i("info", "torch is turn off!");

                p.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
                camera.setParameters(p);
                camera.stopPreview();
                isLighOn = false;

            } else {

                Log.i("info", "torch is turn on!");

                p.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
                camera.setParameters(p);
                camera.startPreview();
                isLighOn = true;

            }

        }
    });

This should solve your problem. it always works in my case.