简体   繁体   English

如何检查android是否要重新创建活动或销毁?

[英]how to check if android going to recreate activity or destroy?

I have an android studio project. 我有一个android studio项目。 When I am rotating screen, android destroys and recreates main activity. 当我旋转屏幕时,android销毁并重新创建主要活动。 How can I check during the destruction, if android going to recreate activity? android是否要重新创建活动,如何在销毁期间检查?

You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing() in onDestroy . 您可以使用onDestroy isFinishing()通过用户选择确定活动是否完成(例如,用户选择通过回退退出isFinishing()

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (isFinishing()) {
      // wrap stuff up
    } else { 
      //It's an orientation change.
    }
  }

Another alternative (if you're only targeting API>=11) is isChangingConfigurations . 另一个替代方法(如果您仅定位API> = 11)是isChangingConfigurations

  @Override
  protected void onDestroy() {
    super.onDestroy();
    if (isChangingConfigurations()) {
      //It's an orientation change.
    }
  }

Override the Activity lifecycle methods to see the flow.And then use the appropriate method to check activity current state like isChangingConfigurations() Example code snippet. 覆盖Activity生命周期方法以查看流程,然后使用适当的方法检查isChangingConfigurations()示例代码段之类的当前状态。

MainActivity.java MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(MainActivity.class.getSimpleName(),"OnStart Called");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(MainActivity.class.getSimpleName(),"OnRestart Called");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(MainActivity.class.getSimpleName(),"OnDestroy Called");
    }


    @Override
    protected void onPause() {
        super.onPause();
        Log.i(MainActivity.class.getSimpleName(),"OnPause Called");
    }

   @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.i(MainActivity.class.getSimpleName(),"OnConfiguration Changed Called");
    }

}

For more details see the official page activity-lifecycle 有关更多详细信息,请参见官方页面活动生命周期

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

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