I’m developing an Android app with three activities: MainActivity
, LoginActivity
, and WebViewActivity
. The MainActivity
is the launcher activity and determines if the user is logged in or not. Based on this, it starts either the LoginActivity
or WebViewActivity
.
I define the the MainActivity
as a launcher in the AndroidManifest.xml
file.
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.MyApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
In the MainActivity’s onCreate method, I determine which Activity to launch.
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
MyAppTheme {
Surface(
modifier = Modifier.fillMaxSize(),
color = colorResource(id = R.color.white)
) {
val intent: Intent = getIntentForInitialLaunch()
startActivity(intent)
// finish() ← tried finishing the activity but did not solve the issue.
}
}
}
}
private fun getIntentForInitialLaunch(): Intent {
val activityToLaunch = if (hasLoggedIn()) {
WebViewActivity::class.java
} else {
LoginActivity::class.java
}
return Intent(this, activityToLaunch)
}
}
The problem I’m facing is with the back button behavior. When the user navigates back from either the LoginActivity
or WebViewActivity
, they see the MainActivity
, which is just a blank screen in my case. For a better user experience, I don’t want the MainActivity
to be visible at all when the user navigates back. Instead, I want the app to be sent to the background and resume the WebViewActivity
when the app is reopened.
I tried calling the finish() method in MainActivity
to prevent it from being shown, but this causes another issue: when the user reopens the app from the background, it restarts from the splash screen, losing the state of the WebViewActivity
. This means the user loses their place in the WebView and has to start over from the root URL.
Here’s a summary of the flow:
MainActivity
checks login status in onCreate().
If logged in, starts WebViewActivity
; if not, start LoginActivity
.
Pressing back in either LoginActivity
or WebViewActivity
currently shows MainActivity
(undesired).
Calling finish() in MainActivity
solves the back button issue but causes the app to restart from the splash screen when reopened, losing WebView state.
How can I achieve the following:
Prevent MainActivity
from being visible when navigating back from LoginActivity
or WebViewActivity
.
Keep the state of the WebViewActivity
when the app is reopened from the background.
Any suggestions or best practices for handling this scenario would be greatly appreciated.