计算我的Android应用程序打开和处理屏幕方向的次数

时间:2014-07-07 20:36:42

标签: android screen-orientation android-orientation

详细地说,我在界面SharedPreferences的帮助下计算我的应用程序打开的次数,并在屏幕上显示计数,但是当我更改orientation时,计数仍会增加。

我不想以纵向方式粘贴布局,我希望我的应用可以使用两种方向,onCreate()的代码如下所示:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate!");

    mPrefs = getPreferences(MODE_PRIVATE);

    int count = mPrefs.getInt(COUNT, 0);

    count = count + 1;
    Editor editor = mPrefs.edit();
    editor.putInt(COUNT, count);
    editor.commit();

    mTextView = new TextView(this);
    mTextView.setTextSize(40);
    mTextView.setText("Count: " + count);
    Log.d(TAG, "Count is " + count);
    setContentView(mTextView);
    // setContentView(R.layout.activity_main);

    mTextView.setOnClickListener(this);

}

2 个答案:

答案 0 :(得分:0)

只要设备方向发生变化,就会调用OnCreate。请尝试将相关代码放入OnStart中。

答案 1 :(得分:0)

您只能在未通过savedInstanceState保存时增加计数,因为在更改方向时会调用onSaveInstaceState

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

    if (savedInstanceState != null) {
        if (savedInstanceState.containsKey(KEY)){
            count = savedInstanceState.getInt(KEY);
        } 
    } else {
        count = mPrefs.getInt(COUNT, 0);
        count += 1;
        Editor editor = mPrefs.edit();
        editor.putInt(COUNT, count);
        editor.commit();
    }
}

    @Override
    protected void onSaveInstanceState (Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(KEY, count);
    }