2

I have created an android app which will allow the user to switch on and switch off the flash light by pressing a button. If the user switch on the flash light and change the orientation, the light is getting switched off. Why this is happening. Please see the code below which i used.

cam = Camera.open();
    final Parameters p = cam.getParameters();

    torch_switch = (Button)findViewById(R.id.torch_switch);
    torch_switch.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {


            // TODO Auto-generated method stub
            if(isLightOn) {
                torch_switch.setText("Switch ON Torch");
                p.setFlashMode(Parameters.FLASH_MODE_OFF);
                cam.setParameters(p);
                cam.stopPreview();
                isLightOn = false;

            } else {
                torch_switch.setText("Switch OFF Torch");
                p.setFlashMode(Parameters.FLASH_MODE_TORCH);
                cam.setParameters(p);
                cam.startPreview();
                isLightOn = true;
            }
        }
    });
Kamalone
  • 4,045
  • 5
  • 40
  • 64

2 Answers2

2

Changing orientation causes your app to destroy its current activity and then recreate it, essentially starting the app again from the start.

You could fix it by disallowing orientation changes in the manifest, or store the current mode in your 'onStop' method and then restoring it in 'OnStart', possibly.

Sean O'Toole
  • 4,304
  • 6
  • 35
  • 43
1

Easiest way out is to Fix your orientation, add the following to your manifest

<activity android:name=".abc" android:screenOrientation="portrait" />

In this way, even if your app is rotated, the orientation wont change. If you plan to handle orientation changes, then go for the solution from Sean O'Toole

Royston Pinto
  • 6,681
  • 2
  • 28
  • 46