Search code examples
androidkotlinemailandroid-fragmentsdeep-linking

How to open a fragment through android deep link from mail?


I need to open a specific fragment in my application, on click of a confirmation link in the email app. Is it possible and if it is, could I receive information from this link?


Solution

  • First off all you need to add these codes in your manifest to <activity/>(For more information):

    <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
    
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
    
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
    
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
    
                <data
                    android:host="@string/APP_LINKS_URL"
                    android:scheme="http" />
            </intent-filter>
    
            <intent-filter android:autoVerify="true">
                <action android:name="android.intent.action.VIEW" />
    
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
    
                <data
                    android:host="@string/APP_LINKS_URL"
                    android:scheme="https" />
            </intent-filter>
        </activity>
    

    @string/APP_LINKS_URL is url address like some.address.com (For more info)

    After that, by clicking a link your activity starts with this link (like Uri: intent.data) in intent object. Based on this link you can open or navigate to the any fragment in your app. For navigating between screen you can use Navigation component navigation-deep-link.

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        //...
        if (intent.data?.toString()?.contains(getString(R.string.APP_LINKS_URL)) == true) {
            //your logic to navigate to specify fragment
        }
    }
    

    And you can get informations from this link (Uri): intent.data