### Add Branch Keys and Register for Install Referrer
Source: https://help.branch.io/developer-hub/docs/android-instant-apps
Configure Branch keys and register for install referrer in the application's manifest. This setup is crucial for tracking installs and referrals.
```xml
```
```xml
```
--------------------------------
### Add Install Metadata (Java)
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Tags an install with custom attributes before the `onStart()` method of the first activity. Call this after Branch object initialization.
```java
// Call this method before the `onStart()` method of the first activity
protected static final String branchKey = "branch_key_here";
public class CustomApplicationClass extends Application {
@Override
public void onCreate() {
super.onCreate();
// Branch object initialization
Branch.getAutoInstance(this.getApplicationContext, branchKey);
// Suggestion: call `addInstallMetadata()` right after object initialization
Branch.getInstance().addInstallMetadata("install_attribute_name", "install_attribute_value");
}
}
```
--------------------------------
### Get Branch Instance Example
Source: https://help.branch.io/developer-hub/docs/android-sdk
Demonstrates how to get an instance of the Branch SDK in both Java and Kotlin. This is a prerequisite for most SDK operations.
```java
Branch.getAutoInstance(this);
```
```kotlin
Branch.getAutoInstance(this)
```
--------------------------------
### Add Install Metadata (Kotlin)
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Tags an install with custom attributes before the `onStart()` method of the first activity. Call this after Branch object initialization.
```kotlin
// Call this method before the `onStart()` method of the first activity
class CustomApplicationClass : Application() {
override fun onCreate() {
super.onCreate()
// Branch object initialization
Branch.getAutoInstance(this.applicationContext)
// Suggestion: call `addInstallMetadata()` right after object initialization
Branch.getInstance().addInstallMetadata("install_attribute_name", "install_attribute_value")
}
}
```
--------------------------------
### Show Install Prompt for Full App
Source: https://help.branch.io/developer-hub/docs/android-instant-apps
Use this code to display an install prompt for the full native app when the current app is an Instant App. It allows passing Branch referring deep data through the install process. Ensure Branch SDK is initialized.
```java
if (Branch.isInstantApp(this)) {
myFullAppInstallButton.setVisibility(View.VISIBLE);
myFullAppInstallButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
.setCanonicalIdentifier("item/12345")
.setTitle("My Content Title")
.setContentDescription("My Content Description")
.setContentImageUrl("https://example.com/mycontent-12345.png")
.addContentMetadata("property1", "blue")
.addContentMetadata("property2", "red");
Branch.showInstallPrompt(myActivity, activity_ret_code, branchUniversalObject);
}
});
} else {
myFullAppInstallButton.setVisibility(View.GONE);
}
```
--------------------------------
### Example Usage - Java
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Example of how to use `sessionBuilder()` in Java to initialize a Branch session and handle the callback.
```APIDOC
## Example Usage (Java)
### Description
Demonstrates initializing a Branch session in Java within the `onStart()` method of an Activity and handling the referral parameters or errors.
### Code
```java
// In LauncherActivity.java
package com.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.i("BranchSDK_Tester", "branch init complete!");
if (branchUniversalObject != null) {
Log.i("BranchSDK_Tester", "title " + branchUniversalObject.getTitle());
Log.i("BranchSDK_Tester", "CanonicalIdentifier " + branchUniversalObject.getCanonicalIdentifier());
Log.i("BranchSDK_Tester", "metadata " + branchUniversalObject.getContentMetadata().convertToJson());
}
if (linkProperties != null) {
Log.i("BranchSDK_Tester", "Channel " + linkProperties.getChannel());
Log.i("BranchSDK_Tester", "control params " + linkProperties.getControlParams());
}
}
}
}).withData(this.getIntent().getData()).init();
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent);
if (intent != null && intent.hasExtra("branch_force_new_session") && intent.getBooleanExtra("branch_force_new_session",false)) {
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.i("BranchSDK_Tester", referringParams.toString());
}
}
}).reInit();
}
}
}
```
```
--------------------------------
### Install Branch Connected SDK via NPM
Source: https://help.branch.io/developer-hub/docs/connected-basic-integration
Use this command to install the Branch Connected SDK using npm. This is the recommended installation method.
```shell
npm install branch-connected-sdk
```
--------------------------------
### Example Usage - Kotlin
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Example of how to use `sessionBuilder()` in Kotlin to initialize a Branch session and handle the callback.
```APIDOC
## Example Usage (Kotlin)
### Description
Demonstrates initializing a Branch session in Kotlin within the `onStart()` method of an Activity and handling the referral parameters or errors.
### Code
```kotlin
package com.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 {
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()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
this.setIntent(intent)
if (intent != null && intent.hasExtra("branch_force_new_session") && intent.getBooleanExtra("branch_force_new_session",false)) {
Branch.sessionBuilder(this).withCallback {
referringParams, error ->
if (error != null) {
Log.e("BranchSDK_Tester", error.message)
} else if (referringParams != null) {
Log.i("BranchSDK_Tester", referringParams.toString())
}
}.reInit()
}
}
```
```
--------------------------------
### addInstallMetadata
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Tags an install with custom attributes by adding key-value pairs that qualify or distinguish an install.
```APIDOC
## addInstallMetadata
### Description
Tags an install with a custom attribute. Add any key-value pairs that qualify or distinguish an install here.
### Method Signature
`public Branch addInstallMetadata(@NonNull String key, @NonNull String value)`
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Arguments
- **key** (String) - Required - The key in the key-value pair.
- **value** (String) - Required - The value in the key-value pair.
### Request Example
```java
// Call this method before the `onStart()` method of the first activity
// Suggestion: call `addInstallMetadata()` right after object initialization
Branch.getInstance().addInstallMetadata("install_attribute_name", "install_attribute_value");
```
```kotlin
// Call this method before the `onStart()` method of the first activity
// Suggestion: call `addInstallMetadata()` right after object initialization
Branch.getInstance().addInstallMetadata("install_attribute_name", "install_attribute_value")
```
### Response
Returns the Branch instance for chaining.
```
--------------------------------
### Install Homebrew, Node.js, and Update
Source: https://help.branch.io/developer-hub/docs/cordova-phonegap-ionic
Installs Homebrew package manager, Node.js, and updates Homebrew. This is a prerequisite for many development tools.
```shell
# add to ~/.bash_profile
export ANDROID_HOME=$HOME/Library/Android/sdk
export PATH=$ANDROID_HOME/tools:$PATH
export PATH=$ANDROID_HOME/platform-tools:$PATH
source ~/.bash_profile;
android update sdk;
```
--------------------------------
### Install Branch SDK with Carthage
Source: https://help.branch.io/developer-hub/docs/tvos-basic-integration
Integrate the Branch SDK using Carthage. Note that Carthage 0.36.x requires installing from source for xcframework support with the `--use-xcframeworks` option.
```bash
github "BranchMetrics/ios-branch-deep-linking"
```
--------------------------------
### Initialize Branch SDK with Callback
Source: https://help.branch.io/developer-hub/docs/connected-full-reference
Demonstrates the usage of the branch.init() function with all its parameters: branch_key, options, and a callback function to handle session data.
```javascript
branch.init(
branch_key,
options,
callback (err, data),
);
```
--------------------------------
### Initialize Branch SDK on App Start
Source: https://help.branch.io/developer-hub/docs/android-basic-integration
Initialize the Branch SDK when your application starts. This setup is crucial for deep linking and referral tracking. Ensure you handle potential errors during initialization.
```java
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.i("BranchSDK_Tester", "branch init complete!");
if (branchUniversalObject != null) {
Log.i("BranchSDK_Tester", "title " + branchUniversalObject.getTitle());
Log.i("BranchSDK_Tester", "CanonicalIdentifier " + branchUniversalObject.getCanonicalIdentifier());
Log.i("BranchSDK_Tester", "metadata " + branchUniversalObject.getContentMetadata().convertToJson());
}
if (linkProperties != null) {
Log.i("BranchSDK_Tester", "Channel " + linkProperties.getChannel());
Log.i("BranchSDK_Tester", "control params " + linkProperties.getControlParams());
}
}
}
}).withData(this.getIntent().getData()).init();
}
}
```
--------------------------------
### Initialize Branch SDK with Basic Options
Source: https://help.branch.io/developer-hub/docs/web-basic-integration
Initialize the Branch SDK using your live Branch Key. This basic example logs any errors or data returned during initialization.
```javascript
// Replace key_live_YOUR_KEY_GOES_HERE with your Branch Key (live version)
branch.init('key_live_YOUR_KEY_GOES_HERE', function(err, data) {
console.log(err, data);
});
```
--------------------------------
### setReferrerGbraidValidityWindow
Source: https://help.branch.io/developer-hub/docs/ios-full-reference
Sets the time window for which `referrer_gbraid` is valid, starting from now. After the validity window is over, it gets cleared from settings and will not be sent with requests anymore.
```APIDOC
## setReferrerGbraidValidityWindow
### Description
Sets the time window for which `referrer_gbraid` is valid, starting from now. After the validity window is over, it gets cleared from settings and will not be sent with requests anymore.
### Method
(void) setReferrerGbraidValidityWindow:(NSTimeInterval) validityWindow;
### Parameters
#### Argument
- **validityWindow** (`NSTimeInterval`) - The number of seconds `referrer_gbraid` will be valid starting from now.
Default `validityWindow` is 30 days (2,592,000 seconds).
### Request Example
```swift
Branch.setReferrerGbraidValidityWindow(10.0)
```
```objectivec
[Branch setReferrerGbraidValidityWindow:10.0]
```
```
--------------------------------
### Initialize Branch SDK (Web)
Source: https://help.branch.io/developer-hub/docs/flutter-sdk-basic-integration
Include this script in your web/index.html file to initialize the Branch SDK for web. Replace 'key_live_YOUR_KEY_GOES_HERE' with your actual Branch live key.
```html
```
--------------------------------
### Get First Referring Parameters
Source: https://help.branch.io/developer-hub/docs/android-full-reference
Retrieves the parameters associated with the link that initially referred the user. This is set only once on a fresh install and can be affected by `setIdentity()` and `logout()`.
```kotlin
fun getFirstReferringBUO(): String {
val branch = Branch.getInstance()
val firstParams = branch?.getFirstReferringParams()
val buo = if (firstParams?.has("+clicked_branch_link") == true && firstParams.getBoolean("+clicked_branch_link")) {
BranchUniversalObject.createInstance(firstParams)
} else {
// Handle error
}
return buo.toString()
}
```
```java
public static String getFirstReferringBranchUniversalObject() {
BranchUniversalObject branchUniversalObject = null;
Branch branchInstance = Branch.getInstance();
if (branchInstance != null && branchInstance.getFirstReferringParams() != null) {
JSONObject firstParam = branchInstance.getFirstReferringParams();
try {
if (firstParam.has("+clicked_branch_link") && firstParam.getBoolean("+clicked_branch_link")) {
branchUniversalObject = BranchUniversalObject.createInstance(firstParam);
}
} catch (Exception ignore) {
}
}
return _jsonObjectFromBranchUniversalObject(branchUniversalObject).toString();
}
```
--------------------------------
### Initialize Branch SDK and Open Session
Source: https://help.branch.io/developer-hub/docs/windows-cpp-basic-integration
Initialize the Branch SDK by creating a `Branch` instance and calling `openSession`. This is typically done early in the application lifecycle, such as in `wWinMain`, to handle incoming URIs and deferred deep links.
```cpp
#include
using namespace BranchIO;
using namespace std;
struct MyCallback : public virtual IRequestCallback;
int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
_In_opt_ HINSTANCE hPrevInstance,
_In_ LPWSTR lpCmdLine,
_In_ int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
// ----- Initialize the Branch SDK
AppInfo appInfo;
appInfo.setAppVersion("1.0");
auto* branch = Branch::create(branchKey, &appInfo);
wstring cmdLineArg(lpCmdLine ? lpCmdLine : L"");
wstring uriScheme(L"myurischeme");
if (cmdLineArg[0] == '"') {
// Strip off any leading and trailing quotes
cmdLineArg = cmdLineArg.substr(1, cmdLineArg.length() - 2);
}
wstring::size_type prefixLength = min(uriScheme.length(), cmdLineArg.length());
wstring prefix = cmdLineArg.substr(0, prefixLength);
if (prefix == uriScheme)
{
// Open any URI passed at the command line
uriToOpen = cmdLineArg;
}
auto* myCallback = new MyCallback;
branch->openSession(uriToOpen, myCallback);
// ----- Continue with normal Win32 startup
MyRegisterClass(hInstance);
```
--------------------------------
### Get Initial Session Data
Source: https://help.branch.io/developer-hub/docs/web-full-reference
Retrieves the same session information and referring data as Branch.init when the app was first installed. The callback returns immediately if Branch has already been initialized.
```javascript
branch.first(function(err, data) {
response.html(err || JSON.stringify(data));
});
```
--------------------------------
### Get First Referring Parameters
Source: https://help.branch.io/developer-hub/docs/cordova-phonegap-ionic
Retrieve the first referring parameters for the user's session. This data is typically set only once when the user first installs and opens the app.
```javascript
Branch.getFirstReferringParams().then(function(res) {
alert('Response: ' + JSON.stringify(res))
}).catch(function(err) {
alert('Error: ' + JSON.stringify(err))
})
```
--------------------------------
### Initialize Branch SDK via HTML Script Tag
Source: https://help.branch.io/developer-hub/docs/connected-full-reference
Include this script in your HTML's section to load and initialize the Branch SDK. Replace 'key_live_YOUR_KEY_GOES_HERE' with your actual Branch Key.
```html
```
--------------------------------
### Get First Referring Parameters
Source: https://help.branch.io/developer-hub/docs/react-native-full-reference
Retrieve the initial referring link parameters using `getFirstReferringParams`. This method returns a promise that resolves with the parameters from the very first time the user was referred by a Branch link, typically during the app's initial install.
```javascript
import branch from 'react-native-branch'
// Listener
branch.subscribe({
onOpenStart: ({
uri,
cachedInitialEvent
}) => {
console.log(
'subscribe onOpenStart, will open '
+ uri
+ ' cachedInitialEvent is '
+ cachedInitialEvent,
);
},
onOpenComplete: ({
error,
params,
uri
}) => {
if (error) {
console.error(
'subscribe onOpenComplete, Error from opening uri: '
+ uri
+ ' error: '
+ error,
);
return;
}
else if (params) {
if (!params['+clicked_branch_link']) {
if (params['+non_branch_link']) {
console.log('non_branch_link: ' + uri);
// Route based on non-Branch links
return;
}
} else {
// Handle params
let deepLinkPath = params.$deeplink_path as string;
let canonicalUrl = params.$canonical_url as string;
// Route based on Branch link data
return
}
}
},
});
let installParams = await branch.getFirstReferringParams() // Params from original install
```
--------------------------------
### init(branch_key, options, callback) - API Reference
Source: https://help.branch.io/developer-hub/docs/connected-full-reference
Detailed reference for the `init` function, outlining its parameters, options, and usage for initializing the Branch SDK.
```APIDOC
## init(branch_key, options, callback)
### Description
The `init` function initiates the Branch session. It creates a new user session in `sessionStorage` if one doesn't exist. If the session was opened from a referring link, the `data()` object will also return the `referring_link`.
### Method
`branch.init(branch_key, options, callback)`
### Endpoint
Not Applicable (SDK Method)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
#### Initialization Parameters
- **branch_key** (`string`) - Required - Your Branch live key, or (deprecated) your app id.
- **options** (`Object`) - Optional - Configuration options. See table below.
- **callback** (`function`) - Optional - A callback function to execute after initialization. It receives `err` (error object) and `data` (session data) as arguments.
### Options Table
| Key | Value | Type | Required |
|---|---|---|---|
| `advertising_ids` | The current device's advertising ID declared by the brand's corresponding key. Please refer to Connected Basic Integration for the key index. | `{string:string}` | **Y** for Ad Network Attribution, **N** for Web Based Attribution |
| `branch_match_id` | The current user's browser-fingerprint-id. The value of this parameter should be the same as the value of `?_branch_match_id` (automatically appended by Branch after a link click). Only necessary if `?_branch_match_id` is lost due to multiple redirects in your flow. | `string` | N |
| `retries` | Default: 2 | `number` | N |
| `retry_delay` | Expressed in milliseconds. Default: 200ms | `number` | N |
| `timeout` | Expressed in milliseconds. Default: 5000ms | `number` | N |
| `tracking_disabled` | Default: false | `boolean` | N |
| `enableLogging` | Default: false | `boolean` | N |
### Request Example
```javascript
branch.init(
'key_live_YOUR_KEY_GOES_HERE',
{
advertising_ids: {
SAMSUNG_IFA: 'xxxxx',
},
retries: 3,
timeout: 10000
},
(err, data) => {
if (err) {
console.error('Branch init error:', err);
} else {
console.log('Branch init data:', data);
// Access referring link if available
if (data.referring_link) {
console.log('Referred by link:', data.referring_link);
}
}
}
);
```
### Response
#### Success Response (Callback Data)
- **data** (`Object`) - An object containing session data. If the session was opened from a referring link, this object will include a `referring_link` property.
#### Error Handling
- If an error occurs during initialization, the `callback` function will be invoked with an error object as the first argument (`err`).
- The `init` function returns a data object where you can read the link the user was referred by.
```
--------------------------------
### Install Node.js using Homebrew
Source: https://help.branch.io/developer-hub/docs/cordova-phonegap-ionic
Installs Node.js using the Homebrew package manager. Ensure you have Homebrew installed first.
```shell
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)";
brew update;
brew install node;
```
--------------------------------
### Initialize Branch SDK in HTML
Source: https://help.branch.io/developer-hub/docs/connected-basic-integration
This snippet shows how to load and initialize the Branch.io SDK within an HTML file. Ensure you replace 'key_live_YOUR_KEY_GOES_HERE' with your actual Branch live key.
```html
```
--------------------------------
### Add Huawei Install Referrer Dependency
Source: https://help.branch.io/developer-hub/docs/android-basic-integration
Include the Huawei Install Referrer library to track app installs originating from Huawei's ecosystem.
```Groovy
implementation "com.huawei.hms:ads-installreferrer:3.4.39.302"
```
--------------------------------
### Initialize Branch SDK with Options
Source: https://help.branch.io/developer-hub/docs/connected-advanced-features
Initialize the Branch SDK with a live key and custom advertising ID options. This is typically done once when your application loads.
```javascript
const options = {
advertising_ids: {
SAMSUNG_IFA: 'xxxxx',
}
};
branch.init('key_live_YOUR_KEY_GOES_HERE', options, function(err, data) {
console.log(err, data);
});
```
--------------------------------
### Test Install Conversion Value
Source: https://help.branch.io/developer-hub/docs/advanced-skadnetwork-sdk-configuration
Verify install conversion values by looking for the 'invoke_register_app' key in the proxy tool's logs. This JSON structure represents the data captured for an install event.
```JSON
{
"session_id" : "850166709486919576",
"data" : "{\"+clicked_branch_link\":false,\"+\":is_first_session\":false}",
"device_fingerprint_id" : "847563926187298061",
"identity_id" : "850166709481620778",
"invoke_register_app" : true,
"link" : "https:\/\/3mnv.app.link?%24identity_id=850166709481620778"
}
```
--------------------------------
### Initialize Branch Session with Callback (Java)
Source: https://help.branch.io/developer-hub/docs/android-full-reference
This Java example demonstrates initializing a Branch session using `sessionBuilder()` and handling the initialization results via a callback. Ensure `init()` is called to activate the session.
```java
// In LauncherActivity.java
package com.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.i("BranchSDK_Tester", "branch init complete!");
if (branchUniversalObject != null) {
Log.i("BranchSDK_Tester", "title " + branchUniversalObject.getTitle());
Log.i("BranchSDK_Tester", "CanonicalIdentifier " + branchUniversalObject.getCanonicalIdentifier());
Log.i("BranchSDK_Tester", "metadata " + branchUniversalObject.getContentMetadata().convertToJson());
}
if (linkProperties != null) {
Log.i("BranchSDK_Tester", "Channel " + linkProperties.getChannel());
Log.i("BranchSDK_Tester", "control params " + linkProperties.getControlParams());
}
}
}
}).withData(this.getIntent().getData()).init();
}
@Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent);
if (intent != null && intent.hasExtra("branch_force_new_session") && intent.getBooleanExtra("branch_force_new_session",false)) {
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.i("BranchSDK_Tester", referringParams.toString());
}
}
}).reInit();
}
}
}
```
--------------------------------
### Initialize Branch SDK and Set Pre-install Campaign
Source: https://help.branch.io/developer-hub/docs/xiaomi-pre-install
Call the `isPreinstallApp()` method within your Android App's `onCreate()` method. If it returns true, set the pre-install campaign name and partner using the Branch SDK.
```java
@Override
public void onCreate() {
super.onCreate();
// Branch object initialization
Branch branch = Branch.getAutoInstance(this);
if(isPreinstallApp(getPackageName())){
branch.setPreinstallCampaign("xiaomipai_test_campaign");
branch.setPreinstallPartner("a_xiaomipai");
}
}
```
--------------------------------
### Load and Initialize Branch Web SDK
Source: https://help.branch.io/developer-hub/docs/web-sdk-overview
This script loads the Branch Web SDK and initializes it with your live key. It should be placed in the `` tag of your HTML.
```javascript
load Branch
(function(b,r,a,n,c,h,_,s,d,k){if(!b[n]||!b[n]._q){for(;s<_.length;)c(h,_[s++]);d=r.createElement(a);d.async=1;d.src="https://cdn.branch.io/branch-latest.min.js";k=r.getElementsByTagName(a)[0];k.parentNode.insertBefore(d,k);b[n]=h}})(window,document,"script","branch",function(b,r){b[r]=function(){b._q.push([r,arguments])}},{_q:[],_v:1},"addListener applyCode autoAppIndex banner closeBanner closeJourney creditHistory credits data deepview deepviewCta first getCode init link logout redeem referrals removeListener sendSMS setBranchViewData setIdentity track validateCode trackCommerceEvent logEvent disableTracking".split(" "), 0);
// init Branch
branch.init('key_live_YOUR_KEY_GOES_HERE');
```
--------------------------------
### Install Branch SDK for Expo
Source: https://help.branch.io/developer-hub/docs/react-native-expo-integration
Use this command to install the Branch React Native SDK into your Expo project.
```bash
npx expo install react-native-branch
```
--------------------------------
### Example Link Conversion (Before and After)
Source: https://help.branch.io/developer-hub/docs/ampscript-for-sfmc-configuration
Illustrates the transformation of a plain text link into an AMPscript-driven Branch Link.
```ampscript
%%[SET @link_to_be_wrapped = "https://branch.io/product/1234" ContentBlockByName("My Contents\branch\deeplink")]%%
Example link
```
--------------------------------
### Install MultiDex in Application Class
Source: https://help.branch.io/developer-hub/docs/android-troubleshooting
Ensure your `Application` class extends `MultiDexApplication` and includes this method to install MultiDex.
```Java
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
}
```
```Java
@Override
protected void attachBaseContext(Context base) {
super.attachBaseContext(base);
MultiDex.install(this);
}
```
--------------------------------
### Initialize Branch SDK with Protected API Endpoint
Source: https://help.branch.io/developer-hub/docs/advanced-compliance
This HTML snippet demonstrates how to load the Branch SDK and configure it to use a protected API endpoint. Ensure you replace 'key_live_YOUR_KEY_GOES_HERE' with your actual Branch key.
```html
My Page
```
--------------------------------
### Install Branch Plugin for Expo
Source: https://help.branch.io/developer-hub/docs/react-native-expo-integration
Install the configuration plugin for Branch to manage native configurations within your Expo project.
```bash
npm install @config-plugins/react-native-branch
```
--------------------------------
### Initialize Branch SDK in AppDelegate.cs
Source: https://help.branch.io/developer-hub/docs/maui-configuration
Initialize the Branch SDK in your AppDelegate.cs file. Ensure you replace 'key_live_' with your actual Branch key. This setup handles session initialization and logging.
```csharp
using BranchSDK;
using Foundation;
using UIKit;
namespace MyMauiApp;
[Register("AppDelegate")]
public class AppDelegate : MauiUIApplicationDelegate, IBranchSessionInterface
{
protected override MauiApp CreateMauiApp() => MyMauiApp.MauiProgram.CreateMauiApp();
public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
{
Branch.EnableLogging = true;
BranchIOS.Init("key_live_", launchOptions, this);
return base.FinishedLaunching(application, launchOptions);
}
// Handle URI opens
public override bool OpenUrl(UIApplication application, NSUrl url, NSDictionary options)
{
return BranchIOS.getInstance().OpenUrl(url);
}
// Handle Universal Links
public override bool ContinueUserActivity(UIApplication application, NSUserActivity userActivity, UIApplicationRestorationHandler completionHandler)
{
return BranchIOS.getInstance().ContinueUserActivity(userActivity);
}
public void InitSessionComplete(Dictionary data)
{
LogMessage("InitSessionComplete: ");
foreach (var key in data.Keys)
{
LogMessage(key + " : " + data[key].ToString());
}
}
public void SessionRequestError(BranchError error)
{
LogMessage("SessionRequestError: ");
LogMessage("Error Message: " + error.ErrorMessage);
LogMessage("Error Code: " + error.ErrorCode);
}
void LogMessage(string message)
{
Console.WriteLine(message);
}
}
```
--------------------------------
### Push Notification Payload Example (JSON)
Source: https://help.branch.io/developer-hub/docs/ios-advanced-features
Example of a push notification payload containing a Branch Link in JSON format.
```json
{
"aps": {
"alert": "Push notification with a Branch deep link",
"badge": "1"
},
"branch": "https://example.app.link/u3fzDwyyjF"
}
```
--------------------------------
### NPM Initialization
Source: https://help.branch.io/developer-hub/docs/connected-full-reference
Install the Branch Connected SDK via NPM and initialize it in your JavaScript code with your Branch Key and optional parameters.
```APIDOC
## Initialization via NPM
### Description
Install the `branch-connected-sdk` package using NPM. Then, import and initialize the SDK in your JavaScript code with your Branch Key and optional parameters. The `options` object can be used to pass advertising IDs for ad network attribution.
### Method
`branch.init(branch_key, options, callback)`
### Endpoint
Not Applicable (SDK Method)
### Parameters
#### Initialization Parameters (SDK Method)
- **branch_key** (`string`) - Required - Your Branch live key.
- **options** (`Object`) - Optional - An object for configuration. See options table below.
- **advertising_ids** (`{string:string}`) - Required for Ad Network Attribution, Optional for Web Based Attribution - An object containing device advertising IDs (e.g., `{ SAMSUNG_IFA: 'xxxxx' }`).
- **callback** (`function`) - Optional - A callback function to execute after initialization, receiving `err` and `data`.
### Request Example
```javascript
import branch from 'branch-connected-sdk';
// Pass the device's advertising id through 'options' with the corresponding key (/developers-hub/docs/connected-basic-integration)
const options = {
advertising_ids: {
SAMSUNG_IFA: 'xxxxx',
}
};
// init Branch
branch.init('key_live_YOUR_KEY_GOES_HERE', options, (err, data) => {
if (err) {
console.error('Branch init error:', err);
return;
}
console.log('Branch init data:', data);
});
```
### Response
#### Success Response (Callback Data)
- **data** (`Object`) - An object containing session data, potentially including `referring_link` if the session was opened from a referring link.
#### Error Response (Callback Error)
- **err** (`Object`) - An error object if initialization fails.
```
--------------------------------
### Initialize Branch SDK in Swift
Source: https://help.branch.io/developer-hub/docs/mac-os-basic-integration
Import the Branch SDK and start it with a configuration object in your application's `applicationDidFinishLaunching:` method. Ensure outgoing connections are enabled in your app's capabilities.
```Swift
func applicationDidFinishLaunching(_ aNotification: Notification) {
// Register for Branch URL notifications
NotificationCenter.default.addObserver(self, selector: #selector(branchWillStartSession), name: .BranchWillStartSession, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(branchDidStartSession), name: .BranchDidStartSession, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(branchOpenedURLNotification), name: .BranchDidOpenURLWithSession, object: nil)
// Create a Branch configuration object with your key:
let configuration = BranchConfiguration(key: "YOUR_KEY_HERE")
// Start Branch:
Branch.sharedInstance.start(with: configuration)
}
```
--------------------------------
### Get APK SHA256 Fingerprint
Source: https://help.branch.io/developer-hub/docs/android-app-links
Run this command on your APK file to obtain its SHA256 fingerprint. This is an alternative method to get the fingerprint.
```bash
keytool -printcert -jarfile my_app.apk
```
--------------------------------
### Initialize Branch SDK in MAUI Application
Source: https://help.branch.io/developer-hub/docs/maui-configuration
Add this code to your `MainApplication.cs` to enable Branch logging and get the auto-instance.
```C#
using Android.App;
using Android.Runtime;
using BranchSDK;
namespace MyMauiApp;
[Application]
public class MainApplication : MauiApplication
{
public MainApplication(IntPtr handle, JniHandleOwnership ownership)
: base(handle, ownership)
{
}
public override void OnCreate()
{
base.OnCreate();
Branch.EnableLogging = true;
BranchAndroid.GetAutoInstance(ApplicationContext);
}
protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp();
}
```
--------------------------------
### Create and Initialize Branch Instance in MainScene.brs
Source: https://help.branch.io/developer-hub/docs/sdk-roku-basic-integration
In your main Scene's BrightScript file (e.g., MainScene.brs), create an instance of the Branch SDK and initialize the session within the init() subroutine. A callback function is provided to handle the session initialization response.
```brightscript
sub init()
' Other init Configs...
' BRANCH SDK INTEGRATION - Create Instance'
m.branchSdkObj = CreateBranchSdkForSceneGraphApp()
if (m.branchSdkObj = invalid) then
ShowMessageDialog("Failed to initialize Branch SDK!")
else
' BRANCH SDK INTEGRATION - Initialize Branch'
m.branchSdkObj.initSession(m.global.launchArgs, "OnInitSessionCallbackFunc")
end if
' Other init Configs...
end sub
function OnInitSessionCallbackFunc(event as object) as void
data = event.GetData()
print "OnInitSessionCallbackFunc: " data
if (data <> invalid) then
m.lSessionApiResultDetails.text = FormatJson(data)
else
m.lSessionApiResultDetails.text = "initSession API response received!"
end if
message = "API Succeeded!"
if (data.error <> invalid)
message = "API Error!"
else
print "Branch initSession details: " + message
end if
end function
```
--------------------------------
### Example Device Import for iOS
Source: https://help.branch.io/developer-hub/docs/importing-historical-user-data
This example demonstrates a device import for an iOS device where only IDFV is available due to Limit Ad Tracking being enabled.
```json
{
"timestamp": 1600720443123,
"app_id": 123456789012345678,
"idfv": "30255BCE-4CDA-4F62-91DC-4758FDFF8512"
}
```