Search code examples
androidback-button

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?


Solution

  • 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();
    }