Open Facebook from Cocos2d-x Lua with Android Deep Link and Web Fallback

A product requirement asked the game to open its Facebook page. Calling device.openURL() opened the browser rather than the Facebook application, so I used the Lua-to-Java bridge on Android.

Lua Bridge Call

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
function AppInfo.openFacebook(name)
    if device.platform == "Android" then
        local signature = "(Ljava/lang/String;)V"
        local arguments = {name}
        luaj.callStaticMethod(
            AppInfo.JAVA_CLASSNAME,
            "openFacebook",
            arguments,
            signature
        )
    end
end

Android Java Implementation

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
static void openFacebook(final String name) {
    Context context = GameConfig.appContext;

    try {
        context.getPackageManager().getPackageInfo("com.facebook.katana", 0);
        Intent appIntent = new Intent(
            Intent.ACTION_VIEW,
            Uri.parse("fb://page/" + facebookId)
        );
        appIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(appIntent);
    } catch (Exception error) {
        Intent webIntent = new Intent(
            Intent.ACTION_VIEW,
            Uri.parse("https://www.facebook.com/" + name)
        );
        webIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(webIntent);
    }
}

The Java method checks whether the Facebook package is installed, attempts an app deep link, and falls back to the HTTPS page. Deep-link formats can change between Facebook app versions, so verify the current supported link format when maintaining this code.