I have an android studio project. When I am rotating screen, android destroys and recreates main activity. How can I check during the destruction, if android going to recreate activity?
问问题
2235 次
2 回答
6
You can determine if the activity is finishing by user choice (user chooses to exit by pressing back for example) using isFinishing()
in onDestroy
.
@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
.
@Override
protected void onDestroy() {
super.onDestroy();
if (isChangingConfigurations()) {
//It's an orientation change.
}
}
于 2019-07-14T10:32:00.343 回答
0
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.
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
于 2019-07-14T10:38:55.817 回答