Android Basic Integration

SDK Stats

Maven Central Javadocs

Open Source Github Repo

SDK Size: 187kb

Speed: Median 80ms to 250ms

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.android.gms:play-services-appindexing:9.+' // App indexing

implementation 'com.google.android.gms:play-services-ads:9+' // GAID matching

Configure Branch Dashboard

  • Configure your Default Link Settings.

  • Make sure I have an Android App and Enable App Links are both enabled

image

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 {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    implementation 'com.android.support:appcompat-v7:25.2.0'
    implementation 'com.android.support:design:25.2.0'

    // 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.firebase:firebase-appindexing:19.0.0'
    implementation 'com.google.android.gms:play-services-ads-identifier:16+'

    // optional
    implementation 'com.android.support:customtabs:28.0.0' // Chrome Tab matching (enables 100% guaranteed matching based on cookies)



    testImplementation 'junit:junit:4.12'
}

Supports for AndroidX

Any library imports with the namespace com.android.support can be safely replaced with AndroidX equivalents.

Google Play Services version 17+

If you reference Google Play Services version 17 or higher, you MUST complete Google's update instructions here.

Due to a major Google Play Services change made in June 2019, not completing the update steps will cause Branch's Android SDK (and various other cross-platform SDKs, e.g. Unity) to stop collecting Android AID which we use to ensure accurate deep linking and attribution.

If you are running Google Play Services versions below 17, no update is necessary.

Using Branch Android SDK versions below 4.3.0

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.

Huawei Mobile Services

Branch SDK supports Huawei devices without Google Mobile Services. Please follow the guide above except remove the following three 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:16+

implementation 'com.google.firebase:firebase-appindexing:19.0.0

and replace them with:

implementation 'com.huawei.hms:ads-identifier:3.4.28.305

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" />

    <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">

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

            <!-- Branch URI Scheme -->
            <intent-filter>
                <data android:scheme="yourapp" />
                <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 (optional) -->
            <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>
        </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>

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

Single Task launch mode required

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.

Load Branch

  • Add Branch to your CustomApplicationClass.java
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);
    }
}
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.enableDebugMode()

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

Initialize Branch

sessionBuilder available for v4.4.0+

  • Add Branch to your LauncherActivity.java
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 public void onStart() {
        super.onStart();
        Branch.sessionBuilder(this).withCallback(branchReferralInitListener).withData(getIntent() != null ? getIntent().getData() : null).init();
    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        // if activity is in foreground (or in backstack but partially visible) launching the same
        // activity will skip onStart, handle this case with reInitSession
        Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
    }
    private Branch.BranchReferralInitListener callback = new Branch.BranchReferralInitListener() {
        @Override
        public void onInitFinished(JSONObject linkProperties, BranchError error) {
            // do stuff with deep link data (nav to page, display content, etc)
        }
    };
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

    override fun onStart() {
        super.onStart()
        // Branch init
        Branch.sessionBuilder(this).withCallback(branchListener).withData(this.intent?.data).init()
    }

    override fun onNewIntent(intent: Intent) {
        super.onNewIntent(intent)
        this.intent = intent
        // Branch reinit (in case Activity is already in foreground when Branch link is clicked)
        Branch.sessionBuilder(this).withCallback(branchListener).reInit()
    }

    object branchListener : Branch.BranchReferralInitListener {
            override fun onInitFinished(referringParams: JSONObject?, error: BranchError?) {
                if (error == null) {
                    Log.i("BRANCH SDK", referringParams.toString())
                    // Retrieve deeplink keys from 'referringParams' and evaluate the values to determine where to route the user
                    // Check '+clicked_branch_link' before deciding whether to use your Branch routing logic
                } else {
                    Log.e("BRANCH SDK", error.message)
                }
            }
        }

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.

Learn more here.

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

Updated 11 days ago

Android Basic Integration


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.