0

In order to reproduce my issue I made a tiny project. It has two activities.

Here is the MainActivity.kt file:

package me.soft.trybackbtnaction

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }


    fun fireSubActivity(view: View) {
        val intent = Intent(this, SubActivity::class.java).apply {}
        startActivity(intent)
    } /* End of fireSubActivity */
}

Here is the SubActivity.kt file:

package me.soft.trybackbtnaction

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log

class SubActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sub)
    }


    override fun onBackPressed() {
        super.onBackPressed()
        println("onBackPressed CALLED")
    }
}

And this is the AndroidManifest.xml file:

<application
    android:allowBackup="true"
    android:dataExtractionRules="@xml/data_extraction_rules"
    android:fullBackupContent="@xml/backup_rules"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.TryBackBtnAction"
    tools:targetApi="31">
    <activity
        android:name=".SubActivity"
        android:exported="false"
        android:parentActivityName=".MainActivity" />
    <activity
        android:name=".MainActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

And to be complete below are the activities XML files.

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="fireSubActivity"
        android:text="Fire Sub-Activity"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

activity_sub.xml :

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".SubActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello Sub-Activity"
        android:textSize="34sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

When running the app and tapping the back arrow from the sub-activity I expect the onBackPressed() function to be called, but that does not happen.

Michel
  • 10,303
  • 17
  • 82
  • 179
  • did you check other Activity lifecycle methods? are they called? – Faisal ur Rehman Jul 22 '22 at 06:31
  • Have you tried using the new `onBackPressedDispatcher`? – Darshan Jul 22 '22 at 08:01
  • @Faisal ur Rehman. onCreate, onResume, onStop, onDestroy are all called. Only onBackPressed for some unknown reason is not called. – Michel Jul 22 '22 at 14:13
  • @DarShan. No I didn't try that. Is it something that I need to do to make it work ? – Michel Jul 22 '22 at 14:23
  • Its a new api, however your `onBackPressed` should've worked, but you can try the newer one as well. – Darshan Jul 22 '22 at 15:00
  • I would like to know why `onBackPressed` did not work. Do you have any idea what could be the reason? – Michel Jul 23 '22 at 05:11
  • @DarShan. By the way I am trying to find out how to use onBackPressedDispatcher. I am not able to find any good tutorial. Is onBackPressedDispatcher supposed to be used with fragments or not? In my current app I am not using fragments. – Michel Aug 03 '22 at 06:37
  • I've added an example via Answer. – Darshan Aug 03 '22 at 06:45

1 Answers1

0

You can try the new onBackPressedDispatcher on the newer versions of the AppCompatActivity which work for both Fragment & Activities.

Example:

  1. Activity
onBackPressedDispatcher.addCallback(this, object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // handle back press here.
    }
})
  1. Fragment
val dispatcher = requireActivity().onBackPressedDispatcher
dispatcher.addCallback(this, object : OnBackPressedCallback(true) {
    override fun handleOnBackPressed() {
        // handle back press in fragments.
    }
})
Darshan
  • 4,020
  • 2
  • 18
  • 49
  • Thank you for this answer. I can use it as a base to try out something. Before thinking about how to properly use this onBackPressedDispatcher/onBackPressed thing; I already noticed some missunderstanding on my part. When I talk about the back button I am referring to the button made available inside the app when adding android:parentActivityName="..." to the activity inside AndroidManifst.xml. But the back button firing onBackPressed is not the same "back button". It is the "hardware button" displayed at the botton of the phone independently of the app. – Michel Aug 03 '22 at 15:01
  • So I need to say that I want to know wich function fires up when the app back button is touched. – Michel Aug 03 '22 at 15:01
  • do you mean the ‘back arrow’ button on the left side of the toolbar? – Darshan Aug 03 '22 at 15:02
  • See my new post to see what I mean: https://stackoverflow.com/questions/73231342/how-to-handle-the-application-back-button-in-an-android-app – Michel Aug 04 '22 at 06:41