ZeroyiQ: Unity multi-platform native SDK access Overview (I) : wechat open platform

ZeroyiQ: Unity multi-platform native SDK access overview (ii) : QQ Interconnection

ZeroyiQ: Unity multi-platform native SDK Access Quick overview (3) : Facebook

ZeroyiQ: Unity multi-platform native SDK Access Overview (4) : Twitter

ZeroyiQ: Unity multi-platform native SDK access overview (five) : Weibo

One, foreword

In order to accommodate more engines, the series mainly chose to study the native SDK. This is the Facebook-Android-SDK.

If you only use Unity to connect to Facebook, it is recommended to use the official Unity version, which is easy to use.

Facebook development platform can be directly logged in through Facebook account, currently (2020-7-1) due to COVID-19, individual developer verification has been suspended, only enterprise verification. However, you can still create applications and obtain application numbers.

After creating the app and adding the Facebook login product, you can choose the quick start tutorial, which is provided by the official guidance. The official project also includes a good Demo.

2. SDK access

1. Add the package management repository

Add mavenCentral to the build.gradle (Project) file of the Project.

buildscript {
    repositories {
        mavenCentral()
    }
}
Copy the code

2. Add dependencies

Add dependencies to the build.gradle (Module: app) file of the Module that needs to be connected to the SDK, and then compile and use it.

Dependencies {implementation 'com. Facebook. Android: facebook -- android SDK: [4, 5)'}Copy the code

3. Set the key hash on the background

In order to verify the correctness of application requests and ensure the security between them, Facebook also needs to provide the development environment or publish the secret key hashes.

Generate key dependencies as follows:

  • Key and certificate Management Tool (KeyTool) in the Java development package
  • Openssl-for-windows OpenSSL library for Windows edition of Google Code Archive

The development environment

If the environment is not configured, both keytool and openssl can use the absolute path, XXX \ openSSL-0.9.8e_x64 \bin\openssl.exe.

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\USERNAME\.android\debug.keystore" | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" sha1 -binary | "PATH_TO_OPENSSL_LIBRARY\bin\openssl" base64
Copy the code

After the release of

YOUR_RELEASE_KEY_ALIAS Key alias

YOUR_RELEASE_KEY_PATH Key path

keytool -exportcert -alias YOUR_RELEASE_KEY_ALIAS -keystore YOUR_RELEASE_KEY_PATH | openssl sha1 -binary | openssl base64
Copy the code

4. Set Android configurations

Apply for network permissions in androidmanifest.xml.

Add AppId and login scheme to res\values\strings. XML (no such file, create your own).

<string name="facebook_app_id">561412404767402</string> <! -- Scheme format: FB + APPID --> <string name=" fb_logIN_PROTOCOL_scheme "> Fb561412404767402 </string>Copy the code

Add meta-data and activity configuration to androidmanifest.xml.

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

        <activity
            android:name="com.facebook.FacebookActivity"
            android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:label="@string/app_name" />
        <activity
            android:name="com.facebook.CustomTabActivity"
            android:exported="true">
            <intent-filter><action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
                <data android:scheme="@string/fb_login_protocol_scheme" />
            </intent-filter>
        </activity>
Copy the code

5. Implement the callback

Create the callbackManager to handle callbacks, which can be initialized by calling the following code at OnCreate.

callbackManager = CallbackManager.Factory.create();

In both login and sharing, you can call the respective registerCallback, pass in the initialized callbackManager and FacebookCallback interfaces, and implement the callback methods in FacebookCallback.

Third, the login

1. Add dependencies

Build. Gradle.

Implementation ‘com. Facebook. Android: facebook – login: [5, 6)’

2. Initiate a request

Facebook provides a LoginButton login element that is added directly to the interface. The login request can be initiated directly by clicking the button. Another option is to customize the button. You can log in to the Manager and initiate the login request. Here are two ways to log in.

2. A) Facebook native button

Add to layout XML.

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="30dp"
    android:layout_marginBottom="30dp" /> 
Copy the code

You can bind the callback directly through the LoginButton, or you can log in to the Manager. See custom buttons below.

loginButton = (LoginButton) findViewById(R.id.login_button); / / set the login user domain loginButton. SetReadPermissions (" email "); // Add the following loginbutton.setFragment (this) if a button is in a fragment; / / LoginButton registered callback LoginButton. RegisterCallback (callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code } @Override  public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } });Copy the code

2. B Custom button (triggered in Unity)

The login request is triggered directly through the logInWithReadPermissions method.

Public void login(Activity Activity) {// Check whether the current accessToken already exists and accessToken is not expired if (! AccessToken.isCurrentAccessTokenActive()) { LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { UnityCallApi.unityLogInfo(TAG, "Login successful."); getUserInfo(); } @Override public void onCancel() { UnityCallApi.unityLogInfo(TAG, "Login cancel."); } @Override public void onError(FacebookException error) { error.printStackTrace(); UnityCallApi.unityLogError(TAG, "Login Error" + error.toString()); }}); // Initiate a request, Public_profile for basic user domain LoginManager. GetInstance (). LogInWithReadPermissions (activity, Arrays. AsList (" public_profile ")); }}Copy the code

3. Send the result in onActivityResult

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        callbackManager.onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
Copy the code

4. Obtain user information

Private void getUserInfo() {// Personal me request, Registration request callback GraphRequest request. = GraphRequest newMeRequest (AccessToken. GetCurrentAccessToken (), new GraphRequest.GraphJSONObjectCallback() { @Override public void onCompleted(JSONObject object, GraphResponse response) { FacebookRequestError error = response.getError(); if (null ! = object && TextUtils.isEmpty(error.getErrorMessage())) { UnityCallApi.unityLogInfo(TAG, "Get User Info Successful."); UnityCallApi.sendLoginInfoToUnity(true, object.toString()); } else { UnityCallApi.unityLogError(TAG, String.format("Get User Info Failed.Code: %s Msg: %s", error.getErrorCode(), error.getErrorMessage())); UnityCallApi.sendLoginInfoToUnity(false, ""); }}}); Bundle parameters = new Bundle(); PutString ("fields", "id,name,gender"); request.setParameters(parameters); request.executeAsync(); }Copy the code

Five, share,

Add dependencies to build. gradle

Implementation ‘com. Facebook. Android: facebook – share: [5, 6)’

The setup share callback can be initialized with the 2.5 Setup callback.

shareDialog = new ShareDialog(activity); shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() { @Override public void onSuccess(Sharer.Result result) { UnityCallApi.unityLogInfo(TAG, "Share Successful."); } @Override public void onCancel() { UnityCallApi.unityLogInfo(TAG, "Share Cancel."); } @Override public void onError(FacebookException error) { UnityCallApi.unityLogError(TAG, Format ("Share Error.Msg: %s", Error. ToString ())); }});Copy the code

1. The web page

public void shareWebLink(Bundle params) { if (ShareDialog.canShow(ShareLinkContent.class)) { ShareLinkContent content = New SharelinkContent.builder ().setContentUrl(uri.parse (" web ")).build(); shareDialog.show(content); }}Copy the code

Picture 2.

Share photos or video, must be in the AndroidManifest. XML configuration provider, format of authorities for the com. Facebook. App. FacebookContentProvider + appid.

        <provider
            android:name="com.facebook.FacebookContentProvider"
            android:authorities="com.facebook.app.FacebookContentProvider{APPID}"
            android:exported="true" />
Copy the code

To share code

public void shareImage(Bundle params) { if (ShareDialog.canShow(SharePhotoContent.class)) { SharePhoto photo = new Sharephoto.builder ().setBitmap(bitmap) // bitmap image.build (); SharePhotoContent content = new SharePhotoContent.Builder() .addPhoto(photo) .build(); shareDialog.show(content); }}Copy the code

Six, summarized

Facebook has a good encapsulation of accessToken, which can be determined directly through static methods and is relatively neat to use. Facebook has a complete set of rules for applying for user domains.

Seven, references,

  1. Facebook official Quick Start
  2. Android development -FaceBook login integration
  3. facebook/facebook-android-sdk