How to launch an app using a deeplink in android
Asked Answered
I

2

18

I want to launch app using my own app but not by giving the package name, I want to open a custom URL.

I do this to start an application.

Intent intent = getPackageManager().getLaunchIntentForPackage(packageInfo.packageName);
startActivity(intent);

Instead of package name is it possible to give a deep-link for example:

"mobiledeeplinkingprojectdemo://product/123"

Reference

Ingressive answered 8/9, 2014 at 10:18 Comment(0)
C
27

You need to define a activity that will subscribe to required intent filters:

<activity
    android:name="DeepLinkListener"
    android:exported="true" >

    <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />      
        <data
            android:host="host"
            android:pathPattern="some regex"
            android:scheme="scheme" />
    </intent-filter>
</activity>

Then in onCreate of your DeepLinkListener activity you can access the host, scheme etc.:

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Intent deepLinkingIntent= getIntent();
    deepLinkingIntent.getScheme();
    deepLinkingIntent.getData().getPath();
}

Perform check on path and again fire a Intent to take the user to corresponding activity. Refer data documentation for more help.

Now fire a Intent:

Intent intent = new Intent (Intent.ACTION_VIEW);
intent.setData(Uri.parse(DEEP_LINK_URL));
Cowshed answered 8/9, 2014 at 10:28 Comment(3)
Hey thanks, but is there a way doing it without specifying anything in the xml file and also what is this deepLinkingIntent ?Ingressive
If you know the activity to launch then why don't you launch it via intent directly?Cowshed
This answer is addressing the opposite of the question.Sebastian
H
6

Don't forget to handle the exception. If there is no activity that can handle the deep link, startActivity will return an exception.

    try {
    context.startActivity(
        Intent(Intent.ACTION_VIEW).apply {
            data = Uri.parse(deepLink)
        }
    )
} catch (exception: Exception) {
    Toast.makeText(context, exception.localizedMessage, Toast.LENGTH_LONG).show()
}
Handiness answered 7/6, 2021 at 21:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.