106

I have upgraded targetSdkVersion and compileSdkVersion to 33.

Now getting warning onBackPressed is deprecated.

It is suggested to use use OnBackInvokedCallback or androidx.activity.OnBackPressedCallback to handle back navigation instead. Anyone can help me to use the updated method.

Example:

onBackPressedDeprecated

Use Case: I use if (isTaskRoot) {} inside onBackPressed(){} method to check activity is last on the activity-stack.

override fun onBackPressed() {
    if (isTaskRoot) { // Check this activity is last on the activity-stack.(Check Whether This activity opened from Push-Notification)
        startActivity(Intent(mContext, Dashboard::class.java))
        finish()
    } else {
        finishWithResultOK()
    }
}
9
  • 1
    If you're just calling super.onBackPressed(), then you can just remove the method entirely as you're not writing any custom back behavior. If you are writing custom back behavior, show your code. Jun 15, 2022 at 16:19
  • @ianhanniballake , I am using if (isTaskRoot) {} inside onBackPressed() to check activity is last on the activity-stack. I have also updated the question. Jun 23, 2022 at 13:08
  • You shouldn't be doing that at all on any API level. Please include your code. Jun 23, 2022 at 13:27
  • The product detail page is opening clicking on the push notification. If the app is closed, now the user enters in product-detail-page clicking on push notification. Then clicking onBackpress, the user should not directly exit the app. for this case I use onBackPressed(). Jun 23, 2022 at 14:36
  • 1
    Did you figure out the isTaskRoot conditional? Most the answer seem to be very focused on trivial use-cases.
    – TWiStErRob
    Oct 9, 2022 at 21:03

15 Answers 15

85

Replace onBackPressed() with below code.

onBackPressedDispatcher.onBackPressed()
3
  • Voilà, I'm using targetSdk 33
    – Josh
    Feb 22 at 21:01
  • 4
    For fragment - requireActivity().onBackPressedDispatcher.onBackPressed()
    – Agilanbu
    Feb 27 at 7:06
  • Xamarin code: OnBackPressedDispatcher.OnBackPressed();
    – Gerry
    Mar 5 at 18:36
75

According your API level register:

This requires to at least use appcompat:1.6.0-alpha03; the current is 1.6.0-alpha04:

 implementation 'androidx.appcompat:appcompat:1.6.0-alpha04'
// kotlin
import androidx.activity.addCallback

if (BuildCompat.isAtLeastT()) {
    onBackInvokedDispatcher.registerOnBackInvokedCallback(
        OnBackInvokedDispatcher.PRIORITY_DEFAULT
    ) {
        // Back is pressed... Finishing the activity
        finish()
    }
} else {
    onBackPressedDispatcher.addCallback(this /* lifecycle owner */, object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            // Back is pressed... Finishing the activity
            finish()
        }
    })
}

// ====================================================
/* Or for lambda simplicity: */
// ====================================================
if (BuildCompat.isAtLeastT()) {
    onBackInvokedDispatcher.registerOnBackInvokedCallback(
        OnBackInvokedDispatcher.PRIORITY_DEFAULT
    ) {
        // Back is pressed... Finishing the activity
        finish()
    }
} else {
    onBackPressedDispatcher.addCallback(this /* lifecycle owner */) {
        // Back is pressed... Finishing the activity
        finish()
    }
}


UPDATE:

Thanks to @ianhanniballake comment; you can just use OnBackPressedDispatcher even in API level 33+

The OnBackPressedDispatcher is already going to be using the Android T specific API internally when using Activity 1.6+,

So, you can just do:

// kotlin
import androidx.activity.addCallback

onBackPressedDispatcher.addCallback(this /* lifecycle owner */, object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // Back is pressed... Finishing the activity
        finish()
    }
})

// ====================================================
/* Or for lambda simplicity: */
// ====================================================
onBackPressedDispatcher.addCallback(this /* lifecycle owner */) {
    // Back is pressed... Finishing the activity
    finish()
}

// java
import androidx.activity.OnBackPressedCallback;

getOnBackPressedDispatcher().addCallback(this, new OnBackPressedCallback(true) {
    @Override
    public void handleOnBackPressed() {
        // Back is pressed... Finishing the activity
        finish();
    }
});

Note that you shouldn't override the onBackPressed() as that will make the onBackPressedDispatcher callback not to fire; check this answer for clarifying that.

15
  • 11
    The OnBackPressedDispatcher is already going to be using the Android T specific API internally when using Activity 1.6+, so there's absolutely no reason to ever use the Android T APIs directly - you can just use the OnBackPressedDispatcher on all API levels. Jun 15, 2022 at 16:46
  • 1
    The problem I see here is now you have two ways to handle back press which is kinda messy. Is there any way to restrict overriding of the old onBackPressed? Jun 25, 2022 at 22:02
  • How can I invoke OnBackPressedCallback handleOnBackPressed programmatically, say I have a button that needs to call onBackPressed() programmatically? Jun 25, 2022 at 22:14
  • @BitwiseDEVS AFAIK, still onBackPressed() exposed to developers; at some newer API this shouldn't be true; but handling both simultaneously isn't that right as the note left at the end of the answer.
    – Zain
    Jun 27, 2022 at 22:20
  • 1
    @Zain It was my fault: I was extending Activity instead of AppCompatActivity. Sorry! Oct 16, 2022 at 0:48
32

With a combination of top answers. Here is a solution :

1. When you need to press the back button, copy this :

Note: it will automatically destroy your activity.

button.setOnClickListener {
    onBackPressedDispatcher.onBackPressed()
}

2. When you need to handle the back button pressed, copy this :

onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // Whatever you want
        // when back pressed
        println("Back button pressed")
        finish()
    }
})
22

Simply replace

override fun onBackPressed() {
      super.onBackPressed() //Replace this is deprecated line
}

with

override fun onBackPressed() {
      onBackPressedDispatcher.onBackPressed() //with this line
}

Update:

As we know override fun onBackPressed() is also deprecated so also replace this function with code below:

onBackPressedDispatcher.addCallback(this, object: OnBackPressedCallback(true) {
override fun handleOnBackPressed() {
    println("Back button pressed")
    // Code that you need to execute on back press i.e. finish()
  }
})

The above code we need to write inside some method like onCreate() function.

0
10

In Kotlin, this way is working

1- Remove onBackPressed()

2- below onCreate(savedInstanceState: Bundle?) add these lines:

 if (Build.VERSION.SDK_INT >= 33) {
        onBackInvokedDispatcher.registerOnBackInvokedCallback(
            OnBackInvokedDispatcher.PRIORITY_DEFAULT
        ) {
           
            exitOnBackPressed()
        }
    } else {
        onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                  
                    Log.i("TAG", "handleOnBackPressed: Exit")
                    exitOnBackPressed()
                }
            })
    }

3- Define a new function for handling

fun exitOnBackPressed() {
}
7

You could use the onBackPressedDispatcher

onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
         
    }
})

in here "this" means the lifeCycleOwner

0
5
import android.os.Bundle
import androidx.activity.OnBackPressedCallback
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.dialog.MaterialAlertDialogBuilder

class SampleActivity : AppCompatActivity(R.layout.activity_sample) {

    private val onBackPressedCallback: OnBackPressedCallback = object : OnBackPressedCallback(true) {
        override fun handleOnBackPressed() {
            showAppClosingDialog()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        onBackPressedDispatcher.addCallback(this, onBackPressedCallback)
    }

    private fun showAppClosingDialog() {
        MaterialAlertDialogBuilder(this)
            .setTitle("Warning")
            .setMessage("Do you really want to close the app?")
            .setPositiveButton("Yes") { _, _ -> finish() }
            .setNegativeButton("No", null)
            .show()
    }
}
4

You can use the OnBackInvokedCallback

OnBackInvokedCallback as described in the documentation and follow this guide here to update your code

1
3

Bonus: To close DrawerLayout when onBackPressed use like below (according to this I/O talk),

val callback = onBackPressedDispatcher.addCallback(this, false) {
    binding.drawerLayout.closeDrawer(GravityCompat.START)
}
            
binding.drawerLayout.addDrawerListener(object : DrawerListener {  
        
    override fun onDrawerOpened(drawerView: View) {
        callback.isEnabled = true
    }
        
    override fun onDrawerClosed(drawerView: View) {
        callback.isEnabled = false
    }

    override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit    
    override fun onDrawerStateChanged(newState: Int) = Unit
})
3

Here is the extension function to implement OnBackPressedCallback in activity.

fun AppCompatActivity.addOnBackPressedDispatcher(onBackPressed: () -> Unit = { finish() }) {
    onBackPressedDispatcher.addCallback(
        this,
        object : OnBackPressedCallback(true) {
            override fun handleOnBackPressed() {
                onBackPressed.invoke()
            }
        }
    )
}

Usage:

addOnBackPressedDispatcher {
    //doSomething()
}
3
  • Are there any code samples for Xamarin C#? I have seen one for .NET but it used a private class and I couldn't get it to compile. I have tried installing some new Nuget classes, but that just became a rathole. Is there a simple way to replace my OnBackPressed calls? Thanks
    – fbs419
    Oct 12, 2022 at 23:35
  • 2
    The function should better be called addOnBackPressedCallback(), because that is what it does. There is only one Dispatcher which handles all the callbacks.
    – Ridcully
    Dec 5, 2022 at 14:26
2

use onBackPressedDispatcher.onBackPressed() instead of super.onBackPressed()

override fun onBackPressed() {
  onBackPressedDispatcher.onBackPressed() 
}
0

override the onDismiss() function for BottomSheets.

override fun onDismiss(dialog: DialogInterface) {
   super.onDismiss(dialog)
   //TODO your logic.
   }
0

For Kotlin Users:

If you are trying to call the Default Native Back Button function using the 'new' way, you can use the code bellow inside your Activity.

this@MyActivity.onBackPressedDispatcher.onBackPressed()

example:

myCloseButton.setOnClickListener { this@MyActivity.onBackPressedDispatcher.onBackPressed() }

The example above sets a click function inside a button, to make the button act like the Native Android Back Button.

However, if you want to customize the onBackPressedDispatcher, you can follow the example bellow, always inside your Activity, because this behaviour needs an Activity Context to work.

Example of Customized OnBackPressed:

override fun onCreate(savedInstanceState: Bundle?) {
    
   val callback: OnBackPressedCallback = object : OnBackPressedCallBack(true) {
        override fun handleOnBackPressed() {
            //ToDo Implement your custom event here    
        }
    }

    this@MyActivity.onBackPressedDispatcher.addCallback(this@MyActivity, callback)
}

The expected result is to make any onBackPressedDispatcher event to do whatever you want, or do nothing at all. But this is not recommended, since your user might get stuck in a screen, without being able to use his Phone's Back Button. Because of that, avoid leaving handleOnBackPressed override empty. So try something like this:

override fun handleOnBackPressed() {
    this@MyActivity.finish()
}
2
  • A little more detail would be nice
    – Maruf Alam
    Feb 22 at 9:53
  • I add some details to this answer. I hope you guys can make good use. Feel free to ask any questions inside this Thread Answer. Mar 6 at 19:45
0

To set up ability to override default behaviour: (call setupBackPressedHandling() From Activity onCreate()):

  private fun setupBackPressedHandling() {
        onBackPressedDispatcher.addCallback(this) {
            if (!backPressHandled())
                invokeDefaultBackPressedHandling()
        }
    }

open fun backPressHandled(): Boolean = false

Global extension function:

  fun AppCompatActivity.invokeDefaultBackPressedHandling(navController: NavController?) {
    when(navController) {
        null -> {
            if (!supportFragmentManager.isStateSaved && !supportFragmentManager.popBackStackImmediate())
                finish()
        }
        else -> {
            if (!navController.popBackStack())
                finish()
        }
    }
}
-1

Use like below,

override fun onClick(v: View?) {
    when (v?.id) {
        R.id.iv_back -> onBackPressedMethod()
    }
}

and now create that method for handling back event

private fun onBackPressedMethod(){
    if (Build.VERSION.SDK_INT >= 33) {
        onBackInvokedDispatcher.registerOnBackInvokedCallback(
            OnBackInvokedDispatcher.PRIORITY_DEFAULT) {
            // back button pressed... finishing the activity
            finish()
        }
    } else {
        onBackPressedDispatcher.addCallback(
            this,
            object : OnBackPressedCallback(true) {
                override fun handleOnBackPressed() {
                // back button pressed... finishing the activity
                finish()
                }
            })
    }
}

That's it!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.