Android 完整参考
安装(Installation)
编译的 Android SDK 占用空间为187kb
安装 Library 项目
Just add implementation 'io.branch.sdk.android:library:5.+'
to the dependencies section of your build.gradle
file.
一些注意事项:
- If you don't plan to use the
Fabric Answers
integration, and don't want to import theanswers-shim
, just import your project as follows:
implementation ('io.branch.sdk.android:library:5+') {
exclude module: 'answers-shim'
}
- This supports minimum sdk level 21.
- Android SDK 3.x 版本及更高版本通过 TLS1.2 进行通信。
- If you want to import the AAR directly, you can find the build in Nexus here: https://search.maven.org/artifact/io.branch.sdk.android/library.
- 或者,您可以克隆此存储库并将源作为库导入到您的项目中
注册您的应用
You can sign up for your own app id at https://dashboard.branch.io
注册 activity 以进行直接深度链接(可选,但是推荐)
在项目的 Manifest(清单)文件中,您可以通过添加第二个 intent filter 块来注册应用以响应直接深度链接(在移动浏览器中为 yourapp://)。另外,请确保将 yourapp 更改为代表应用名称的唯一 string。
其次,确保此 activity 作为 singleTask 启动。这对于处理来自其他应用(如 Facebook)的正确深度链接很重要。
通常,您将注册某种 splash activity 来处理应用的路由。
<activity
android:name="com.yourapp.SplashActivity"
android:label="@string/app_name"
<!-- Make sure the activity is launched as "singleTask" -->
android:launchMode="singleTask"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Add this intent filter below, and change yourapp to your app name -->
<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>
</activity>
利用 Android App Link 进行深度链接
如果您要构建针对 Android M 或更高版本的应用,使用 Branch 则可以非常轻松地使用 App Link 配置应用以进行深度链接。在项目的 Manifest(清单)文件中,您可以通过添加如下所示的 intent filter 将 activity 注册为 App Linking。
如果使用 app.link
使用 app.link,您无需使用编码 ID,只需要列出域即可。
<activity android:name="com.yourapp.your_activity">
<!-- App Link your activity to Branch 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="yourapp-alternate.app.link" />
<data android:scheme="https" android:host="yourapp.app.link" />
</intent-filter>
</activity>
If using a custom domain
<activity android:name="com.yourapp.your_activity">
<!-- App Link your activity to Branch 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="your.app.com"/>
</intent-filter>
</activity>
这就是您所需要的。与链接关联的深度链接参数会通过 Branch 初始化过程传递。
注意
While using App Links please make sure you have registered the Activity for deep linking using Branch URI scheme as discussed in the previous session inorder to get deep link work on previous versions of Android (which does not support App Links).
通过推送通知进行深度链接
如果您想在应用处于前台时支持基于推送通知的路由,请在 notification intent 中添加以下内容。
intent.putExtra("branch_force_new_session",true);
确定性匹配
Branch 支持使用 Custom Chrome Tab,确保与基于 Cookie 的匹配实现100%匹配。如果您想通过深度链接 metadata进行用户身份验证,我们强烈建议这么做。
您只需将以下内容添加到您的 build.gradle 文件中即可启用确定性匹配
implementation 'com.android.support:customtabs:23.3.0'
注意
Adding additional dependencies may overrun the dex limit and lead to
NoClassDefFoundError
orClassNotFoundException
. Please make sure you have enabled multi-dex support to solve this issue. For more information on enabling multi-dex support please refer to Troubleshooting
配置您的 Android Manifest.xml
注意
Provide internet permission. Branch SDK need internet access to talk to Branch APIs.
将 Branch key 添加到您的项目。
After you register your app, your Branch key can be retrieved on the Settings page of the dashboard. Add it (them, if you want to do it for both your live and test apps) to your project's manifest file as a meta data.
编辑 Manifest(清单)文件以包含上述各项
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="io.branch.sample"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" />
<application>
<!-- Other existing entries -->
<!-- Add this meta-data below, and change "key_live_xxxxxxx" to your actual live Branch key -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_xxxxxxx" />
<!-- For your test app, if you have one; Again, use your actual test Branch key -->
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_yyyyyyy" />
</application>
</manifest>
Proguard 设置,以利用 Branch 的池匹配
要收集 Google Advertising ID,您必须确保 proguard 不会删除必要的Google Ads 类。最可靠的方法是将其添加到您的 proguard 规则中。如果您的应用启用了 proguard,请将以下说明添加到您的 proguard.cfg
or proguard-rules.pro
file:
-keep class com.google.android.gms.** { *; }
如果您使用 Facebook SDK 支持通过 Facebook ads 进行深度链接,请确保将 Facebook SDK 类保留在 proguard 中
-keep class com.facebook.applinks.** { *; }
-keepclassmembers class com.facebook.applinks.** { *; }
-keep class com.facebook.FacebookSdk { *; }
如果要添加对不带 Google 移动服务的华为设备的支持,请确保将其添加到您的混淆规则 (proguard rules)中。
-keep class com.huawei.hms.ads.** { *; }
-keep interface com.huawei.hms.ads.** { *; }
Instant App 深度链接和归因支持
Branch SDK 使您可以更轻松地对 Instant App 进行深度链接和归因。由于 Branch 会自动为您配置并托管 assetlinks.json 文件,因此您无需担心设置 Android App Link 时涉及的所有复杂问题。此外,Branch SDK 可以帮助您更有效地从 Instant App 延迟深度链接到 Android App install 的全过程,从而为每一步提供归因。请确保您已添加以下内容以及常规的 Branch 实现,以实现启用了 Instant App 的项目
You can check out a full demo application on our Github. We've replicated our original Android demo application and modified it to support Android Instant Apps.
1. 初始化 Branch SDK
转到您的核心库项目,其中定义了 Application 类,并将代码片段放入 onCreate() 方法中,如下所示。
public void onCreate() {
super.onCreate();
// Initialize the Branch SDK
Branch.getAutoInstance(this);
}
2. 添加 Branch key
Instant Apps can be rather confusing as there are many different manifests, but you want to find the Manifest that contains your application
tags. Make sure your Application class name is defined here, and then specify the Branch keys inside the application
element.
<application
android:allowBackup="true"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:supportsRtl="true"
android:name=".MyApplication">
<meta-data android:name="io.branch.sdk.TestMode" android:value="false" /> <!-- Set to true to use Branch_Test_Key -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_my_live_key" />
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_my_test_key" />
</application>
3. 将您的 Branch Link 配置为 Android App Link
This guide presumes that you've already configured Branch for Android App Links in the past. If you haven't configured your full native app to use Branch as Android App Links, please complete this guide which will correctly configure the dashboard and manifest.
Now, you simply need to edit the above manifest and paste in the following snippet inside the application
element. Then you'll need to replace the xxxx
with your own custom subdomain which will be visible on the Branch link settings dashboard at the bottom of the page. If you're using a custom subdomain, you can find the advanced instructions in the above link regarding configuring Android App Links.
<application
......
<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="xxxx.app.link" />
<data android:scheme="https" android:host="xxxx-alternate.app.link" />
</intent-filter>
</application>
4. 获得 Branch 深度链接数据
Now that you've outfitted your Instant App project with the above, you can now register a deep link router function for activities you want to receive the deep link data in any Activity split, similar to how you would retrieve deep link data in the full app.
5. 配置从 Instant App 到 Full App 的深度链接
Now, the user has arrived in your Instant App and you're ready to convert them to install your full native app. Don't worry, Branch as got your covered! We have overridden the default showInstallPrompt
with a method that auto configures the Google Play prompt with all of the deep link data you need to carry context through install. Additionally, we can provide you the full set of attribution on how many users conver through this prompt.
Branch SDK 提供了方便的方法来检查应用类型和完整的应用转化。这消除了对 Google IA 支持 SDK('com.google.android.instantapp')的依赖。这里有一些使生活变得轻松的方法
Branch#isInstantApp()
此便捷方法会检查当前运行的应用版本是 Instant App 还是 Full Android App,以便为您提供方便
Branch#showInstallPrompt()
此方法显示 full Android app 的安装提示,使您可以轻松地通过安装过程将 Branch 引用深度数据传递给 full app。与 Branch 通常使用延迟深度链接类似,完整的应用将在句柄回调中接收深度链接参数。
下例显示了如何创建自定义 Branch Universal Object,并将其与安装提示相关联,该提示将在用户安装后传递到完整的本机 Android 应用。
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")
.setContentMetadata(new ContentMetadata()
.addCustomMetadata("property1", "blue")
.addCustomMetadata("property2", "red"));
Branch.showInstallPrompt(myActivity, activity_ret_code, branchUniversalObject);
}
});
} else {
myFullAppInstallButton.setVisibility(View.GONE);
}
初始化
如果您的最低 sdk 级别为15+,要想从 Branch SDK 接收深度链接参数,请调用 initSession 并传入 BranchReferralInitListener。这将返回与刚刚点击的链接关联的 referringParams 字典。您可以随时随地对其进行调用以获得参数。
如果您需要支持 pre 15,Branch 必须知道应用何时打开或关闭,以正确处理深度链接参数获得。您可以在 [this docs site](/zh/developers-hub/docs/android-sdk-overview 上查看有关如何执行此操作的更多详细信息。基本上,如果您不关闭 Branch 会话,则会看到一些奇怪的行为,比如第二次点击链接后,深度链接参数未显示。
初始化 Branch lifecycle
借助我们新的自动会话管理,可以自动完成初始化和关闭会话。
选择1:您有一个自定义 Application 类
如果您有一个自定义 Application 类,只需将此调用添加到 onCreate
public void onCreate() {
super.onCreate();
Branch.getAutoInstance(this);
}
选择2:您没有一个自定义 Application 类
If you are not creating or using an Application class throughout your project, all you need to do is declare BranchApp
as your application class in your manifest.
<application
android:name="io.branch.referral.BranchApp">
注册深度链接路由
Branch branch = Branch.getInstance(getApplicationContext());
branch.initSession(new BranchReferralInitListener(){
@Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
// params are the deep linked params associated with the link that the user clicked -> was re-directed to this app
// params will be empty if no data found
// ... insert custom logic here ...
} else {
Log.i("MyApp", error.getMessage());
}
}
}, this.getIntent().getData(), this);
注意
If you're calling this inside a fragment, please use getActivity() instead of passing in
this
. Also,this.getIntent().getData()
refers to the data associated with an incoming intent.
Next, you'll need to hook into the onNewIntent
method specified inside the Activity lifecycle and set the intent. This is required for conformity with Facebook's AppLinks. Verify that the activity you're implementing has launchMode set to singleTask inside the Manifest declaration. Once that is done, go to said activity and do something like the following:
@Override
public void onNewIntent(Intent intent) {
this.setIntent(intent);
}
initSession 回调中 Branch 提供的数据参数
Previously, Branch did not return any information to the app if initSession
was called but the user hadn't clicked on a link. Now Branch returns explicit parameters every time. Here is a list, and a description of what each represents.
~
表示分析+
表示 Branch 添加的信息- (for the curious,
$
denotes reserved keywords used for controlling how the Branch service behaves)
参数 | 描述 |
---|---|
~channel | 在创建链接时指定共享链接的渠道 |
~feature | The feature, such as invite or share , specified at link creation time |
~tags | 在链接创建时指定的任何标签 |
~campaign | 与链接关联的 Campaign,在链接创建时指定 |
~stage | 在链接创建时指定的阶段 |
~creation_source | 链接创建位置 ('API', 'Dashboard', 'SDK', 'iOS SDK', 'Android SDK', 或 'Web SDK') |
+match_guaranteed | 关于匹配是否以100%的准确性进行的判断是对还是错 |
+referrer | 点击链接的推荐人来源网址(如果已点击链接) |
+phone_number | 用户的电话号码(如果用户通过短信将应用发送给自己) |
+is_first_session | 表示这是第一个会话(安装)还是任何其他会话(打开) |
+clicked_branch_link | 表示用户是否点击了触发该会话的 Branch Link |
+click_timestamp | 点击发生的时间戳记 |
获得会话(安装或打开)参数
这些会话参数在此命令之后随时可用。如果没有参数,则字典将为空。这会刷新每一次的新会话(应用安装和应用打开)。
Branch branch = Branch.getInstance(getApplicationContext());
JSONObject sessionParams = branch.getLatestReferringParams();
要同步获得此信息,请从非 UI 线程调用以下命令:
JSONObject sessionParams = branch.getLatestReferringParamsSync();
获得安装(仅安装)参数
如果要访问原始会话参数(仅为第一个 install 事件传递的参数),则可以使用此行。如果您只想奖励通过推荐链接或其它方式来新安装应用的用户,这会很有用。
Branch branch = Branch.getInstance(getApplicationContext());
JSONObject installParams = branch.getFirstReferringParams();
要同步获得此信息,请从非 UI 线程调用以下命令:
JSONObject sessionParams = branch.getFirstReferringParamsSync();
持久身份
通常,您可能拥有自己的用户 ID,或者希望引用和事件数据在各个平台之间持久存在或进行卸载/重新安装。如果您知道您的用户可以从不同的设备访问您的服务,那么这将很有帮助。这里我们介绍“身份(identity)”的概念。
要识别用户,只需调用:
Branch branch = Branch.getInstance(getApplicationContext());
branch.setIdentity(your user id); // your user id should not exceed 127 characters
注销
如果您在应用中提供注销功能,请确保在注销完成后清除用户。这将确保清除所有存储的参数,并将所有事件归因于正确的身份。
警告
This call will clear the referral credits and attribution on the device.
Branch.getInstance(getApplicationContext()).logout();
Branch Universal Object(用于深度链接,内容分析和索引编制)
随着 Android 中更多方法的演变,我们发现越来越难以管理所有这些方法。我们尽可能多地将其抽象化到一个 Branch Universal Object 概念。它与您要分享的事物(内容或用户)相关联。您可以设置与该对象关联的所有 metadata,然后调用操作方法以获取链接或注册视图。
Branch Universal Object 最佳实践
这里有一组最佳实践,可确保您的分析正确无误,并且您的内容有效地在 Spotlight 上排名。
- 将
canonicalIdentifier
to a unique, de-duped value across instances of the app - 请确保
title
,contentDescription
andimageUrl
properly represent the object - Call
showShareSheet
andcreateShortLink
later in the life cycle, when the user takes an action that needs a link - 当采取相应的用户操作时,调用其他对象事件(购买,分享完成等)
需要避免的实践:
- Don't set the same
title
,contentDescription
andimageUrl
across all objects - 请不要等到用户分享再初始化对象并注册视图。
- 请不要等到您需要链接再初始化对象。
- Don't create many objects at once and register views in a
for
loop.
定义 Branch Universal Object
Universal Object 是定义所有与要链接或索引的内容相关的自定义 metadata的地方。请使用下面的构建器格式来创建一个。
BranchUniversalObject branchUniversalObject = new BranchUniversalObject()
// The identifier is what Branch will use to de-dupe the content across many different Universal Objects
.setCanonicalIdentifier("item/12345")
// The canonical URL for SEO purposes (optional)
.setCanonicalUrl("https://branch.io/deepviews")
// This is where you define the open graph structure and how the object will appear on Facebook or in a deepview
.setTitle("My Content Title")
.setContentDescription("My Content Description")
.setContentImageUrl("https://example.com/mycontent-12345.png")
// You use this to specify whether this content can be discovered publicly - default is public
.setContentIndexingMode(BranchUniversalObject.CONTENT_INDEX_MODE.PUBLIC)
// Here is where you can add custom keys/values to the deep link data
.setContentMetadata(new ContentMetadata()
.addCustomMetadata("property1", "blue")
.addCustomMetadata("property2", "red"));
参数
参数 | 描述 |
---|---|
canonicalIdentifier | This is the unique identifier for content that will help Branch dedupe across many instances of the same thing. If you have a website with pathing, feel free to use that. Or if you have database identifiers for entities, use those. |
标题 | This is the name for the content and will automatically be used for the OG tags. It will insert $og_title into the data dictionary of any link created. |
contentDescription | This is the description for the content and will automatically be used for the OG tags. It will insert $og_description into the data dictionary of any link created. |
imageUrl | This is the image URL for the content and will automatically be used for the OG tags. It will insert $og_image_url into the data dictionary of any link created. |
metadata | These are any extra parameters you'd like to associate with the Branch Universal Object. These will be made available to you after the user clicks the link and opens up the app. To add more keys/values, just use the method addMetadataKey 。 |
price | 与以下 commerce 相关事件结合使用的商品价格。 |
currency | The currency representing the price in ISO 4217 currency code. Default is USD. |
contentIndexMode | Can be set to the ENUM of either ContentIndexModePublic or ContentIndexModePrivate . Public indicates that you'd like this content to be discovered by other apps. Currently, this is only used for Spotlight indexing but will be used by Branch in the future. |
expirationDate | 内容将不再可用或有效的日期。目前,此功能仅用于 Spotlight 索引编制,但将来会被 Branch 使用。 |
追踪用户操作和事件
使用 BranchEvent
class to track special user actions or application specific events beyond app installs, opens, and sharing. You can track events such as when a user adds an item to an on-line shopping cart, or searches for a keyword etc.
BranchEvent
provides an interface to add content(s) represented by a BranchUniversalObject in order to associate content(s) with events.
You can view analytics for the BranchEvents you fire on the Branch dashboard. BranchEvents provide a seamless integration with many third party analytics providers like Google Analytics, Criteo.
BRANCH_STANDARD_EVENT
enumerate the most commonly tracked events and event parameters that can be used with BranchEvent
for the best results. You can always use custom event names and event parameters.
new BranchEvent(BRANCH_STANDARD_EVENT.PURCHASE)
.setAffiliation("affiliation_value")
.setCoupon("coupon_value")
.setCurrency(CurrencyType.USD)
.setTax(12.3)
.setRevenue(1.5)
.setDescription("Event_description")
.setSearchQuery("related_search_query")
.addCustomDataProperty("Custom_Event_Property_Key", "Custom_Event_Property_Val")
.addContentItems(contentBUO1, contentBUO2)
.logEvent(context);
new BranchEvent("My_Custom_Event")
.addCustomDataProperty("key1", "value1")
.addCustomDataProperty("key2", "value2")
.logEvent(context);
在对象上注册用户操作
This functionality is deprecated. Please consider using BranchEvent
for tracking user action and events as described here.
我们已经添加了一系列您希望开始追踪的自定义事件,以便使您进行丰富的分析和定位。下面的列表列出了一个示例片段,该片段调用了注册视图事件。
Key | 值 |
---|---|
BranchEvent.VIEW | 用户查看了对象 |
BranchEvent.ADD_TO_WISH_LIST | 用户将该对象添加到他们的愿望清单 |
BranchEvent.ADD_TO_CART | 用户将对象添加到购物车 |
BranchEvent.PURCHASE_STARTED | 用户开始签出 |
BranchEvent.PURCHASED | 用户购买了该物品 |
BranchEvent.SHARE_STARTED | 用户开始分享对象 |
BranchEvent.SHARE_COMPLETED | 用户完成了分享 |
创建深度链接
Once you've created your Branch Universal Object
, which is the reference to the content you're interested in, you can then get a link back to it with the mechanisms described below. First define the properties of the link itself.
LinkProperties linkProperties = new LinkProperties()
.setChannel("facebook")
.setFeature("sharing")
.addControlParameter("$desktop_url", "https://example.com/home")
.addControlParameter("$ios_url", "https://example.com/ios");
您可以通过在控制参数中插入以下可选 key 来进行自定义重定向:
Key | 值 |
---|---|
"$fallback_url" | 未安装应用时将所有平台的用户发送到这里。请注意,Branch 会将所有 robots 转发到此 URL,从而覆盖在链接中输入的所有 OG 标签。 |
"$desktop_url" | 在台式机或笔记本电脑上将用户发送到这里。默认情况下,它是 Branch 托管的 text-me 服务 |
"$android_url" | Play Store 的替代 URL,用于在用户没有该应用的情况下向其发送。仅当您想要移动网站启动时才需要 |
"$ios_url" | App Store 的替代 URL,用于在用户没有该应用的情况下向其发送。仅在您想要移动网站启动时才需要 |
"$ipad_url" | 与上述相同,但适用于 iPad Store |
"$fire_url" | 与上述相同,但适用于 Amazon Fire Store |
"$blackberry_url" | 与上述相同,但适用于 Blackberry Store |
"$windows_phone_url" | 与上述相同,但适用于 Windows Store |
您可以通过在控制参数插入以下可选 key 来控制每个链接的直接深度链接:
Key | 值 |
---|---|
"$deeplink_path" | 您希望我们追加到您的 URI 的深度链接路径的值。例如,您可以指定 "$deeplink_path": "radio/station/456",然后我们将使用 URI "yourapp://radio/station/456?link_click_id=branch-identifier" 打开应用。这主要是为了支持旧版深度链接基础架构。 |
"$always_deeplink" | true 或 false。 (默认设置为不先进行深度链接)即使我们不确定用户是否已安装该应用,也可以指定此 key 以使我们的链接服务团队尝试打开该应用。如果未安装该应用,我们将退回到相应的 app store 或 $platform_url key。默认情况下,我们仅在看到用户通过 Branch Link 在您的应用中启动会话(已被 Branch cookie 并进行深度链接)时才会打开该应用。 |
然后,向 Universal Object 发出请求以创建 URL。
branchUniversalObject.generateShortUrl(this, linkProperties, new BranchLinkCreateListener() {
@Override
public void onLinkCreate(String url, BranchError error) {
if (error == null) {
Log.i("MyApp", "got my Branch link to share: " + url);
}
}
});
列出带有 App Indexing 的 Google 搜索中的链接
使用 BranchUniversalObject 很容易在 Google 搜索中列出您的 Branch Link 和应用内容。创建 BUO 后,使用以下 API 通过 Firebase App Indexing API 在 Google 搜索中列出您的应用内容。用户点击搜索结果后,将使用深度链接数据打开您的应用,并追踪会话。
This also allow your contents Indexed locally and shown in Google In Apps
search. By default the the BranchUniversal objects are locally indexable. Set your BranchUniversalObject's local index mode to private
if intended to avoid indexing locally
branchUniversalObject.listOnGoogleSearch(context);
注意
Please make sure Firebase app indexing is enabled for your application and has Firebase app indexing dependency added
'implementation 'com.google.firebase:firebase-appindexing:10.0.1'
To test content indexing follow instructionshere.
请启用调试模式并检查日志以获取用于索引的 Branch Link,并将其与以上链接一起使用以验证内容索引。
注意
使用
BranchUniversalObject#removeFromLocalIndexing
method to remove the contents from local index. Please make sure to remove user specific contents from local index up on user logout.
显示自定义分享表
我们已经意识到 Android 提供的本机分享表功能非常差劲,因此我们构建了自己的产品并将其捆绑到核心 SDK 中。该分享表是可自定义的,当用户选择要分享的渠道时,它将自动生成链接。

Android 分享表
要使用它,首先像这样定义自定义分享表样式。其中大多数都是完全可选的,如果您不想花费大量时间进行自定义,我们有很多默认值供您选择。
ShareSheetStyle shareSheetStyle = new ShareSheetStyle(MainActivity.this, "Check this out!", "This stuff is awesome: ")
.setCopyUrlStyle(getResources().getDrawable(android.R.drawable.ic_menu_send), "Copy", "Added to clipboard")
.setMoreOptionStyle(getResources().getDrawable(android.R.drawable.ic_menu_search), "Show more")
.addPreferredSharingOption(SharingHelper.SHARE_WITH.FACEBOOK)
.addPreferredSharingOption(SharingHelper.SHARE_WITH.EMAIL)
.setAsFullWidthStyle(true)
.setSharingTitle("Share With");
要显示分享表,请在 Branch Universal Object 上调用以下内容。您可以根据自己的需要在我们的动画上添加许多回调方法,以进行自定义。
branchUniversalObject.showShareSheet(this,
linkProperties,
shareSheetStyle,
new Branch.ExtendedBranchLinkShareListener() {
@Override
public void onShareLinkDialogLaunched() {
}
@Override
public void onShareLinkDialogDismissed() {
}
@Override
public void onLinkShareResponse(String sharedLink, String sharedChannel, BranchError error) {
}
@Override
public void onChannelSelected(String channelName) {
}
@Override
public boolean onChannelSelected(String channelName, BranchUniversalObject buo, LinkProperties linkProperties) {
return false;
}
});
启用或禁用用户追踪
为了符合追踪要求,您可以在 SDK 级别禁用追踪。您只需调用:
Branch.getInstance().disableTracking(true);
这将防止发送任何 Branch 网络请求(深度链接除外)。如果有人点击 Branch Link,但又不想被追踪,我们会将深度链接数据返回给应用,但不会捕获任何追踪信息。
在 “do-not-track” 模式下,您仍然可以创建和分享链接。它们没有可识别的信息。如果用户不想被追踪,则事件追踪不会将数据传回服务器。您可以随时通过调用上述函数来更改此行为。此信息将被保存并持续存在。
控制 Branch 如何处理网络请求
By default, Branch Android SDK uses Java's javax.net.ssl.HttpsURLConnection
for network requests. There are known issues with that interface and typically applications use third party networking libraries, such as OkHttp, to customize their networking. Branch SDK provides an interface, BranchRemoteInterface
, to apply your networking customization to how Branch handles network requests. Use the below API to set your implementation of BranchRemoteInterface
to handle Branch requests.
setBranchRemoteInterface(@NonNull BranchRemoteInterface remoteInterface)
setBranchRemoteInterface(remoteInterface: BranchRemoteInterface)
Below is an example of an implementation of BranchRemoteInterface
using OkHttp.
public class OkhttpBranchNetworkInterface extends BranchRemoteInterface {
private OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(3, TimeUnit.SECONDS).writeTimeout(3, TimeUnit.SECONDS).connectTimeout(3, TimeUnit.SECONDS).build();
@Override
public BranchResponse doRestfulGet(String url) throws BranchRemoteException {
Request request = new Request.Builder().url(url).build();
return handleNetworkRequest(request);
}
@Override
public BranchResponse doRestfulPost(String url, JSONObject payload) throws BranchRemoteException {
Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"), payload.toString())).build();
return handleNetworkRequest(request);
}
private BranchResponse handleNetworkRequest(Request request) throws BranchRemoteException {
try {
Response response = okHttpClient.newCall(request).execute();
ResponseBody rb = response.body();
if (rb != null) throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
return new BranchResponse(rb.string(), response.code());
} catch(Exception exception) {
if (exception instanceof SocketTimeoutException) {
// add desired retry logic, then eventually throw BranchError.ERR_BRANCH_REQ_TIMED_OUT
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT);
} else {
// handle other failures as needed, throw BranchError.ERR_BRANCH_NO_CONNECTIVITY as a default
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
}
}
}
}
public class OkhttpBranchNetworkInterface extends BranchRemoteInterface {
private OkHttpClient okHttpClient = new OkHttpClient.Builder().readTimeout(3, TimeUnit.SECONDS).writeTimeout(3, TimeUnit.SECONDS).connectTimeout(3, TimeUnit.SECONDS).build();
@Override
public BranchResponse doRestfulGet(String url) throws BranchRemoteException {
Request request = new Request.Builder().url(url).build();
return handleNetworkRequest(request);
}
@Override
public BranchResponse doRestfulPost(String url, JSONObject payload) throws BranchRemoteException {
Request request = new Request.Builder().url(url).post(RequestBody.create(MediaType.parse("application/json"), payload.toString())).build();
return handleNetworkRequest(request);
}
private BranchResponse handleNetworkRequest(Request request) throws BranchRemoteException {
try {
Response response = okHttpClient.newCall(request).execute();
ResponseBody rb = response.body();
if (rb != null) throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
return new BranchResponse(rb.string(), response.code());
} catch(Exception exception) {
if (exception instanceof SocketTimeoutException) {
// add desired retry logic, then eventually throw BranchError.ERR_BRANCH_REQ_TIMED_OUT
throw new BranchRemoteException(BranchError.ERR_BRANCH_REQ_TIMED_OUT);
} else {
// handle other failures as needed, throw BranchError.ERR_BRANCH_NO_CONNECTIVITY as a default
throw new BranchRemoteException(BranchError.ERR_BRANCH_NO_CONNECTIVITY);
}
}
}
}
Updated 25 days ago