是否可以检查onCreate是否因为方向改变而被调用?

Eug*_*ene 17 android

我需要在onStart()方法上采取不同的行动,这取决于onCreate()结果是否被调用orientation change.有可能检查一下吗?

实际上我需要的是something在活动开始时做的事情, 除非用户改变方向的情况.

我需要清楚地区分用户刚刚切换到另一个应用程序并返回的情况,或者他改变了设备的方向.

tos*_*tos 14

按照Nahtan的想法,我写了这个:

在onCreate()中:

if ( (oldConfigInt & ActivityInfo.CONFIG_ORIENTATION)==ActivityInfo.CONFIG_ORIENTATION ) {
    // ... was rotated
} else {
    // ... was not rotated
}
Run Code Online (Sandbox Code Playgroud)

在onDestroy()中:

super.onDestroy();
oldConfigInt = getChangingConfigurations();
Run Code Online (Sandbox Code Playgroud)


Moh*_*ikh 10

public class MyActivity extends Activity {
    boolean fromOrientation=false;
    SharedPreferences myPrefLogin;
    Editor prefsEditor;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        prefsEditor = myPrefLogin.edit();
        myPrefLogin = this.getSharedPreferences("myPrefs", Context.MODE_WORLD_READABLE);
        fromOrientation = myPrefLogin.getString("fromOrient", false);

        if(fromOrientation) {
             // do as per need--- logic of orientation changed.
        } else {
             // do as per need--- logic of default onCreate().
        }
    }

    @Override
    public Object onRetainNonConfigurationInstance() {
        prefsEditor.putString("fromOrient", true);
        prefsEditor.commit();
        return null;
    }

    @Override
    protected void onDestroy() {
        if(fromOrientation) {
            prefsEditor.putString("fromOrient", false);
            prefsEditor.commit();
        }
        super.onDestroy();
    }  
}
Run Code Online (Sandbox Code Playgroud)

标志fromOrientation(告诉状态,无论配置是否已经改变)我们已经完成了上面的defalut,我们正在考虑onCreate()不通过改变方向来调用.如果orientation更改了(onRetainNonConfigurationInstance()),那么我们首先设置标志值,让我们知道是否onCreate()从on方向调用.最后onDestroy()我们再次重置方向标志.

  • 应该是putboolean (2认同)

Nat*_*Fig 5

只需检查捆绑包:当活动首次启动时,捆绑包将为空。如果方向发生变化,则它应该是非空的。

来自安卓文档

如果活动在先前关闭后重新初始化,则此 Bundle 包含它最近在 onSaveInstanceState(Bundle) 中提供的数据。注意:否则为空。

编辑:我认为您不必在 onSaveInstanceState 中提供一个捆绑包,使其在方向更改后变为非空,但这将是微不足道的。


Nat*_*Fig 5

尝试getChangingConfigurations.使用此选项可以发现由于方向更改而导致活动被销毁的时间,设置标志,并在调用onCreate时检查该标志.

这样做的好处是,让您知道活动重新启动的原因,而不会覆盖清单中的方向配置.