Saturday, April 25, 2015

App Invites For Android & iOS Apps - Facebook Friends To Mobile App

Recently I got a Notification from my Close friend in Facebook suggesting me to try a Android App.I too Eagerly clicked over that and installed from Google Play.
And the next day i was asking her how did you invite me via Facebook ? or just spammy Notification just like another Candy Crush Saga :D.Then she shown this page to me App-invites - Facebook Developers page.I was Wondering how could i invite From My App(Android) and checked out the Documentation  About the App invites and it was Quite confusing first,however after lot of Searching over Stackoverflow,reading the Documentation thrice i could build a Simple Invite System from My Android App to Invite and Suggest the App in Facebook to Engage to Download or to open the app.

App Invites For Android & iOS Apps -  Facebook Friends To Mobile App

Refernce : Download Code from GitHub 

A Drift from Web App to Mobile App : 

Once Upon a time i could remember working with implementing the invite system with Javascript with Facebook,and Now i consider this is as a Major Drift Change from web app to Mobile apps replacing it.This invite system can increase the User engagement to the user at higher levels,since you're personally inviting your friend,sweetheart :D to try those Apps.

Prerequisites : 

Here we're developing a Simple Android App that has invite button and directs to invite popup and invite our friends in facebook.
  • Android Studio With Recent SDK installed (Preferable for Dependency Adding).
  • Facebook Developer Account.
  • Register A Facebook App with Key Hash and Package Name.
  • Android Phone with facebook App Logined
  • Little patience to Debug the App via logcat.
  • A little Knowledge About Developing Android Apps and Java.
Before Writing this post,I have created a small App which made me many troubles such as App crashing,Low speed internet Connectivity(My Fate :D ) and Some Exceptions.here i will completely write my experience and exception and how i handled them.If anything apart from this let's discuss in Comments or over Email.

Creating Facebook Application - Developer console :

here we can discuss about creating Facebook App and obtaining APP ID and Secret keys for our app,and providing platform as Android,Adding key hash and package name.

  • visit here and Create new App - Link - Facebook Developers Console.
  • select the Platform As Android > and provide a Name for Your app corresponding to your android app.
  • Choose a Best category that fits your App(Most recommended by facebook to Rank your app).
  • Provide the package name to facebook and Launcher Activity too as java package name.(be cautious about package name or else it wont works :D)
  • Provide your necessary app info and move on to key hashes(will see it later how to add it)
  • At the top right of the Page click skip the Quick start and you will be redirected to App dashboard which you have created.
  • go to app > settings > provide a namespace for your app(mandatory)
  • Add contact email also and save it.
  • Now,at below add platform > select Web app and give your website address(if it available)
  • if you have website and added the platform then,Add your domain in Domain Field and Save the info.(Don't worry if you don't have any websites just skip to next step)
  • Get your APP ID and make your App live for production in status & review > toggle the button to enter in to Production mode.
  • And finally We need to Add Key hashes to our Facebook App console.(see below)

How to Generate Key Hash and Add to Developer Console :

just with your onCreate method add this code and replace with your package name correctly and run your app in Debug method(by Default it would be) and check your Logcat for the keyHash : XXXXXXXXXXXXX. Just copy it and visit your app in facebook Developer Account > Settings > in the Android Section (Which you have already created with package name) in the key Hash Field add it over and enable single-signon(may be useful for apps with login) and save the app settings.

Note : this is preferable method which i have created the key added to my Account.
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Add code to print out the key hash
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                "REPLACE WITH YOUR PACKAGE NAME HERE", 
                PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
            }
    } catch (NameNotFoundException e) {

    } catch (NoSuchAlgorithmException e) {

    }

Android Studio Project and Facebook SDK Setup :

I just love Android Studio mainly because it automatically adds the dependency with one line in app gradle.However i'm not expert in Working of Gradle system! however i know how to use it projects to add dependency without any pain unlike Eclipse you have to Add it and point the locations and export while you're building it finally.
  • Open You Android Studio(i hope you have installed latest SDK and tools installed).
  • create new project with a Empty Blank Activity.
Now just open your app gradle file and add the entries to resolve the dependencies via maven repository.

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.facebook.android:facebook-android-sdk:4.0.0'
}
 and just sync your gradle or rebuild your project.

Note : Mainly this Dependency support from API 9 and above.just change minSDK as 9 and higher till Android API 22 or L (your choice).

Adding the Code : 

lets just first see about setting permissions and adding entries in Manifest file regarding Facebook SDK setup.
  • I have added a default activity to be launched and shown in launcher.
  • then added facebook activity (may be useful for apps used for login/share with facebook)
  • added meta-data content containing facebook app id as string from xml file.
    don't just hardcode your APP ID, it may create exceptions,it is recommended by facebook to use as String from xml string.
  • Finally add Permission for internet appropriately since we are doing network based operation in our app and facebook needs it. 
        

    <uses-permission android:name="android.permission.INTERNET" />
<application ...>
<activity
            android:name=".facebook"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/title_activity_facebook" >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
                <action android:name="android.intent.action.VIEW" />
                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
               
            </intent-filter>


        </activity>
        <activity android:name="com.facebook.FacebookActivity"
            android:configChanges=
                "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
            android:theme="@android:style/Theme.Translucent.NoTitleBar"
            android:label="@string/app_name" />

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

So just use this example to add your manifest file,and check that you have added facebook activity in your manifest file too.

MainActivity - Activity to initiate App invites :

Here we are initializing the App with facebook library and set the view as XML layout and then simply add a link and preview image preferably a large image is recommended.
get your App links from facebook to launch the activity from facebook or web or some other apps.learn more about app links here in my previous article.
create App link from here
  • select the created facebook app for android
  • Select android platform and scroll down
  • in the Android section , Add your package name for launching the app if it is present in the particular device or else just as fallback it may be moving into playstore.
  • Enter your playstore package name(must be equivalent to your android app project package name)
  • If you have website just add it,check that you have app links in the head section of the website and the domain should be already added in the App> settings > domain(when web platform is enabled )
  • Create a new Applink and just copy it.
Just replace with your app link in the code given below,and chenge your imageurl too(must be high resolution image).
 
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

            FacebookSdk.sdkInitialize(getApplicationContext());

            setContentView(R.layout.activity_facebook);
            
String appLinkUrl, previewImageUrl;

            appLinkUrl = "https://fb.me/493857950766025";
            previewImageUrl = "https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgUzhjIqsj81dnMpN-TwpRL-oKQy7Gr2kHPgIe_d8_XLpucTjbvpFgQVznZFLkuXDlQ8iLHml6shtTFV7mEAk-ZEJ7AvVMMkrMqSWj4npc7jLMC5inGnBT4xOV-Y3j5A6MH3D-vdQDupvHG/s1600/appscripts.png";

                AppInviteContent content = new AppInviteContent.Builder()
                        .setApplinkUrl(appLinkUrl)
                        .setPreviewImageUrl(previewImageUrl)
                        .build();
                AppInviteDialog.show(this, content);

        }
Thus while Opening your app this will default invoke to app invite activity of facebook.
Here facebook verifies the user has installed however latest facebook app in device or else as fallback it opens as webview facebook.You must be logined in the facebook Native app or Webview already will be fine for testing.

Main Note:

This Invite Feature doesnt need any Login With Facebook Feature,This just Simply enables you to invite your friends when you're logined with facebook app.

Errors which i came across:

  • null pointer Exception for not Adding Facebook App ID in manifest file.
  • null pointer Exception for Hardcoding the APP ID in manifest File.
  • Facebook App canvas Error for not adding key hash mismatch.
  • Facebook App canvas Error for App in development mode(switch to Production mode)
  • Null pointer Exception for not initializing Facebook SDK before setcontentView method.
However if you didnt find any error if you come across,comment below lets discuss it and resolve and make this post more usable.

My Screenshot : 



For hugs/bugs/errors/help/suggestions just comment below or mail me to [email protected] or chat with me in Facebook/G+ or tweet me in twitter.Share is care.