3

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 ?

darsh
  • 741
  • 4
  • 10
  • 34

3 Answers3

5

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();
}
Dharmendra
  • 33,296
  • 22
  • 86
  • 129
  • Thanks for your effort. I tried this. The problem still persists. The activity C is not launched – darsh May 04 '12 at 06:29
1

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));

Krishnakant Dalal
  • 3,568
  • 7
  • 34
  • 62
0

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);
}
Nazik
  • 8,696
  • 27
  • 77
  • 123
Raghul Sugathan
  • 350
  • 1
  • 7
  • 22