Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money.

During the Connect 2021 live event on October 28, Facebook founder Mark Zuckerberg officially announced that the company will change its name to “Meta,” regardless of how it changes access first.

🔥 Creating an application

If yes, skip this step.

💥 Select audience

💥 Select a type

💥 details (can be modified later)

💥 Created successfully (in development)

User data deletion: Applications that access user data must provide users with a way to request data deletion. You must provide data removal request callbacks or instructions that tell users how to delete their data from your application or website. Failure to provide this feature risks being removed from the app store.

💥 Adding a platform

Select next.

Other than that, you’ll get an email warning after you’ve been online for a while.

Of course, you can fill in the package names of the 12 marketplaces for other platforms (such as the official website). However, the key hash is generated using the corresponding package name. Facebook currently recognizes key hashes, not packet names.

I don’t have a key hash here. Fill in the packet name first.

💥 Add the login function

Then he’ll walk you through the integration of the Facebook SDK step by step.

💥 Setting permissions

Access permissions

🔥 integrate with the Facebook SDK

Just follow the instructions above, do not download the SDK project, let you import the version of the library, those are out of date. For example, the SDK that lets you import is still [5,6] version, but the Github version is already 12.0.1, depending on the operation line, the latest project and the import is still to find on Github.

💥 use Maven

🌀 1. Add jCenter () to build.gradle (Project)

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

🌀 2. Add libraries to build.gradle (Module: app)

dependencies {
    implementation 'com. Facebook. Android: facebook -- android SDK: 12.0.1'
    implementation 'com. Facebook. Android: facebook - login: 12.0.1'
}
Copy the code

🌀 3. Build the project

If the automatic event logging function is not disabled when you log in to the SDK using Facebook, the system automatically records and collects application events for Facebook analysis. (This function is basically disabled)

💥 Associate the software package name and default class with the application

💥 Generates a key hash

Key hashes (which may vary from computer to computer), so check whenever you generate a key hash or publish it, and upload it to Facebook.

🌀 Generate development key hashes

Each Android development environment will have a unique development key hash (which may vary from computer to computer). Facebook supports uploading multiple keys.

Mac OS

The key and certificate management tool (Keytool) from the Java development package is required. To generate a development key hash, open a terminal window and run the following command:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
Copy the code

Windows

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

To generate a development key hash, run the following command at the command prompt in the Java SDK folder:

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

🌀 Generate publish key hash (published)

Android apps must be signed electronically using a distribution key before they can be uploaded to the store. To generate a publish key hash, run the following command on Mac or Windows:

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

🌀 code generation

This is the way I use it all the time. Simple and convenient

        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "Com.scc. sccmall(your package name)",
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                Log.e("HashKey:", Base64.encodeToString(md.digest(), Base64.DEFAULT)); }}catch (PackageManager.NameNotFoundException e) {
        } catch (NoSuchAlgorithmException e) {
        }
Copy the code

Results: E/HashKey: + HCAQng1tQI5z/lqF2jVThpufHk =

The + HCAQng1tQI5z/lqF2jVThpufHk = let’s fill them in the save, continue to go down.

🌀 Error message is generated

During the login test, a message is displayed indicating that the key hash is incorrect and the correct key hash is displayed.

💥 Configure resources and list files

🌀 adds resources in strings.xml

The application number just obtained

<string name="facebook_app_id">2992757927647074</string> 
<string name="fb_login_protocol_scheme">fb2992757927647074</string>
Copy the code

🌀 Add content in 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

💥 Records application events

Due to the reasons of iOS14, application events (which take about 14 days to send back events) cannot meet the operation requirements, so the uploads from AppsFlyer to Facebook are often analyzed.

Of course, if only reference or no time requirements can access

Add content to the onCreate method of the 🌀 Application class

@Override
public void onCreate(a) {
    super.onCreate();
    FacebookSdk.sdkInitialize(getApplicationContext());
    AppEventsLogger.activateApp(this);
}
Copy the code

🌀 Purchase event

logger.logPurchase(BigDecimal.valueOf(4.32), Currency.getInstance("USD"));
Copy the code

🌀 Other Events

    public void setEvent(String event) {
        AppEventsLogger logger = AppEventsLogger.newLogger(MyApp.getAppContext().getTopActivity());
        if(event.equals("Complete Registration"))
        {
            // Here you can pass in fb-defined events or customize them
            // Params is the event parameter you pass in
            Bundle params = new Bundle();
            logger.logEvent(AppEventsConstants.EVENT_NAME_COMPLETED_REGISTRATION, params);
        }else {
            logger.logEvent(event);
        }
        setAfEvent(event, null);
    }
Copy the code

💥 Register callback

public class MainActivity extends AppCompatActivity {

    private CallbackManager registerCallback(a){
        if (callbackManager == null) {
            callbackManager = CallbackManager.Factory.create();

            LoginManager.getInstance().registerCallback(callbackManager,
                    new FacebookCallback<LoginResult>() {
                        @Override
                        public void onSuccess(LoginResult loginResult) {
                            AccessToken accessToken = loginResult.getAccessToken();
                            String userId = accessToken.getUserId();
                            String token = accessToken.getToken();
                            MLog.e("onSuccessLogin"."userId:" + userId + "|accessToken:" + token);
                        }

                        @Override
                        public void onCancel(a) {
                            // App code
                            MLog.e("onCancel");
                        }

                        @Override
                        public void onError(FacebookException exception) {
                            MLog.e("onError"); }}); }return callbackManager;
    }
    private CallbackManager callbackManager;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        registerCallback().onActivityResult(requestCode, resultCode, data);
        super.onActivityResult(requestCode, resultCode, data);
    }
Copy the code

🔥 install FaceBook

  • Android WebView login has been abandoned.

  • The SDK version must be later than 8.2 and remove any overwriting in the LoginBehavior during login (that is, using loginbehavior.web_view_only).

So you have to download FaceBoook to log in.

🔥 Start testing

💥 developing

You can generate test accounts for this application test.

💥 has launched

I opened it up and tested it directly with my Facebook account.

💥 error

  • Some are caused by the key hash input error, add the key hash she prompted.

  • Some applications do not take effect because they have just been created or external. Try again later.

  • Permissions and functions are not set

💥 Login test

Call the SDK method to log in, and the public_profile passed in is the permission we applied for above.

Public_profile: allows applications to read default public profile fields in user nodes. The system automatically grants this permission to all applications.

LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile"));
Copy the code

Ok, got in the callback interface LoginResult. GetAccessToken (), here is the AccessToken userId and token, live.

Log printing:

E/-SCC-onSuccessLogin: 
userId:600111111111194| accessToken:EAAqh5cEtF2IBAHy4SZBSGTEKKkcLPIBw83Uslk2yKOgZB5iCdDGLiXXXXXXXXXXXXXXXXXXGkN9COLbLAebhqVpyPdq7FEnto2ZB7S8nXzL 2U754VZBJ5xfvrnhEJ4mqtYHqHIAO88MRKOXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXhqVpD48lZA1zfBejpyfglXQ0kYUIj0S1JeEkKhZAh0KIhAZDZDCopy the code

Ok, got in the callback interface LoginResult. GetAccessToken (),

🔥 Apply event tests

🔥 portal

💥 Log in to the document portal

💥 Create an application portal

💥 Apply events to test the portal

💥 GithubSDKDemo portal