简体   繁体   中英

Recover a method after a screen rotation on android

I read that after a screen rotation, an android activity is created again. I understood how to recover a view, but i don't understand if i can start from where a method was stopped after a screen rotation.

If there was a method that was executing at the moment you turned your screen, the method will finish its work.

It wont be paused or anything else since its "impossible" to do that.

If that particular method was important to your app/activity you should then call it again upon Activity recreation.

Recover after screen rotation.

In it's simplest form you save what you need to recreate where you left off in the onSaveInstanceState method. So for your basic flashlight you save the state of the light. For you more complex apps your saving all of the global fields. Flashlight has a global variable isFlashOn.

private boolean isFlashOn = false;

save the state of the flashlight in the onSaveInstanceState

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putBoolean(ISON, isFlashOn);
}

Then in the oncreate method you recreate the global variable.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    if (savedInstanceState != null) {
        isFlashOn = savedInstanceState.getBoolean(ISON);
    } 

later in the onstart method process the isFlashOn. This flashlight is turned on by a click so I change the state of isFlashOn and call the click handler.

@Override
protected void onStart() {
    super.onStart(); // Always call the superclass method first

    if (camera == null) {
        camera = Camera.open();
    }
            //flip the isflashon and then click the button
    isFlashOn = !isFlashOn;
    onClick(null);
}

process the click.

public void onClick(View arg0) {
    ImageButton i = (ImageButton) findViewById(R.id.imageButton1);

    final Parameters p = camera.getParameters();
    if (isFlashOn) {
        i.setImageResource(R.drawable.ic_launcher);
        isFlashOn = false;
        p.setFlashMode(Parameters.FLASH_MODE_OFF);
    } else {
        i.setImageResource(R.drawable.ic_launcher2);
        p.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(p);
        // Set flag to true
        camera.startPreview();
        isFlashOn = true;
    }

Good Luck

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM