Junior — Middle
Kuidas saab push-teavituse abil liikuda konkreetse Fragmenti juurde?
sobes.tech AI
Vastus AI-lt
To navigate to a specific Fragment via a push notification, a common approach is to use an Intent with additional data (extras), which is passed to the Activity, and then the Activity decides which Fragment to display.
Approximate algorithm:
- In the push notification, pass data indicating the desired Fragment (e.g., a string identifier or enum).
- In the method handling the notification click (PendingIntent), create an Intent to start the Activity.
- In the Activity, in onCreate or onNewIntent, read the data from the Intent and replace the Fragment with the required one.
Code example:
// When creating the notification
val intent = Intent(context, MainActivity::class.java).apply {
putExtra("target_fragment", "profile")
}
val pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT)
// In MainActivity
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val targetFragment = intent.getStringExtra("target_fragment")
if (targetFragment != null) {
val fragment = when(targetFragment) {
"profile" -> ProfileFragment()
"settings" -> SettingsFragment()
else -> DefaultFragment()
}
supportFragmentManager.beginTransaction()
.replace(R.id.fragment_container, fragment)
.commit()
}
}
This way, when the user taps the notification, they are directly taken to the desired screen.