Filters

Android Advanced Features

Do more with the Branch Android SDK by leveraging advanced features for specific use cases.

Set Initialization Metadata

Some third-party Data Integration Partners require setting certain identifiers before initializing the Branch Android SDK.

Do this using the setRequestMetadataKey() method.

Branch.getInstance().setRequestMetadata("\$analytics_visitor_id", "000001")
Branch.getInstance().setRequestMetadata("$analytics_visitor_id", "000001");

Delay Branch Initialization

There are certain cases when you may want to delay the initialization of a Branch session. An example would be making an async call to retrieve data that needs to be passed to Branch as request metadata.

Warning: When you try to do this, you may run into an error that reads SDK already initialized. This happens because Branch is self-initializing the session when the Activity enters a RESUMED state. To avoid this, manually disable auto session initialization and initialize the session yourself after the async call finishes.

Note: The expectDelayedSessionInitialization() method must be called before establishing the Branch singleton within your application class's onCreate().

package com.example.android

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

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

		// Delay session initialization 
		Branch.expectDelayedSessionInitialization()

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

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

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

		// Delay session initialization 
		Branch.expectDelayedSessionInitialization();

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

General Deep Linking

Branch Deep Links point to specific content that exists inside your app.

If a user clicks a Branch Deep Link and they have your app installed, the Deep Link will take them directly to your app and the specific content featured in your ad.

If the user does not have your app installed, they will be routed to the fallback URL you specified in your Branch Dashboard.

Deep Link Prerequisites

Before you can create a Branch Deep Link, you first need to:

  1. Create a BranchUniversalObject instance that will represent a unique piece of content:
    val buo: BranchUniversalObject =  BranchUniversalObject()
      .setCanonicalIdentifier("content/12345")
      .setTitle("My Content Title")
      .setContentDescription("My Content Description")
      .setContentImageUrl("https://lorempixel.com/400/400")
      .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
      .setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
      .setContentMetadata(ContentMetadata().addCustomMetadata("key1", "value1"))
    
    BranchUniversalObject buo = new BranchUniversalObject()
      .setCanonicalIdentifier("content/12345")
      .setTitle("My Content Title")
      .setContentDescription("My Content Description")
      .setContentImageUrl("https://lorempixel.com/400/400")
      .setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
      .setLocalIndexMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
      .setContentMetadata(new ContentMetadata().addCustomMetadata("key1", "value1"));
    
  2. Create a BranchLinkProperties instance that will contain info about the URL associated with the content:
    val lp: LinkProperties = LinkProperties()
      .setChannel("facebook")
      .setFeature("sharing")
      .setCampaign("content 123 launch")
      .setStage("new user")
      .addControlParameter("\$desktop_url", "https://example.com/home")
      .addControlParameter("custom", "data")
      .addControlParameter("custom_random", Calendar.getInstance().timeInMillis.toString())
    
    LinkProperties lp = new LinkProperties()
      .setChannel("facebook")
      .setFeature("sharing")
      .setCampaign("content 123 launch")
      .setStage("new user")
      .addControlParameter("$desktop_url", "https://example.com/home")
      .addControlParameter("custom", "data")
      .addControlParameter("custom_random", Long.toString(Calendar.getInstance().getTimeInMillis()));
    

Create Deep Links

Once you have a BranchUniversalObject and a BranchLinkProperties instance, you can use the getShortUrl() method to create a Branch Deep Link.

BranchUniversalObject buo = new BranchUniversalObject().setCanonicalIdentifier(“content/12345”)
LinkProperties lp = new LinkProperties().setCampaign("content 123 launch")

// Generate a short URL for the Branch Universal Object
String url = buo.getShortUrl(this.applicationContext, lp)
BranchUniversalObject buo = new BranchUniversalObject().setCanonicalIdentifier("content/12345");
LinkProperties lp = new LinkProperties().setCampaign("content 123 launch");

// Generate a short URL for the Branch Universal Object
String url = buo.getShortUrl(this.getApplicationContext, lp);

For more about the getShortUrl() method, visit the Android Full Reference guide.

Read Deep Links

You can read a Branch Deep Link to retrieve data from it. This must happen after Branch initialization.

The best practice is to get the data from the listener, since this will prevent a possible race condition.

// Listener within MainActivity's `onStart`
Branch.sessionBuilder(this).withCallback(object : BranchReferralInitListener {
	override fun onInitFinished(referringParams: JSONObject?, error: BranchError?) {
		if (error == null) {
			Log.i("BRANCH SDK", referringParams.toString())
		} else {
			Log.e("BRANCH SDK", error.message)
		}
	}
}).withData(this.intent.data).init()

// Latest params
val sessionParams = Branch.getInstance().latestReferringParams()
// Listener within Main Activity's `onStart`
Branch.sessionBuilder(this).withCallback(new Branch.BranchReferralInitListener() {
	@Override
	public void onInitFinished(JSONObject referringParams, BranchError error) {
		if (error == null) {
			Log.i("BRANCH SDK", referringParams.toString());
		} else {
			Log.i("BRANCH SDK", error.getMessage());
		}
	}
}).withData(this.getIntent().getData()).init();

// Latest params
JSONObject sessionParams = Branch.getInstance().getLatestReferringParams();

The getLatestReferringParams() method returns Deep Link properties.

Navigate to Content

Using data you've retrieved from a Branch Deep Link, you can navigate the user to specific content. Alternatively, you can log data, display data, or save data to be used later.

// Within Main Activity's `onStart`
Branch.sessionBuilder(this).withCallback { referringParams, error ->
	if (error == null) {
		// Option 1: log data
		Log.i("BRANCH SDK", referringParams.toString())

		// Option 2: save data to be used later
		val preferences = getSharedPreferences(
		"MyPreferences",
		MODE_PRIVATE)
		preferences.edit().putString("branchData", referringParams.toString()).apply()

		// Option 3: navigate to page
		val intent = Intent(this@MainActivity, OtherActivity::class.java)
		startActivity(intent)

		// Option 4: display data
		Toast.makeText(this@MainActivity, referringParams.toString(), Toast.LENGTH_LONG).show()
	} else {
		Log.i("BRANCH SDK", error.message)
	}
}.withData(this.intent.data).init()
// Within Main Activity's `onStart`
Branch.sessionBuilder(this).withCallback(new Branch.BranchReferralInitListener() {
	@Override
	public void onInitFinished(JSONObject referringParams, BranchError error) {
		if (error == null) {
			// Option 1: log data
			Log.i("BRANCH SDK", referringParams.toString());

			// Option 2: save data to be used later
			SharedPreferences preferences = MainActivity.this.getSharedPreferences("MyPreferences", Context.MODE_PRIVATE);
			preferences.edit().putString("branchData", referringParams.toString()).apply();

 			// Option 3: navigate to page
			Intent intent = new Intent(MainActivity.this, OtherActivity.class);
			startActivity(intent);

			// Option 4: display data
			Toast.makeText(MainActivity.this, referringParams.toString(), Toast.LENGTH_LONG).show();
		} else {
			Log.i("BRANCH SDK", error.getMessage());
		}
	}
}).withData(this.getIntent().getData()).init();

Event Tracking

General Event Tracking

By default, the Branch Android SDK tracks clicks, opens, installs, reinstalls and impressions automatically (out-of-the-box).

You can also use the BranchEvent class to track special user actions or application-specific events. For example, you can track when a user adds an item to a shopping cart or searches for a keyword.

In short, a BranchEvent instance corresponds to an in-app event that you want to log with Branch.

You can use a BranchUniversalObject (BUO) instance to populate the contentItems field of the BranchEvent class. This is how you associate BUO data with a specific event.

Learn more about tracking events and the logEvent() method in our respective guides.

Content Tracking

To track how many times a piece of content is viewed, use the addContentItems() and logEvent() methods together.

BranchEvent(BRANCH_STANDARD_EVENT.VIEW_ITEM).addContentItems(buo).logEvent(this.applicationContext)
new BranchEvent(BRANCH_STANDARD_EVENT.VIEW_ITEM).addContentItems(buo).logEvent(this.getApplicationContext);

Sharing

Android Native Sharesheet

Use the share() method to create a Branch Deep Link that has Android Native Sharesheet behavior associated with it.

@RequiresApi(Build.VERSION_CODES.LOLLIPOP_MR1)
    private fun shareBranchLink(@NonNull activity:Activity ) {

        // Create a Branch Universal Object
        val buo = BranchUniversalObject()
            .setCanonicalIdentifier("content/12345")

        // Create a Link Properties instance
        val lp = LinkProperties()
            .setChannel("facebook")
            .setFeature("sharing")
            .setCampaign("content 123 launch")
            .setStage("new user")

            // `$deeplink_path` routes users to a specific Activity
            .addControlParameter("\$deeplink_path", "color block page")

            // You can set the `blockColor` parameter to `Blue`, `Yellow`, `Red`, `Green` or `White` to modify the color block page.
            .addControlParameter("blockColor", "Green")

            .addControlParameter("\$desktop_url", "https://example.com/home")
            .addControlParameter("custom", "data")
            .addControlParameter("custom_random", Calendar.getInstance().timeInMillis.toString())

        Branch.getInstance().share(
            this@MainActivity,
            buo,
            lp,
            object : BranchNativeLinkShareListener {
                override fun onLinkShareResponse(sharedLink: String, error: BranchError) {}
                override fun onChannelSelected(channelName: String) { }
            },
            "Sharing Branch Short URL",
            "Using Native Chooser Dialog"
        )
    }
   private void  shareBranchLink(){
        // Create a Branch Universal Object
        BranchUniversalObject buo = new BranchUniversalObject()
                .setCanonicalIdentifier("content/12345");

        // Create a Link Properties instance
        LinkProperties lp = new LinkProperties()
                .setChannel("facebook")
                .setFeature("sharing")
                .setCampaign("content 123 launch")
                .setStage("new user")
                .addControlParameter("$desktop_url", "https://example.com/home")
                .addControlParameter("custom", "data")
                .addControlParameter("custom_random", Long.toString(Calendar.getInstance().getTimeInMillis()));
        
        // Show Sharesheet
       Branch.getInstance().share(MainActivity.this, branchUniversalObject, lp, new Branch.BranchNativeLinkShareListener() {
                    @Override
                    public void onLinkShareResponse(String sharedLink, BranchError error) {}
                    @Override
                    public void onChannelSelected(String channelName) { }
                },
                "Sharing Branch Short URL",
                "Using Native Chooser Dialog");
    }

Learn more about share() in our Android Full Reference guide.

Handle Links in Your Own App

Use the code below to deep link into your own app from within the app itself. This is done by launching a Chrome intent.

Note: Handling a new Branch Deep Link in your app will clear the current session data and a new referred OPEN will be attributed.

Note: Linking to the currently open activity or an activity that is in the backstack and partially visible must be handled via sessionBuilder()...reInit().

val intent = Intent(this, ActivityToLaunch::class.java)

// Replace with your own link URL
intent.putExtra("branch", "https://xxxx.app.link/testlink")

intent.putExtra("branch_force_new_session", true)
startActivity(intent)
Intent intent = new Intent(this, ActivityToLaunch.class);

// Replace with your own link URL
intent.putExtra("branch","https://xxxx.app.link/testlink");

intent.putExtra("branch_force_new_session",true);
startActivity(intent);

Push Notifications

Handle push notifications by adding a Branch Deep Link to your result intent.

val resultIntent = Intent(this, TargetClass::class.java)
resultIntent.putExtra("branch", "https://xxxx.app.link/testlink")
resultIntent.putExtra("branch_force_new_session", true)
val resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)
Intent resultIntent = new Intent(this, TargetActivity.class);
resultIntent.putExtra("branch","https://xxxx.app.link/testlink");
resultIntent.putExtra("branch_force_new_session",true);
PendingIntent resultPendingIntent =  PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

To handle situations where TargetActivity is in the foreground when a push notification is clicked, don't forget to call sessionBuilder()...reInit() from onNewIntent inside TargetActivity.

override fun onNewIntent(intent: Intent) {
	super.onNewIntent(intent)
	this.intent = intent
  
	// Branch reinit (in case Activity is already visible when Branch Link is clicked)
	// Will re-initialize only if `branch_force_new_session=true` intent extra is set
	Branch.sessionBuilder(this).withCallback(branchListener).reInit()
}
@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`)
	if (intent != null &&
		intent.hasExtra("branch_force_new_session") && 
		intent.getBooleanExtra("branch_force_new_session")) {
		Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
	}
}

QR Codes

To use a Branch QR Code, first create a BranchQRCode object. Fill out relevant properties for that object, then use getQRCodeAsImage() or getQRCodeAsData() to retrieve and use the Branch QR Code.

val qrCode = BranchQRCode()
	.setCodeColor("#a4c639")
	.setBackgroundColor(Color.WHITE)
	.setMargin(1)
	.setWidth(512)
	.setImageFormat(BranchQRCode.BranchImageFormat.JPEG)
	.setCenterLogo("https://cdn.branch.io/branch-assets/1598575682753-og_image.png")

val buo = BranchUniversalObject()
	.setCanonicalIdentifier("content/12345")
	.setTitle("My Content Title")
	.setContentDescription("My Content Description")
	.setContentImageUrl("https://lorempixel.com/400/400")

val lp = LinkProperties()
	.setChannel("facebook")
	.setFeature("sharing")
	.setCampaign("content 123 launch")
	.setStage("new user")

qrCode.getQRCodeAsImage(this@MainActivity, buo, lp, object : BranchQRCodeImageHandler<Any?> {
	override fun onSuccess(qrCodeImage: Bitmap) {
		// Do something with your QR code here
	}

	override fun onFailure(e: Exception) {
		Log.d("Failed to get QR code", e.toString())
	}
})
BranchQRCode qrCode = new BranchQRCode() //All QR code settings are optional
	.setCodeColor("#a4c639")
	.setBackgroundColor(Color.WHITE)
	.setMargin(1)
	.setWidth(512)
	.setImageFormat(BranchQRCode.BranchImageFormat.PNG)
	.setCenterLogo("https://cdn.branch.io/branch-assets/1598575682753-og_image.png");

BranchUniversalObject buo = new BranchUniversalObject()
	.setCanonicalIdentifier("content/12345")
	.setTitle("My QR Code");

LinkProperties lp = new LinkProperties()
	.setChannel("facebook")
	.setFeature("qrCode")
	.setCampaign("content 123 launch");

qrCode.getQRCodeAsImage(MainActivity.this, buo, lp, new BranchQRCode.BranchQRCodeImageHandler() {
	@Override
	public void onSuccess(Bitmap qrCodeImage) {
		// Do something with the QR code here
	}

	@Override
	public void onFailure(Exception e) {
		Log.d("Failed to get QR code", String.valueOf(e));
	}
});

Learn more about getting your Branch QR Code as an image or as data in our Android Full Reference guide.

User Data

Google DMA Compliance

In response to the European Union's enactment of the Digital Markets Act (DMA), the Branch Android SDK includes the setDMAParamsForEEA() method to help you pass consent information from your user to Google.

The setDMAParamsForEEA() method takes 3 parameters:

Parameter NameTypeDescriptionWhen trueWhen false
eeaRegionBooleanWhether European regulations, including the DMA, apply to this user and conversion.User is included in European Union regulations. For example, if the user is located within the EEA, they are within the scope of DMA.User is considered excluded from European Union regulations.
adPersonalizationConsentBooleanWhether end user has granted or denied ads personalization consent.User has granted consent for ads personalization.User has denied consent for ads personalization.
adUserDataUsageConsentBooleanWhether end user has granted or denied consent for 3P transmission of user level data for ads.User has granted consent for 3P transmission of user-level data for ads.User has denied consent for 3P transmission of user-level data for ads.

Default Behavior

When eeaRegion is set to true, the parameters adPersonalizationConsent and adUserDataUsageConsent must also be set.

When parameters are successfully set using setDMAParamsForEEA(), they will be sent along with every future request to the following Branch endpoints:

  • /v1/install
  • /v1/open
  • /v2/event

🚧

Warning: NULL by Default

Please note that the 3 parameters passed to setDMAParamsForEEA() are all NULL by default.

Failure to include user consent signals may result in attribution or campaign performance degradation. For additional information, please reach out to your Google AM.

Example Usage

// Example for an EEA resident who has denied both ad personalization and data usage consent
Branch.getInstance.setDMAParamsForEEA(true,false,false)
// Example for an EEA resident who has denied both ad personalization and data usage consent
Branch.getInstance.setDMAParamsForEEA(true,false,false);
// Example for an EEA resident who has consented to ad personalization but denied data usage consent
Branch.getInstance.setDMAParamsForEEA(true,true,false)
// Example for an EEA resident who has consented to ad personalization but denied data usage consent
Branch.getInstance.setDMAParamsForEEA(true,true,false);
// Example for an EEA resident who has denied ad personalization but granted data usage consent
Branch.getInstance.setDMAParamsForEEA(true,false,true)
// Example for an EEA resident who has denied ad personalization but granted data usage consent
Branch.getInstance.setDMAParamsForEEA(true,false,true);

Set User Identity

An "identity" is a unique alias attributed to a specific user in the Branch system.

Some scenarios which could leverage the setIdentity() function:

  1. You have your own user IDs that you want to see reflected in the Branch system.
  2. You want referral and event data to persist across platforms so you can see how your users access your service from different devices.
  3. You want referral and event data to persist across uninstall/reinstall events.

🚧

Sending PII

Be sure to not send any PII through the setIdentity() method. For additional details, please view our guide on Best Practices to Avoid Sending PII to Branch.

To confirm that user identities are being set as expected, use the Liveview section of the Branch Dashboard.

Branch branch = Branch.getAutoInstance(this.applicationContext)

branch.setIdentity("unique_user_id",
	BranchReferralInitListener { referringParams, error ->
		Log.i(
			"Test",
			"Install params = " + referringParams.toString()
	)
})

Branch.getInstance().logout()
Branch branch = Branch.getAutoInstance(this.getApplicationContext);

public void onClick(View v) {
	branch.setIdentity("unique_user_id", new BranchReferralInitListener() {
		@Override
		public void onInitFinished(JSONObject referringParams, BranchError error) {
			Log.i("Test", "install params = " + referringParams.toString());
		}
	});
}

Branch.getInstance().logout();

Learn more about the setIdentity method in our Android Full Reference guide.

Disable Tracking

You can also visit the Full Reference guide to learn how to disable tracking across your entire application with the disableTracking() method.