studentknight
studentknight

Reputation: 163

How to make return to previous Activity with on back pressed?

I have an activity called MainAct and SubAct. MainAct is the parent of SubAct.

In SubAct, I am playing a music background. In order to stop the music when I press back button, I implement this code below :

@Override 
    public void onBackPressed(){
      if (tick != null){
          if(tick.isPlaying())
              tick.stop();

          tick.release();
      }
 }

With that code, the music is stopped as I expected. but the problem is I cannot go back from subAct to MainAct...

I know this is trivial, but can you show me the correct way to do this?

Upvotes: 2

Views: 16330

Answers (5)

Raghunandan
Raghunandan

Reputation: 133560

Call finish() This is will pop the current activity from back stack and the previous Activity in the back stack takes focus.

Also look at the activity lifecycle and stop your music in onStop() or onDestroy().

Clicking back button will call finish(). No need to override onBackPressed(). Just handle the life cycle methods methods properly.

Upvotes: 2

Glenn
Glenn

Reputation: 12809

Just put back your super.onBackPressed() call

@Override 
public void onBackPressed() {
      if (tick != null){
          if(tick.isPlaying())
              tick.stop();

          tick.release();
      }

     super.onBackPressed();
 }

super.onBackPressed() because if we look in Activity.java (Android 2.2)

public void onBackPressed() {
        finish();
}

Upvotes: 8

Jitesh Upadhyay
Jitesh Upadhyay

Reputation: 5260

just use

@Override 
public void onBackPressed() {
      if (tick != null){
          if(tick.isPlaying())
              tick.stop();

          tick.release();
      }

     super.onBackPressed();
 }

You need super.onBackPressed(); because when you called super class onBackPressed what it is doing is, it is calling finish();

or diectly you can write

@Override 
public void onBackPressed(){
    if (tick != null){
        if(tick.isPlaying())
            tick.stop();

        tick.release();
        finish();
    }
}

Upvotes: 2

Hamid Shatu
Hamid Shatu

Reputation: 9700

Just call the following method inside the onBackPressed() method and this will close your activity...

finish();

as follows...

@Override 
public void onBackPressed(){
    if (tick != null){
        if(tick.isPlaying())
            tick.stop();

        tick.release();
        finish();
    }
}

You can also do this by calling super.onBackPressed() inside your onBackPressed()...so that it will maintain the default behavior of onBackPressed() method...

@Override 
public void onBackPressed(){

    super.onBackPressed()

    if (tick != null){
        if(tick.isPlaying())
            tick.stop();

        tick.release();
        finish();
    }
}

Upvotes: 4

android_dev_
android_dev_

Reputation: 402

Call the finish() method to end the current activity.

Upvotes: 3

Related Questions