zaro

How to make a link open an app on Android?

Published in Android App Linking 8 mins read

The most effective and secure way to make a link open an app on Android is by implementing Android App Links. This allows your app to handle web URLs (HTTP/HTTPS links) directly, providing a seamless user experience that bypasses the need for a disambiguation dialog (the "Open with..." chooser).

What Are Android App Links?

Android App Links are a specific type of deep link that Google introduced to improve the user experience and security of linking to app content. Unlike standard deep links, Android App Links are verified associations between your website and your Android app. When a user clicks a verified URL, the system immediately opens your app to the relevant content, without asking the user which app to use. If your app isn't installed, the link gracefully falls back to opening in a web browser.

Implementing Android App Links: A Step-by-Step Guide

Creating Android App Links involves three primary stages: configuring your Android app to recognize URLs, handling the incoming link data within your app, and establishing a secure, verifiable association with your website.

Step 1: Create Deep Links in Your App Manifest

As specified in the reference, the foundational step is to "In your app manifest, create intent filters for your website URIs". This declaration tells the Android system which specific web URLs your app is capable of handling.

You achieve this by adding an <intent-filter> element within the <activity> tag of the Activity you want to launch.

  • Manifest Configuration Components:

    • <action android:name="android.intent.action.VIEW" />: This action indicates that the intent is for displaying data to the user.
    • <category android:name="android.intent.category.DEFAULT" />: This category ensures your activity can be launched by an implicit intent.
    • <category android:name="android.intent.category.BROWSABLE" />: This category is essential as it allows the intent to be executed by a web browser, making the link clickable.
    • <data> tag: This is where you define the specific URL structure your app will handle.
      • android:scheme="http" and android:scheme="https": Define the protocols (HTTP and HTTPS are crucial for web links).
      • android:host="yourwebsite.com": Specifies the domain of your website.
      • android:pathPrefix, android:pathPattern, or android:path: (Optional) Allows you to match specific URL paths or patterns within your domain (e.g., /products/ or /users/*).
      • android:autoVerify="true": This is critical for Android App Links. It instructs the Android system to verify that your app is indeed the official handler for the specified domains. This verification step removes the disambiguation dialog.
  • Example Manifest Entry:

    Here's an example of how this might look in your AndroidManifest.xml file, focusing on a MainActivity that handles URLs from www.example.com and example.com.

    <manifest ...>
        <application ...>
            <activity
                android:name=".MainActivity"
                android:exported="true"> <!-- Must be true for external links to open it -->
                <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:scheme="http"
                        android:host="www.example.com"
                        android:pathPrefix="/products/" />
                    <data
                        android:scheme="https"
                        android:host="www.example.com"
                        android:pathPrefix="/products/" />
                    <data
                        android:scheme="http"
                        android:host="example.com" />
                    <data
                        android:scheme="https"
                        android:host="example.com"
                        android:autoVerify="true" /> <!-- Apply autoVerify to all relevant data tags -->
                </intent-filter>
                <!-- Other intent filters or activity declarations -->
            </activity>
        </application>
    </manifest>
    Element Attribute Value Description
    <activity> android:name .MainActivity The Android activity that will handle the incoming URL.
    android:exported true Allows the activity to be launched by intents from other apps (like a web browser).
    <intent-filter> Defines the types of implicit intents the activity can respond to.
    <action> android:name android.intent.action.VIEW Standard action for viewing data.
    <category> android:name android.intent.category.DEFAULT Allows the activity to receive implicit intents.
    <category> android:name android.intent.category.BROWSABLE Makes the activity's intent filter accessible from a web browser.
    <data> android:scheme http / https The protocol of the URI (e.g., http://, https://).
    android:host www.example.com / example.com The domain or hostname of the URI.
    android:pathPrefix /products/ (Optional) Matches URLs starting with this path (e.g., https://www.example.com/products/123).
    android:autoVerify true Crucial: Signals the system to verify app ownership of the domain.

Step 2: Configure Your App to Use Data from the Intents

The reference highlights the next crucial step: "configure your app to use data from the intents to send users to the right content in your app". Once the Android system determines that your app is the best handler for a given URL and launches your activity, you need to extract the URL data from the incoming Intent and use it to navigate the user to the correct screen or display relevant content within your app.

  • Handling Incoming Intent Data:
    In the onCreate() or onNewIntent() method of the Activity declared in your AndroidManifest.xml (e.g., MainActivity), you can retrieve the Intent object and its data.

    // In your Activity (e.g., MainActivity.java)
    
    import android.content.Intent;
    import android.net.Uri;
    import android.os.Bundle;
    import androidx.appcompat.app.AppCompatActivity;
    
    public class MainActivity extends AppCompatActivity {
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main); // Your activity's layout
    
            handleIncomingLink(getIntent());
        }
    
        @Override
        protected void onNewIntent(Intent intent) {
            super.onNewIntent(intent);
            setIntent(intent); // Essential for subsequent calls to getIntent()
            handleIncomingLink(intent);
        }
    
        private void handleIncomingLink(Intent intent) {
            String action = intent.getAction();
            Uri data = intent.getData(); // This contains the full URL
    
            if (Intent.ACTION_VIEW.equals(action) && data != null) {
                // Example: Extract components of the URL
                String scheme = data.getScheme(); // e.g., "https"
                String host = data.getHost();     // e.g., "www.example.com"
                String path = data.getPath();     // e.g., "/products/123"
                String query = data.getQuery();   // e.g., "category=electronics&id=456"
    
                // Log or process the data to understand the incoming link
                android.util.Log.d("AppLink", "Scheme: " + scheme + ", Host: " + host + ", Path: " + path + ", Query: " + query);
    
                // Example: Navigate to a specific product detail screen
                if ("www.example.com".equals(host) && path != null && path.startsWith("/products/")) {
                    String productId = path.substring(path.lastIndexOf('/') + 1);
                    // Now you can use productId to fetch product details or navigate
                    // For instance, start a new activity with product information
                    // Intent productDetailIntent = new Intent(this, ProductDetailActivity.class);
                    // productDetailIntent.putExtra("productId", productId);
                    // startActivity(productDetailIntent);
                } else if ("example.com".equals(host)) {
                    // Handle links to the root domain
                    // Perhaps show a specific homepage fragment
                }
                // Add more 'else if' blocks for other specific paths or hosts declared in your manifest
            }
        }
    }

Step 3: Verify Android App Links with Your Website

For android:autoVerify="true" to function correctly and enable your app to open directly without a chooser dialog, Google requires verification that your app legitimately owns the domains specified in your AndroidManifest.xml. This verification happens via a Digital Asset Links JSON file hosted on your website.

  • Creating and Hosting assetlinks.json:

    1. Generate assetlinks.json: You need to create a Digital Asset Links JSON file (assetlinks.json). This file contains information about your Android app, including its package name and the SHA256 fingerprint of your app's signing key. You can find your app's SHA256 fingerprint using Gradle tasks or keytool.

    2. Host the file: Upload this assetlinks.json file to your website at the specific path: https://yourwebsite.com/.well-known/assetlinks.json. Replace yourwebsite.com with your actual domain.

    3. Content of assetlinks.json:

      [{
        "relation": ["delegate_permission/common.handle_all_urls"],
        "target": {
          "namespace": "android_app",
          "package_name": "com.yourcompany.yourapp", // Your app's package name
          "sha256_cert_fingerprints": ["AA:BB:CC:DD:EE:FF:11:22:33:44:55:66:77:88:99:00:AA:BB:CC:DD:EE:FF:11:22:33:44:55:66:77:88:99:00"] // Your app's signing key fingerprint
        }
      }]

      Note: The SHA256 fingerprint must match the key you use to sign your app (debug or release). For release builds, ensure you use the release key's fingerprint.

  • Verification Process: When your app is installed on an Android device (or updated), the Android system automatically attempts to fetch and verify the assetlinks.json file from your specified domains. If the verification is successful, your app becomes the default handler for those web links, opening them directly.

Testing Your Android App Links

After implementation, thoroughly test your Android App Links:

  • Using ADB: Use the Android Debug Bridge (ADB) to simulate clicking a web link:
    adb shell am start -W -a android.intent.action.VIEW -d "https://www.example.com/products/123" com.yourcompany.yourapp

    Replace the URL and package name with your own.

  • Browser Testing: Open a web browser on your Android device and navigate to one of your configured URLs. If implemented correctly, your app should launch directly.
  • Digital Asset Links API: Use Google's Digital Asset Links API to verify your assetlinks.json file is correctly formatted and accessible.

Benefits of Android App Links

  • Seamless User Experience: Links open directly in your app, eliminating the user choice dialog.
  • Enhanced Security: The verification process ensures that only your authenticated app can handle your domain's links, preventing malicious apps from hijacking them.
  • Improved User Engagement: A direct path from the web to your app content can increase retention and feature usage.
  • SEO Value: Google can crawl and index your app content, allowing users to find your app's content directly from Google Search results.
  • Reliable Fallback: If the app is not installed, the link will open in the user's default web browser, ensuring content is always accessible.

By following these steps, focusing on the AndroidManifest.xml configuration, proper intent data handling, and thorough domain verification, you can effectively make web links open your app on Android, providing a superior user experience.