Package 

Class Branch

  • All Implemented Interfaces:
    io.branch.referral.BranchViewHandler.IBranchViewEvents , io.branch.referral.StoreReferrerGooglePlayStore.IGoogleInstallReferrerEvents , io.branch.referral.StoreReferrerHuaweiAppGallery.IHuaweiInstallReferrerEvents , io.branch.referral.StoreReferrerSamsungGalaxyStore.ISamsungInstallReferrerEvents , io.branch.referral.StoreReferrerXiaomiGetApps.IXiaomiInstallReferrerEvents , io.branch.referral.SystemObserver.AdsParamsFetchEvents

    
    public class Branch
     implements BranchViewHandler.IBranchViewEvents, SystemObserver.AdsParamsFetchEvents, StoreReferrerGooglePlayStore.IGoogleInstallReferrerEvents, StoreReferrerHuaweiAppGallery.IHuaweiInstallReferrerEvents, StoreReferrerSamsungGalaxyStore.ISamsungInstallReferrerEvents, StoreReferrerXiaomiGetApps.IXiaomiInstallReferrerEvents
                        

    The core object required when using Branch SDK. You should declare an object of this type at the class-level of each Activity or Fragment that you wish to use Branch functionality within.

    Normal instantiation of this object would look like this:

    • Method Detail

      • getInstance

         static synchronized Branch getInstance()

        Singleton method to return the pre-initialised object of the type Branch.Make sure your app is instantiating BranchApp before calling this methodor you have created an instance of Branch already by calling getInstance(Context ctx).

      • getAutoInstance

         static synchronized Branch getAutoInstance(@NonNull() Context context)

        Singleton method to return the pre-initialised, or newly initialise and return, a singletonobject of the type Branch.

        Use this whenever you need to call a method directly on the Branch object.

        Parameters:
        context - A Context from which this call was made.
      • getAutoInstance

         static Branch getAutoInstance(@NonNull() Context context, @NonNull() String branchKey)

        Singleton method to return the pre-initialised, or newly initialise and return, a singletonobject of the type Branch.

        Use this whenever you need to call a method directly on the Branch object.

        Parameters:
        context - A Context from which this call was made.
        branchKey - A String value used to initialize Branch.
      • setBranchRemoteInterface

         void setBranchRemoteInterface(BranchRemoteInterface remoteInterface)

        Sets a custom Branch Remote interface for handling RESTful requests. Call this for implementing a custom network layer for handling communication betweenBranch SDK and remote Branch server

        Parameters:
        remoteInterface - A instance of class extending BranchRemoteInterface withimplementation for abstract RESTful GET or POST methods, if nullis passed, the SDK will use its default.
      • enableTestMode

         static void enableTestMode()

        Enables the test mode for the SDK. This will use the Branch Test Keys. This is same as setting"io.branch.sdk.TestMode" to "True" in Manifest file.Note: As of v5.0.1, enableTestMode has been changed. It now uses the test key but will not log or randomizethe device IDs. If you wish to enable logging, please invoke enableLogging. If you wish to simulateinstalls, please see add a Test Device (https://help.branch.io/using-branch/docs/adding-test-devices)then reset your test device's data (https://help.branch.io/using-branch/docs/adding-test-devices#section-resetting-your-test-device-data).

      • disableTestMode

         static void disableTestMode()

        Disables the test mode for the SDK.

      • disableAdNetworkCallouts

         void disableAdNetworkCallouts(boolean disabled)

        Disable (or re-enable) ad network callouts. This setting is persistent.

        Parameters:
        disabled - (@link Boolean) whether ad network callouts should be disabled.
      • expectDelayedSessionInitialization

         static void expectDelayedSessionInitialization(boolean expectDelayedInit)

        Temporarily disables auto session initialization until user initializes themselves.Context: Branch expects session initialization to be started in LauncherActivity.onStart(),if session initialization has not been started/completed by the time ANY Activity resumes,Branch will auto-initialize. This allows Branch to keep an accurate count of all app sessions,including instances when app is launched from a recent apps list and the first visible Activityis not LauncherActivity.However, in certain scenarios users may need to delay session initialization (e.g. to asynchronouslyretrieve some data that needs to be passed to Branch prior to session initialization). In thosecases, use expectDelayedSessionInitialization() to temporarily disable auto self initialization.Once the user initializes the session themselves, the flag will be reset and auto session initializationwill be re-enabled.

        Parameters:
        expectDelayedInit - A Boolean to set the expectation flag.
      • setAPIUrl

         static void setAPIUrl(String url)

        Sets a custom base URL for all calls to the Branch API. Requires https.

        Parameters:
        url - The String URL base URL that the Branch API uses.
      • setCDNBaseUrl

         static void setCDNBaseUrl(String url)

        Sets a custom CDN base URL.

        Parameters:
        url - The String base URL for CDN endpoints.
      • disableTracking

         void disableTracking(boolean disableTracking)

        Method to change the Tracking state. If disabled SDK will not track any user data or state. SDK will not send any network calls except for deep linking when tracking is disabled

      • setPlayStoreReferrerCheckTimeout

         static void setPlayStoreReferrerCheckTimeout(long delay)

        Set timeout for Play Store Referrer library. Play Store Referrer library allows Branch to providemore accurate tracking and attribution. This delays Branch initialization only the first time user opens the app.This method allows to override the maximum wait time for play store referrer to arrive.

        Parameters:
        delay - Long Maximum wait time for install referrer broadcast in milli seconds.
      • disableInstantDeepLinking

         static void disableInstantDeepLinking(boolean disableIDL)

        Disables or enables the instant deep link functionality.

        Parameters:
        disableIDL - Value {@code true} disables the instant deep linking.
      • resetUserSession

         void resetUserSession()

        Manually sets the Boolean value, that indicates that the Branch API connection hasbeen initialised, to false - forcing re-initialisation.

      • setRetryCount

         void setRetryCount(int retryCount)

        Sets the max number of times to re-attempt a timed-out request to the Branch API, beforeconsidering the request to have failed entirely. Default to 3. Note that the the networktimeout, as set in setNetworkTimeout, together with the retry interval value from setRetryInterval will determine if the max retry count will be attempted.

        Parameters:
        retryCount - An Integer specifying the number of times to retry before givingup and declaring defeat.
      • setRetryInterval

         void setRetryInterval(int retryInterval)

        Sets the amount of time in milliseconds to wait before re-attempting a timed-out requestto the Branch API. Default 1000 ms.

        Parameters:
        retryInterval - An Integer value specifying the number of milliseconds towait before re-attempting a timed-out request.
      • setNetworkTimeout

         void setNetworkTimeout(int timeout)

        Sets the duration in milliseconds that the system should wait for a response before timingout any Branch API. Default 5500 ms. Note that this is the total time allocated for all requestretries as set in setRetryCount.

        Parameters:
        timeout - An Integer value specifying the number of milliseconds to wait beforeconsidering the request to have timed out.
      • setNetworkConnectTimeout

         void setNetworkConnectTimeout(int connectTimeout)

        Sets the duration in milliseconds that the system should wait for initializing a network* request.

        Parameters:
        connectTimeout - An Integer value specifying the number of milliseconds to wait beforeconsidering the initialization to have timed out.
      • setNoConnectionRetryMax

         void setNoConnectionRetryMax(int retryMax)

        In cases of persistent no internet connection or offline modes,set a maximum number of attempts for the Branch Request to be tried.Must be greater than 0Defaults to 3

      • setReferrerGclidValidForWindow

         void setReferrerGclidValidForWindow(long window)

        Sets the window for the referrer GCLID field. The GCLID will be persisted locally from thetime it is set + window in milliseconds. Thereafter, it will be deleted.By default, the window is set to 30 days, or 2592000000L in millsecondsMinimum of 0 millisecondsMaximum of 3 years

        Parameters:
        window - A Long value specifying the number of milliseconds to wait beforedeleting the locally persisted GCLID value.
      • setDeepLinkDebugMode

         void setDeepLinkDebugMode(JSONObject debugParams)

        Sets the key-value pairs for debugging the deep link. The key-value set in debug mode is given back with other deep link data on branch init session.This method should be called from onCreate() of activity which listens to Branch Init Session callbacks

        Parameters:
        debugParams - A JSONObject containing key-value pairs for debugging branch deep linking
      • enableFacebookAppLinkCheck

         void enableFacebookAppLinkCheck()

        Enable Facebook app link check operation during Branch initialisation.

      • setLimitFacebookTracking

         void setLimitFacebookTracking(boolean isLimitFacebookTracking)

        Enables or disables app tracking with Branch or any other third parties that Branch use internally

        Parameters:
        isLimitFacebookTracking - {@code true} to limit app tracking
      • addInstallMetadata

         Branch addInstallMetadata(@NonNull() String key, @NonNull() String value)

        This API allows to tag the install with custom attribute. Add any key-values that qualify or distinguish an install here.Please make sure this method is called before the Branch init, which is on the onStartMethod of first activity.A better place to call this method is right after Branch#getAutoInstance()

      • enableCookieBasedMatching

         static void enableCookieBasedMatching(String cookieMatchDomain)

        Enabled Strong matching check using chrome cookies. This method should be called beforeBranch#getAutoInstance(Context).

        Parameters:
        cookieMatchDomain - The domain for the url used to match the cookie (eg.
      • enableCookieBasedMatching

         static void enableCookieBasedMatching(String cookieMatchDomain, int delay)

        Enabled Strong matching check using chrome cookies. This method should be called beforeBranch#getAutoInstance(Context).

        Parameters:
        cookieMatchDomain - The domain for the url used to match the cookie (eg.
        delay - Time in millisecond to wait for the strong match to check to finish before Branch init session is called.Default time is 750 msec.
      • addWhiteListedScheme

         Branch addWhiteListedScheme(String urlWhiteListPattern)

        Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist.However the following method provisions application to set SDK to collect only URLs in particular form. This method allow application to specify a set of regular expressions to white list the URL collection.If whitelist is not empty SDK will collect only the URLs that matches the white list.

        This method should be called immediately after calling getAutoInstance

        Parameters:
        urlWhiteListPattern - A regular expression with a URI white listing pattern
      • setWhiteListedSchemes

         Branch setWhiteListedSchemes(List<String> urlWhiteListPatternList)

        Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist.However the following method provisions application to set SDK to collect only URLs in particular form. This method allow application to specify a set of regular expressions to white list the URL collection.If whitelist is not empty SDK will collect only the URLs that matches the white list.

        This method should be called immediately after calling getAutoInstance

        Parameters:
        urlWhiteListPatternList - List of regular expressions with URI white listing pattern
      • addUriHostsToSkip

         Branch addUriHostsToSkip(String urlSkipPattern)

        Branch collect the URLs in the incoming intent for better attribution. Branch SDK extensively check for any sensitive data in the URL and skip if exist.This method allows applications specify SDK to skip any additional URL patterns to be skipped

        This method should be called immediately after calling getAutoInstance

        Parameters:
        urlSkipPattern - String A URL pattern that Branch SDK should skip from collecting data
      • setIdentity

         void setIdentity(@NonNull() String userId)

        Identifies the current user to the Branch API by supplying a unique identifier as a String value. No callback.

        Parameters:
        userId - A String value containing the unique identifier of the user.
      • setIdentity

         void setIdentity(@NonNull() String userId, @Nullable() Branch.BranchReferralInitListener callback)

        Identifies the current user to the Branch API by supplying a unique identifier as a String value, with a callback specified to perform a defined action upon successfulresponse to request.

        Parameters:
        userId - A String value containing the unique identifier of the user.
        callback - A BranchReferralInitListener callback instance that will returnthe data associated with the user id being assigned, if available.
      • isUserIdentified

         boolean isUserIdentified()

        Indicates whether or not this user has a custom identity specified for them. Note that this is independent of installs.If you call setIdentity, this device will have that identity associated with this user until logout is called.This includes persisting through uninstalls, as we track device id.

      • logout

         void logout()

        This method should be called if you know that a different person is about to use the app. For example,if you allow users to log out and let their friend use the app, you should call this to notify Branchto create a new user for this device. This will clear the first and latest params, as a new session is created.

      • logout

         void logout(Branch.LogoutStatusListener callback)

        This method should be called if you know that a different person is about to use the app. For example,if you allow users to log out and let their friend use the app, you should call this to notify Branchto create a new user for this device. This will clear the first and latest params, as a new session is created.

        Parameters:
        callback - An instance of io.branch.referral.Branch.LogoutStatusListener to callback with the logout operation status.
      • userCompletedAction

         void userCompletedAction(@NonNull() String action, JSONObject metadata)

        A void call to indicate that the user has performed a specific action and for that to bereported to the Branch API, with additional app-defined meta data to go along with that action.

        Parameters:
        action - A String value to be passed as an action that the user has carriedout.
        metadata - A JSONObject containing app-defined meta-data to be attached to auser action that has just been completed.
      • userCompletedAction

         void userCompletedAction(String action)

        A void call to indicate that the user has performed a specific action and for that to bereported to the Branch API.

        Parameters:
        action - A String value to be passed as an action that the user has carriedout.
      • getFirstReferringParams

         JSONObject getFirstReferringParams()

        Returns the parameters associated with the link that referred the user. This is only set once,the first time the user is referred by a link. Think of this as the user referral parameters.It is also only set if isReferrable is equal to true, which by default is only trueon a fresh install (not upgrade or reinstall). This will change on setIdentity (if theuser already exists from a previous device) and logout.

      • getFirstReferringParamsSync

         JSONObject getFirstReferringParamsSync()

        This function must be called from a non-UI thread! If Branch has no install link data,and this func is called, it will return data upon initializing, or until LATCH_WAIT_UNTIL.Returns the parameters associated with the link that referred the user. This is only set once,the first time the user is referred by a link. Think of this as the user referral parameters.It is also only set if isReferrable is equal to true, which by default is only trueon a fresh install (not upgrade or reinstall). This will change on setIdentity (if theuser already exists from a previous device) and logout.

      • getLatestReferringParams

         JSONObject getLatestReferringParams()

        Returns the parameters associated with the link that referred the session. If a userclicks a link, and then opens the app, initSession will return the parameters of the linkand then set them in as the latest parameters to be retrieved by this method. By default,sessions persist for the duration of time that the app is in focus. For example, if youminimize the app, these parameters will be cleared when closeSession is called.

      • getLatestReferringParamsSync

         JSONObject getLatestReferringParamsSync()

        This function must be called from a non-UI thread! If Branch has not been initializedand this func is called, it will return data upon initialization, or until LATCH_WAIT_UNTIL.Returns the parameters associated with the link that referred the session. If a userclicks a link, and then opens the app, initSession will return the parameters of the linkand then set them in as the latest parameters to be retrieved by this method. By default,sessions persist for the duration of time that the app is in focus. For example, if youminimize the app, these parameters will be cleared when closeSession is called.

      • addFacebookPartnerParameterWithName

         void addFacebookPartnerParameterWithName(@NonNull() String key, @NonNull() String value)

        Add a Partner Parameter for Facebook.Once set, this parameter is attached to installs, opens and events until cleared or the app restarts.See Facebook's documentation for details on valid parameters

      • cancelShareLinkDialog

         void cancelShareLinkDialog(boolean animateClose)

        Cancel current share link operation and Application selector dialog. If your app is not using auto session management, make sure you arecalling this method before your activity finishes inorder to prevent any window leak.

        Parameters:
        animateClose - A Boolean to specify whether to close the dialog with an animation.A value of true will close the dialog with an animation.
      • handleNewRequest

         void handleNewRequest(ServerRequest req)

        Handles execution of a new request other than open or install.Checks for the session initialisation and adds a install/Open request in front of this requestif the request need session to execute.

        Parameters:
        req - The ServerRequest to execute
      • notifyNetworkAvailable

         void notifyNetworkAvailable()

        Notify Branch when network is available in order to process the next request in the queue.

      • isAutoDeepLinkLaunch

         static boolean isAutoDeepLinkLaunch(Activity activity)

        Checks if an activity is launched by Branch auto deep link feature. Branch launches activity configured for auto deep link on seeing matching keys.Keys for auto deep linking should be specified to each activity as a meta data in manifest.

        Configure your activity in your manifest to enable auto deep linking as follows
        Parameters:
        activity - Instance of activity to check if launched on auto deep link.
      • enableLogging

         static void enableLogging()

        Enable Logging, independent of Debug Mode.

      • disableLogging

         static void disableLogging()

        Disable Logging, independent of Debug Mode.

      • bypassWaitingForIntent

         static void bypassWaitingForIntent(boolean bypassIntent)

        Use this method cautiously, it is meant to enable the ability to start a session beforethe user opens the app.The use case explained:Users are expected to initialize session from Activity.onStart. However, by default, Branch actuallywaits until Activity.onResume to start session initialization, so as to ensure that the latest intentdata is available (e.g. when activity is launched from stack via onNewIntent). Setting this flag to truewill bypass waiting for intent, so session could technically be initialized from a background serviceor otherwise before the application is even opened.Note however that if the flag is not reset during normal app boot up, the SDK behavior is undefinedin certain cases.

        Parameters:
        bypassIntent - a Boolean indicating if SDK should wait for onResume in order to fire thesession initialization request.
      • isForceSessionEnabled

        @Deprecated() static boolean isForceSessionEnabled()

        Returns true if session initialization should bypass waiting for intent (retrieved after onResume).

      • addExtraInstrumentationData

         void addExtraInstrumentationData(String key, String value)

        Update the extra instrumentation data provided to Branch

        Parameters:
        key - A String Value for instrumentation data key
        value - A String Value for instrumentation data value
      • onBranchViewVisible

         void onBranchViewVisible(String action, String branchViewID)

        Called when a Branch view shown

        Parameters:
        action - action name associated with the Branch view item
        branchViewID - ID for the Branch view displayed
      • onBranchViewAccepted

         void onBranchViewAccepted(String action, String branchViewID)

        Called when user click the positive button on Branch view

        Parameters:
        action - action name associated with the App Branch item
        branchViewID - ID for the Branch view accepted
      • onBranchViewCancelled

         void onBranchViewCancelled(String action, String branchViewID)

        Called when user click the negative button app Branch view

        Parameters:
        action - action name associated with the Branch view
        branchViewID - ID for the Branch view cancelled
      • onBranchViewError

         void onBranchViewError(int errorCode, String errorMsg, String action)

        Called when there is an error on creating or showing Branch view

        Parameters:
        errorCode - Integer with error code for the issue
        errorMsg - String with value error message
        action - action name for the Branch view failed to display
      • showInstallPrompt

         static boolean showInstallPrompt(@NonNull() Activity activity, int requestCode)

        Method shows play store install prompt for the full app. Thi passes the referrer to the installed application. The same deep link params as the instant app are provided to thefull app up on Branch#initSession()

        Parameters:
        activity - Current activity
        requestCode - Request code for the activity to receive the result
      • showInstallPrompt

         static boolean showInstallPrompt(@NonNull() Activity activity, int requestCode, @Nullable() String referrer)

        Method shows play store install prompt for the full app. Use this method only if you have custom parameters to pass to the full app using referrer else use showInstallPrompt

        Parameters:
        activity - Current activity
        requestCode - Request code for the activity to receive the result
        referrer - Any custom referrer string to pass to full app (must be of format "referrer_key1=referrer_value1%26referrer_key2=referrer_value2")
      • showInstallPrompt

         static boolean showInstallPrompt(@NonNull() Activity activity, int requestCode, @NonNull() BranchUniversalObject buo)

        Method shows play store install prompt for the full app. Use this method only if you want the full app to receive a custom BranchUniversalObject to do deferred deep link.Please see showInstallPrompt NOTE :This method will do a synchronous generation of Branch short link for the BUO. So please consider calling this method on non UI threadPlease make sure your instant app and full ap are using same Branch key in order for the deferred deep link working

        Parameters:
        activity - Current activity
        requestCode - Request code for the activity to receive the result
        buo - BranchUniversalObject to pass to the full app up on install
      • initSession

         boolean initSession(boolean isReferrable)