Android Basic Integration

👍

SDK Stats

Open Source Github Repo

SDK Size: 187kb

Speed: Median 80ms to 250ms

Minimum OS Version: API Level 21+

Android Version History

📘

Amazon Fire Device Support

The Branch Android SDK 4.1.1+ includes support for Amazon Fire devices.

Please follow the guide below except do not include the following two lines in the app level build.gradle file:

implementation 'com.google.firebase:firebase-appindexing:19.0.0'
implementation 'com.google.android.gms:play-services-ads-identifier:17.1.0+'

Configure Branch Dashboard

  • Configure your Default Link Settings.- Make sure I have an Android App and Enable App Links are both enabled

Notes:

  • When entering your SHA256 Cert Fingerprints, please ensure the characters are all UPPER CASE
  • If you want to enter multiple fingerprints, please separate them with commas.
15521552

Install Branch

  • Import the Branch SDK to your app level build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.2"
    defaultConfig {
        applicationId "com.eneff.branch.example.android"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    ...
    // required for all Android apps
    implementation 'io.branch.sdk.android:library:5.+'
    // required if your app is in the Google Play Store (tip: avoid using bundled play services libs)
    implementation 'com.google.android.gms:play-services-ads-identifier:17.1.0+'
    // alternatively, use the following lib for getting the AAID
    // implementation 'com.google.android.gms:play-services-ads:17.2.0'
    // optional
    // Chrome Tab matching (enables 100% guaranteed matching based on cookies)
    implementation 'androidx.browser:browser:1.0.0'
    // Replace above with the line below if you do not support androidx
    // implementation 'com.android.support:customtabs:28.0.0'
    ...
}

Dependencies

There are dependencies that you can add to your Android app that will allow for additional functionality to be used by the Branch SDK.

📘

Note

Some of these dependencies are already bundled into the Branch SDK.

Dependency

Description

Signature

Library Repository

Android Advertising ID (AAID)

In order for Branch to properly access the GAID value of a device, apps targeting Android 13+ will need to use the latest version
of the play-services-ads-identifier dependency or explicitly declare <uses-permission android:name="com.google.android.gms.permission.AD_ID" /> within the app's manifest file.

implementation "com.google.android.gms:play-services-ads-identifier:18.0.1"

maven { url 'https://maven.google.com/' }

Play Install Referrer Library

As of version 4.3.0, Google's Play Install Referrer Library is bundled into Branch Android SDK.

If you are using a version below 4.3.0, you must update your app's dependencies to include the Play Install Referrer Library.

implementation "com.android.installreferrer:installreferrer:2.2"

maven { url 'https://maven.google.com/' }

Huawei Mobile Services & Ads Kit

The Branch SDK supports Huawei devices without Google Mobile Services. This dependency will add Install Referrer support on the Huawei AppGallery store and attribution using OAID.

Ensure proguard rules are set.

implementation "com.huawei.hms:ads-identifier:3.4.39.302"

maven { url 'http://developer.huawei.com/repo/' }

Xiaomi GetApps Store Referrer

This dependency will add Install Referrer support on the Xiaomi GetApps store.

Please reach out to your Xiaomi representative for additional details.

implementation "com.miui.referrer:homereferrer:1.0.0.6"

maven { url 'https://repos.xiaomi.com/maven/‘ }

Samsung Galaxy Store Referrer

This dependency will add Install Referrer support on the Samsung Galaxy store

Please reach out to your Samsung representative for additional details.

implementation files('/../galaxyapps_sdk_referrer-release-v1.0.aar')

Please reach out to your Samsung representative for the maven repo to add to your project level build.gradle

Configure app

  • Add Branch to your AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.eneff.branch.example.android">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.google.android.gms.permission.AD_ID"/>

    <application
        android:allowBackup="true"
        android:name="com.eneff.branch.example.android.CustomApplicationClass"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">

        <!-- Launcher Activity to handle incoming Branch intents -->
        <activity
            android:name=".LauncherActivity"
            android:launchMode="singleTask"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar"
            android:exported="true">

           <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>

            <!-- Branch URI Scheme -->
            <intent-filter>
                <!-- If utilizing $deeplink_path please explicitly declare your hosts, or utilize a wildcard(*) -->
                <data android:scheme="yourapp" android:host="open" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>

            <!-- Branch App Links - Live App -->
            <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:scheme="https" android:host="example.app.link" />
                <!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website.  -->
                <data android:scheme="https" android:host="example-alternate.app.link" />
            </intent-filter>
           <!-- Branch App Links - Test App -->
           <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:scheme="https" android:host="example.test-app.link" />
                <!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website.  -->
                <data android:scheme="https" android:host="example-alternate.test-app.link" />
            </intent-filter>
         </activity>

        <!-- Branch init -->
        <meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Sw" />
        <meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_hlxrWC5Zx16DkYmWu4AHiimdqugRYMr" />
        <meta-data android:name="io.branch.sdk.TestMode" android:value="false" />     <!-- Set to true to use Branch_Test_Key (useful when simulating installs and/or switching between debug and production flavors) -->

    </application>

    <queries>
        <intent>
            <action android:name="android.intent.action.SEND" />
            <data android:mimeType="text/plain" />
        </intent>
    </queries>

</manifest>
  • Replace the following with values from your Branch Dashboard App settings and Link settings
    • yourapp
    • example.app.link
    • example-alternate.app.link
    • key_live_kaFuWw8WvY7yn1d9yYiP8gokwqjV0Sw
    • key_test_hlxrWC5Zx16DkYmWu4AHiimdqugRYMr

🚧

Single Task Launch Mode & Activities

The Single Task mode instantiates the Main/Splash Activity only if it does not exist in the Activity Stack.

If the Activity exists in the background, every subsequent intent to the Activity just brings it to the foreground. You can read more about Single Task mode here.

If your app has multiple activities triggered by multiple intent filters with the same scheme, your app may run into a race condition when clicking on links that open the app (ex. Branch Links and custom deep links). To prevent this, make sure to implement the Branch SDK in the launcher activity.

Load Branch

  • Add Branch to your CustomApplicationClass.java
package com.eneff.branch.example.android

import android.app.Application
import io.branch.referral.Branch

class CustomApplicationClass : Application() {
    override fun onCreate() {
        super.onCreate()

        // Branch logging for debugging
        Branch.enableTestMode()

       // Branch object initialization
        Branch.getAutoInstance(this)
    }
}
package com.eneff.branch.example.android;

import android.app.Application;
import io.branch.referral.Branch;

public class CustomApplicationClass extends Application {
    @Override
    public void onCreate() {
        super.onCreate();

        // Branch logging for debugging
        Branch.enableLogging();

        // Branch object initialization
        Branch.getAutoInstance(this);
    }
}

Initialize Branch

  • Add Branch to your LauncherActivity.java
package com.eneff.branch.example.android

import io.branch.indexing.BranchUniversalObject
import io.branch.referral.Branch
import io.branch.referral.BranchError
import io.branch.referral.util.LinkProperties

import android.util.Log;
import org.json.JSONObject;

    override fun onStart() {
        super.onStart()
        Branch.sessionBuilder(this).withCallback { branchUniversalObject, linkProperties, error ->
            if (error != null) {
                Log.e("BranchSDK_Tester", "branch init failed. Caused by -" + error.message)
            } else {
                Log.e("BranchSDK_Tester", "branch init complete!")
                if (branchUniversalObject != null) {
                    Log.e("BranchSDK_Tester", "title " + branchUniversalObject.title)
                    Log.e("BranchSDK_Tester", "CanonicalIdentifier " + branchUniversalObject.canonicalIdentifier)
                    Log.e("BranchSDK_Tester", "metadata " + branchUniversalObject.contentMetadata.convertToJson())
                }
                if (linkProperties != null) {
                    Log.e("BranchSDK_Tester", "Channel " + linkProperties.channel)
                    Log.e("BranchSDK_Tester", "control params " + linkProperties.controlParams)
                }
            }
        }.withData(this.intent.data).init()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        sessionBuilder(this).withCallback { referringParams, error ->
            if (error != null) {
                Log.e("BranchSDK_Tester", error.message)
            } else if (referringParams != null) {
                Log.e("BranchSDK_Tester", referringParams.toString())
            }
        }.reInit()
    }
}
package com.eneff.branch.example.android;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;

import org.json.JSONObject;

import io.branch.indexing.BranchUniversalObject;
import io.branch.referral.Branch;
import io.branch.referral.BranchError;
import io.branch.referral.util.LinkProperties;

public class LauncherActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_launcher);
    }

    @Override
    protected void onStart() {
        super.onStart();
        Branch.sessionBuilder(this).withCallback(new Branch.BranchUniversalReferralInitListener() {
            @Override
            public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
                if (error != null) {
                    Log.e("BranchSDK_Tester", "branch init failed. Caused by -" + error.getMessage());
                } else {
                    Log.e("BranchSDK_Tester", "branch init complete!");
                    if (branchUniversalObject != null) {
                        Log.e("BranchSDK_Tester", "title " + branchUniversalObject.getTitle());
                        Log.e("BranchSDK_Tester", "CanonicalIdentifier " + branchUniversalObject.getCanonicalIdentifier());
                        Log.e("BranchSDK_Tester", "metadata " + branchUniversalObject.getContentMetadata().convertToJson());
                    }

                    if (linkProperties != null) {
                        Log.e("BranchSDK_Tester", "Channel " + linkProperties.getChannel());
                        Log.e("BranchSDK_Tester", "control params " + linkProperties.getControlParams());
                    }
                }
            }
        }).withData(this.getIntent().getData()).init();

    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        this.setIntent(intent);
        Branch.sessionBuilder(this).withCallback(new BranchReferralInitListener() {
            @Override
            public void onInitFinished(JSONObject referringParams, BranchError error) {
                if (error != null) {
                    Log.e("BranchSDK_Tester", error.getMessage());
                } else if (referringParams != null) {
                    Log.e("BranchSDK_Tester", referringParams.toString());
                }
            }
        }).reInit();
    }
}

🚧

LauncherActivity vs other Activities

Branch recommends initializing session inside the LauncherActivity (i.e. Activity that contains intent filter of category, “android.intent.category.LAUNCHER” in AndroidManifext.xml). However, if your app requires it, session initialization can happen in a different Activity too, as long as that Activity is the one configured to open Branch links using the intent filters in AndroidManifest.xml (see above). Note that, in this case, if the app is opened organically, Branch will auto-initialize behind the scenes and calling sessionBuilder()…init() will return an error. This is because the SDK will already be initialized. The main exceptions are push notifications and intra-app linking.

🚧

Always initialize Branch in onStart()

Initializing Branch in other Android lifecycle methods, like onCreate()/onResume(), will lead to unintended behavior. onStart() is what makes the activity visible to the user, as the app prepares for the activity to enter the foreground and become interactive.

To Learn more:

If your app requires a different session initialization setup please see Delay Session Initialization.

Proguard Settings

To collect the Google Advertising ID, you must ensure that proguard doesn't remove the necessary Google Ads class. The surest way to do this is add it to your proguard rules. If your Application is enabled with proguard, add the following instruction to your proguard.cfg or proguard-rules.pro file:

-keep class com.google.android.gms.** { *; }

In case you are using Facebook SDK to support deep linking through Facebook ads, please make sure to keep the Facebook SDK classes in proguard

-keep class com.facebook.applinks.** { *; }
-keepclassmembers class com.facebook.applinks.** { *; }
-keep class com.facebook.FacebookSdk { *; }

If you are adding support for Huawei devices without Google Mobile Services, please make sure to add this to your proguard rules.

-keep class com.huawei.hms.ads.** { *; }
-keep interface com.huawei.hms.ads.** { *; }

Recommended Next Steps