Social Network Ingeration in Android

Blog Single

According to android applications; There is a huge demand of social network application integrations for establishing an interaction with social communities and friends. like google, facebook, twitter, linkedin, instagram and etc., We can make use of these social application's credentials for both login and sharing the contents of our developed android application

Here, I have briefed my experience of learning with the following.
  • Facebook login & share
  • Accessing Facebook graph API
  • Google Maps & navigation
  • Twitter login & tweets

According to ANDROID Development strategies, if there is a need of using third-party API or Libraries then we need to do the first thing as specifing that specific API or Library to the gradle settings.

Facebook Login and Share

Facebook Login

Add FACEBOOK’s latest SDK on build.gradle(Module: app) under dependencies
compile 'com.facebook.android:facebook-android-sdk:4.7.0'
Initialize the facebook SDK on onCreate() method of MainActivity’s java class
FacebookSdk.sdkInitialize(getApplicationContext());

//Note: This has to be done before setContentView(R.layout.activity_main);
Set CallbackManager on onCreate()
CallbackManager callbackManager = CallbackManager.Factory.create();

//Note: we need to override onAcitivityResult() method by calling
callbackManager.onActivityResult(requestCode, resultCode, data);
If we forget to override this method then we can’t able to achieve the onSuccess,onCancel methods.
                                    
Add login button of facebook on xml layout by adding this
<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"
    android:layout_centerInParent="true"/>
Instantiate the login button by adding this
LoginButton loginButton = (LoginButton) findViewById(R.id.login_button);
//loginButton.setReadPermissions("user_friends");

loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    @Override
    public void onSuccess(LoginResult loginResult) {
        String atValue= loginResult.getAccessToken().getToken();
        Log.e("Access Token Value:",atValue);

        Intent i = new Intent(MainActivity.this, ToActivity.class);
        startActivity(i);

        finish();
    }

    @Override
    public void onCancel() {

    }

    @Override
    public void onError(FacebookException e) {

    }
});
									

Facebook Share

To implement the CallbackManager to ShareActivity’s java class(User-defined) by adding this on onCreate() method
CallbackManager callbackManager = CallbackManager.Factory.create();
Add login button of facebook on xml layout by adding this
<com.facebook.share.widget.ShareButton
    android:id="@+id/shareButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="5dp"
    android:layout_gravity="center"/>
                                    
Add this functional logic to your action/event listener like button click/press
ShareDialog shareDialog = new ShareDialog(this);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
    @Override
    public void onSuccess(Sharer.Result result) {

    }
    @Override
    public void onCancel() {

    }
    @Override
    public void onError(FacebookException e) {

   }
});                                 
Create the share dialog with your own properties
if (shareDialog.canShow(ShareLinkContent.class)) {
    ShareLinkContent content = new ShareLinkContent.Builder()
            .setContentTitle(“Your (App) Title")
            .setContentDescription(“Your (App) Description")
            .setContentUrl(Uri.parse("https://www.yourapplink.com"))
            .build();
    shareDialog.show(content);
}
ShareButton shareButton = (ShareButton) findViewById(R.id.shareButton);
shareButton.setShareContent(content);

Accessing Facebook's GRAPH API

To access the fb graph api we need to get the current Access Token; we can achieve this thing by
AccessToken accessToken = AccessToken.getCurrentAccessToken();

Here, for instance I’m going to get my friends information according to who are all using this app

if (accessToken != null) {
    GraphRequest request = GraphRequest.newMeRequest(accessToken,
            new GraphRequest.GraphJSONObjectCallback() {
                @Override
                public void onCompleted(JSONObject object, GraphResponse response) {
                    Log.e("Graph Datas", String.valueOf(response));
                    try {
                        JSONObject f_obj = new JSONObject(response.getRawResponse());
                        JSONObject friendObj = f_obj.getJSONObject("friends");
                        String friends = f_obj.getString("friends");
                        JSONArray dataArr = friendObj.getJSONArray("data");
                        for (int i = 0; i < dataArr.length(); i++) {
                            JSONObject dataObj = dataArr.getJSONObject(i);
                            String friendName = null, friendID = null;
                            ArrayList<HashMap<String, String>> f_list = new ArrayList<HashMap<String,String>>();
                            if (dataObj.has("name")) {
                                friendName = dataObj.optString("name");
                            }
                            if (dataObj.has("id")) {
                                friendID = dataObj.optString("id");
                            }
		}
                        JSONObject s_obj = friendObj.getJSONObject("summary");
                        String count = s_obj.getString("total_count");
                        String id = f_obj.getString("id");
		} catch (JSONException e) {
                        Log.e("onCompleted", e.toString());
                    }
                }
            });
    Bundle parameters = new Bundle();
    parameters.putString("fields", "id,name,friends");
    request.setParameters(parameters);
    request.executeAsync();

Twitter Login and Tweets

First thing is registering on fabric then have to create one app.Next, We need to add the Twitter’s latest SDK on gradle settings

Goto build.gradle(Module:app) under dependencies add this
compile('com.twitter.sdk.android:twitter:1.10.0@aar') {
    transitive = true;
}
Add this plugins at the top
apply plugin: 'io.fabric'
apply plugin: 'com.google.gms.google-services'
                             
Add this maven() under repositories
repositories {
    maven { url 'https://maven.fabric.io/public' }
}                           
Go to twitter developer site(fabric) and copy your (app) Twitter_key and Twitter_secret (keys) from which you have been created. And paste it on static String variables for future reference
// Note: Your consumer key and secret should be obfuscated in your source code before shipping.
private static final String TWITTER_KEY = “your twitter key";
private static final String TWITTER_SECRET = “your twitter secret";
Add twitter button to your xml layout
<com.twitter.sdk.android.core.identity.TwitterLoginButton
    android:id="@+id/login_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center" />
Configure the twitter app(which is created on fabric) on onCreate() method
TwitterAuthConfig authConfig = new TwitterAuthConfig(TWITTER_KEY, TWITTER_SECRET);
Fabric.with(this, new Twitter(authConfig));

NOTE: This  has to be done before setContentView(R.layout.activity_main);
                             
Initialize the login button of twitter on onCreate() method
TwitterLoginButton  loginButton = (TwitterLoginButton) findViewById(R.id.login_button);
Setting Callback to loginbutton
loginButton.setCallback(new Callback<TwitterSession>() {
    @Override
    public void success(Result<TwitterSession> result) {

        //TwitterSession session = Twitter.getSessionManager().getActiveSession();
        TwitterSession session = result.data;
        TwitterAuthToken authToken = session.getAuthToken();
        String token = authToken.token;
        String secret = authToken.secret;

        Intent i = new Intent(MainActivity.this, ToActivity.class);
        startActivity(i);

        finish();

        Log.e("SUCCESS", "Success");
    }

    @Override
    public void failure(TwitterException e) {
        Log.e("FAILURE", "Failure");
    }
});

Twitter Tweets

Add latest SDK for tweet-composer on gradle settings under dependencies
compile('com.twitter.sdk.android:tweet-composer:1.0.1@aar') {
    transitive = true;
}
                        
Build the TweetComposer on onCreate() method
TweetComposer.Builder builder = new TweetComposer.Builder(this).text(“App Description/Message...");
        //.image(myImageUri);
builder.show();

Share this post:

Posted by Abdul Gaffar

He is an enthusiastic android engineer at Arivista Digital, his area of expertise is Core Java, Sqlite, Realm, noSQL concepts and json and his area of specialization is very eager to newer technologies.