Issue
I made two activities for the test.
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this, SubActivity.class));
}
}
@Override
protected void onDestroy() {
super.onDestroy();
}
}
This button in MainActivity can start SubActivity.
public class SubActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
...
}
@Override
protected void onDestroy() {
super.onDestroy();
}
@Override
public void onBackPressed() {
startActivity(new Intent(SubActivity.this, MainActivity.class));
}
}
When in SubActivity, press back button, it doesn't call onDestroy() in SubActivity class and start MainActivity. What I want to do is, How to call SubActivity onDestroy() when I finish the MainActivity? It doesn't call SubActivity onDestroy() when I press the back button in MainActivity. Is there any solution like using Intent.FLAG_ACTIVITY?
Solution
You should finish() your SubActivity in onBackPressed to destroy it and go back to your MainActivity, instead of doing a startActivity. In many cases, that is the behavior you'll get even if you don't implement onBackPressed yourself. Your current code is starting a second MainActivity.
Answered By - Ryan M
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.