Getting Started with Facebook Analytics for Mobile Apps

Last updated Nov 05, 2020

Facebook introduced Facebook Analytics for Apps, a platform that unifies analytics across multiple devices and platforms

In this post, we will take a high-level view of integrating Facebook Analytics in Android application.

For More Facebook Analytics details, refer official Facebook Analytics Page

To Use the Facebook Analytics feature in our apps we need to Enable this feature.

To do this follow these steps

Step 1: Create a New app a Facebook Portal by following this link https://developers.facebook.com/products/analytics/quickstarts/android/

 

Facebook Analytics

 

Step 2: Add Facebook SDK to the Android project.

  • Open  Android Studio
  • Start a new Android Studio project with minimum   API 15: Android 4.0.3 9 (IceCreamSandwich) or higher and click Next.
  • Click Basic Activity and then click Next, and then Finish
  • Now open the Project level Gradle file and add below 

buildscript {
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:2.3.0'
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}
allprojects {
    repositories {
        jcenter()
    }
}
task clean(type: Delete) {
    delete rootProject.buildDir
}

 

Now open app-level Gradle file and Facebook SDK dependencies

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

    implementation 'com.android.support.constraint:constraint-layout:2.0.4'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.facebook.android:facebook-android-sdk:[5,6)'

}

 

Step 3: Now we need to add Facebook APP ID

open string file in project copy your app id from the Facebook portal and paste it in string

PASE_YOUR_FACEBOOK_APP_ID

 

Now update manifest.xml file by adding internet permission and Facebook APP id like below

 

<uses-permission android:name="android.permission.INTERNET"/>

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <meta-data android:name="com.facebook.sdk.ApplicationId"
               android:value="@string/facebook_app_id"/>
</application>

 

Step 4: 

Now we need to add our Android project details in App created in Facebook Portal 

Here we need to Application Package Name and MainScreen of application.

Now we need to add HashKey for the Created application. The HashKey having 28 length

 

Facebook Android Analytics

 

 

How to create HashKey for Android application for Facebook integration?

 We can Generate HashKey in two ways.

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

 

If you want it for production build add your Released Keystore file.

 

We can also Generate HashKey in Android by programmatically

    try {
        val info = pContext.packageManager.getPackageInfo(pContext.packageName, PackageManager.GET_SIGNATURES)
        for (signature in info.signatures) {
            val md = MessageDigest.getInstance("SHA")
            md.update(signature.toByteArray())
            val hashKey = String(Base64.encode(md.digest(), 0))
            Log.i(TAG, "printHashKey() Hash Key: $hashKey")
        }
    } catch (e: NoSuchAlgorithmException) {
        Log.e(TAG, "printHashKey()", e)
    } catch (e: Exception) {
        Log.e(TAG, "printHashKey()", e)
    }

}

 

Step 5: Verify App Events

Now we can verify app events at Events Manager by running the application 

Events Manager will take 20 minutes to show events on the dashboard.

 

Facebook Analytics

 

How to add Facebook Log Events

Facebook Events are categorized in to below categories

  • Standard events - events and parameters that are defined in the Facebook SDK and are generated by your app.
  • Custom events - events and parameters that you define and are generated by your app.
  • Auto-logged events - events and parameters that are inferred by Facebook based on user interactions with your app and automatically logged

 

 

Also have few Auto-logged Events

Install App

Journey

Launch App

 

See More Facebook Events at https://developers.facebook.com/docs/analytics/send_data/events

 

Sample Code

 

MainActivty.kt

package com.rrtutors.facebookanalytics

import android.content.Context
import android.content.pm.PackageManager
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.util.Base64
import android.util.Log
import com.facebook.appevents.AppEventsLogger
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        printHashKey(applicationContext)
        logSentFriendRequestEvent()
    }

    internal var TAG = "Facebook HashKey"
    fun printHashKey(pContext: Context) {
        try {
            val info = pContext.packageManager.getPackageInfo(pContext.packageName, PackageManager.GET_SIGNATURES)
            for (signature in info.signatures) {
                val md = MessageDigest.getInstance("SHA")
                md.update(signature.toByteArray())
                val hashKey = String(Base64.encode(md.digest(), 0))
                Log.i(TAG, "printHashKey() Hash Key: $hashKey")
            }
        } catch (e: NoSuchAlgorithmException) {
            Log.e(TAG, "printHashKey()", e)
        } catch (e: Exception) {
            Log.e(TAG, "printHashKey()", e)
        }

    }

    fun logSentFriendRequestEvent() {

        val logger = AppEventsLogger.newLogger(this)
        logger.logEvent("App Started ")

    }
}

 

manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.rrtutors.facebookanalytics">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:roundIcon="@mipmap/ic_launcher_round"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>

                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <meta-data android:name="com.facebook.sdk.ApplicationId"
                   android:value="@string/facebook_app_id"/>
    </application>

</manifest>

 

 

Resize and Crop Image in Android Kotlin

Dependency Injection - What is Dependency Injection

One to One Chat Application in Kotlin

 

 

Related Topics

 

 

Article Contributed By :
https://www.rrtutors.com/site_assets/profile/assets/img/avataaars.svg

1557 Views