Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
790 views
in Technique[技术] by (71.8m points)

android - onCreate(...) is called twice after the device is rotated

I have a question about rotating the Android device. My code logs a static and non-static attribute in onCreate(...).

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    static int sn;
    int n;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        sn++;
        n++;

        Log.i("onCreate", String.format("sn=%d n=%d", sn, n));
    }
}

The screen orientation is portrait. When I first ran the code, I got:

onCreate(): sn=1 n=1

After I rotated the screen to landscape, I got:

onCreate(): sn=2 n=1

After I rotated the screen again to portrait, I got:

onCreate(): sn=3 n=1
onCreate(): sn=4 n=1

My questions are:

  1. How can I prevent onCreate(...) to be called twice when the device is rotated back to portrait?
  2. How can I save the value of non-static variable when the device is rotated?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is a known issue in the emulator (see the discussion here). It's not a bug, but it is an issue for many people going back years. As I understand it, the basic problem is that your activity is restarted twice when it goes into portrait mode because the emulator is handling two configuration changes separately: the orientation change itself and the deactivation of the keyboard. It doesn't happen in the other direction because there isn't a configuration change event corresponding to activation of the keyboard. (I find this strange, but evidently this is the desired behavior for some reason.)

In any event, the solution seems to be this to add this to your activity manifest declaration:

android:configChanges="keyboardHidden|orientation"

If you actually require those changes to load new resources, you can manually handle it in onConfigurationChanged.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...