Android 基本集成

👍

SDK 统计

Open Source Github Repo

SDK 大小:187kb

速度 :中值80ms至250ms

Minimum OS Version: API Level 21+

Android 版本记录

📘

Amazon Fire 设备支持

Branch Android SDK 4.1.1+包括对 Amazon Fire 设备的支持。

请遵循以下指南,但在 app level build.gradle文件中不要包括以下两行

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

配置 Branch 操作后台 (Dashboard)

15521552

安装 Branch

  • 将 Branch SDK 导入到您的 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

描述

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

从4.3.0版本开始,Google 的 Play Install Referrer Library 已捆绑到 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

配置应用

  • 将 Branch 添加到您的 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>
                <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 -->
            <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>

            <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

Single Task 模式仅在 Activity 堆栈中不存在时才实例化 Main/Splash Activity。

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.

加载 Branch

  • 将 Branch 添加到您的 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.enableTestMode()

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

初始化 Branch

🚧

sessionBuilder 适用于 v4.4.0 +

  • 将 Branch 添加到您的 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
        if (intent != null &&
              intent.hasExtra("branch_force_new_session") && 
              intent.getBooleanExtra("branch_force_new_session",false)) {
            Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
        }
    }
    private Branch.BranchReferralInitListener branchReferralInitListener = 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

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

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
    
    // if activity is in foreground (or in backstack but partially visible) launch the same
    // activity will skip onStart, handle this case with reInit
    if (intent != null && 
            intent.hasExtra("branch_force_new_session") &&
            intent.getBooleanExtra("branch_force_new_session", false)
    ) {
        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 其他 Activity

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.

🚧

始终在 onStart()中初始化 Branch

在其他 Android lifecycle 方法(例如 onCreate()/onResume())中初始化 Branch 会导致非预期行为。 onStart()可使 Activity 被用户可见,因为应用为 Activity 做好准备,使其进入前台并变得互动。

To Learn more:

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

Proguard 设置

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:```bash
-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```bash
-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.```bash
-keep class com.huawei.hms.ads.** { *; }
-keep interface com.huawei.hms.ads.** { *; }

这个页面对您有帮助吗?