Launch Fragment (instead of Activity) from Android 7.1 App Shortcut

4.9k views Asked by At

I have decided to look at adding static shortcuts into an application, using this page as reference:

https://developer.android.com/preview/shortcuts.html

The XML for my shortcuts currently looks like so:

<?xml version="1.0" encoding="utf-8"?>
<shortcuts xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <shortcut
        android:shortcutId="id"
        android:enabled="true"
        android:icon="@drawable/icon"
        android:shortcutShortLabel="@string/short_label"
        android:shortcutLongLabel="@string/long_label"
        android:shortcutDisabledMessage="@string/disabled_message">
        <intent
            android:action="android.intent.action.VIEW"
            android:targetPackage="com.example"
            android:targetClass="com.example.Activity" />
        <categories android:name="android.shortcut.category" />
    </shortcut>
</shortcuts>

The issue comes from the targetClass variable as I cannot find a way to launch a Fragment rather than an Activity. Most of the main pages I would want to launch from the shortcuts are Fragments displayed within an Activity. How can I get the intent to launch straight to a Fragment instead?

3

There are 3 answers

8
Tin Tran On BEST ANSWER

You can do the following:

1) In the intent specified in shortcuts.xml, set a custom intent action string:

 <intent
        android:action="com.your.packagename.custom.name"
        android:targetPackage="com.example"
        android:targetClass="com.example.Activity" />

2) Check for the getIntent().getAction() for intent action in the Activity specified in android:targetClass:

public void onCreate(Bundle savedInstanceState){
    if (CUSTOM_NAME.equals(getIntent().getAction())) {
        // do Fragment transactions here 
    }
}
0
Sampath Kumar On

You can also do the redirection on navigation component with DeepLink navigation, The shortcut xml intent will look like below:

<intent
        android:action="android.intent.action.VIEW"
        android:data="<Your deeplink URI, like appname://feature-to-be-names>"
        android:targetClass="activity class with package name"
        android:targetPackage="application id"/>

And the onCreate() -> in activity to handle the deeplink navigation

intent.dataString?.let {
        navHostFragment.findNavController().navigate(Uri.parse(it), false)
    }

This will take care of the multiple shortcut and redirection.

2
Matthias Robbers On

You can easily achieve this with the Shortbread library.

class MainActivity : AppCompatActivity() {
        
    @Shortcut(id = "movies", shortLabel = "Movies", icon = R.drawable.ic_shortcut_movies)
    fun showMovies() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.fragment_container, MoviesFragment())
            .commit()
    }
}