Reputation: 751
I have three Activities - A B and C, of which B is a Tab Activity. Activity A is launched first, and B is launched from A. I finish Activity A when B is launched using this code
public void onStop() {
super.onStop();
this.finish();
}
Now I want to launch Activity C when back key is pressed in B.
I tried overriding back key using this code
@Override
public void onBackPressed() { this.getParent().onBackPressed();
}
This doesn't Help as the Parent Activity is finished while launching the Child Activity. What actually happens when I press back key is that the Activity exits to the Home screen.
I tried overriding the back key and setting an Intent to it
@Override
public void onBackPressed() {
Intent backIntent = new Intent();
backIntent.setClass(this, main.class);
startActivity(backIntent);
}
This also doesn't help me. What could be a possible solution to this problem, How can I launch Activity C when back key is pressed ?
Upvotes: 3
Views: 2029
Reputation: 370
Override the below method and import event.....
public boolean onKeyDown(int keyCode, KeyEvent event)
{
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK)
{
//Write your intent or other code here
}
return super.onKeyDown(keyCode, event);
}
Upvotes: 0
Reputation: 33996
First you should not finish the activity A when Activity A stops this is completely wrong approach instead of it you have to finish activity when you start activity B.
For example
Intent i = new Intent(this, B.class);
startActivity(i);
finish();
Now you want to start the activity C when user press the back button so use the below code.
@Override
public void onBackPressed() {
Intent backIntent = new Intent(this, C.class);
startActivity(backIntent);
super.onBackPressed();
}
Upvotes: 5
Reputation: 3578
You have to override onKeyDown
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if (keyCode == event.KEYCODE_BACK)
{
//Do your code here
}
return super.onKeyDown(keyCode, event);
}
}
This will be called when user pressed Device Hard Back Button.
To navigate to next activity: StartActivity(new Intent(getApplicationContext(),main.class));
Upvotes: 1