Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/179.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
计算我的android应用程序打开的次数并处理屏幕方向_Android_Screen Orientation_Android Orientation - Fatal编程技术网

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

计算我的android应用程序打开的次数并处理屏幕方向,android,screen-orientation,android-orientation,Android,Screen Orientation,Android Orientation,详细地说,我正在计算我的应用程序在SharedReferences界面的帮助下打开的次数,并在屏幕上显示该次数,但每当我改变方向时,该次数仍会增加 我不想在纵向上粘贴布局,我希望我的应用程序可以使用两个方向。onCreate的代码如下所示: protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.d(TAG, "onCreate!"); mP

详细地说,我正在计算我的应用程序在SharedReferences界面的帮助下打开的次数,并在屏幕上显示该次数,但每当我改变方向时,该次数仍会增加

我不想在纵向上粘贴布局,我希望我的应用程序可以使用两个方向。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。请尝试将相关代码放在OnStart中。

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

@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);
    }