简体   繁体   English

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

[英]Counting the number of times my android app opens and handling screen orientation

In detail, I am counting the number of times my app opens with the help of the interface SharedPreferences and showing that count on screen but when ever I change orientation the count still increments. 详细地说,我是在界面SharedPreferences的帮助下统计我的应用程序打开的次数,并在屏幕上显示该计数,但是无论何时我改变orientation ,计数仍会增加。

I do not want to stick the layout in portrait, I want both orientations available for my app the code for the onCreate() is shown below: 我不想将布局保持纵向,我希望两个方向都可用于我的应用程序, 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);

}

OnCreate is called whenever the devices orientation changes. 只要设备方向发生变化,就会调用OnCreate。 Try putting the relevant code in OnStart instead. 尝试将相关代码放在OnStart中。

You could only increment the count when it hasn't been saved via savedInstanceState because onSaveInstaceState is called when the orientation is changed 您只能在尚未通过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);
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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