Amyth
Amyth

Reputation: 32969

Android: camera's startPreview method not working after stopPreview

In my application i have an image button that basically switches on and off the flash LED. The code is running fine for the first time i.e. On first Click it Switches On the LED and on the Second Click it Switches it Off. But then Nothing happens third Click onwards. I am testing this on Nexus S.

Following is the Code for the ImageButton Click Method.

public void ToggleTorch(){
    final ImageButton tt = (ImageButton)findViewById(R.id.tt);
    tt.setOnClickListener(new OnClickListener(){
        @Override
        public void onClick(View v){
            if (isFlashOn){
                mycam.stopPreview();
                isFlashOn = false;
            } else {
                mycam.startPreview();
                isFlashOn = true;
            }
        }
    });
}

From what i think, it has to do something with the SurfaceView as i think it is not being destroyed while calling stopPreview but i am not sure..

Following is the Code for the onCreate Method.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    //Check if Flash Light is Available
    Boolean has_flash = this.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);
    if(has_flash){
        setContentView(R.layout.activity_main);
        SurfaceView preview = (SurfaceView)findViewById(R.id.pSv);
        SurfaceHolder holder = preview.getHolder();
        holder.addCallback(this);
        holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        disableSleepMode();
        initFlashLight();
        ToggleTorch();
        screenTorchOn();
    } else {
        setContentView(R.layout.activity_main);
        disableSleepMode();
        screenTorchOn();
    }
}

any help would be appreciated. Thanks.

Upvotes: 0

Views: 2197

Answers (1)

Milind
Milind

Reputation: 83

instead of calling stop preview release camera and make camera instance null. To restart camera, initialize camera again. Make two different method one for initialize camera and another to release it. This will solve your problem.

Upvotes: 1

Related Questions