Showing posts with label Social integration. Show all posts
Showing posts with label Social integration. Show all posts

Thursday, December 08, 2016

Linkedin Integration, Login with Linkedin

Linkedin Integration - To provide the one click signup and signin process in the application, Android developers provide the login with social sites facilities like- facebook, twitter, linkedin, g+ etc. This tutorial guide you for Linkedin one click signup and signin process.



Steps to use recycle view in your project.
  1. Crate a project in android studio.
  2. First download linkedin sdk(Download SDK)  and import as a module in your project.

  3. Open build.gradle(app) and add some dependency

    //______add linkedin-sdk as a dependency
    compile project(':linkedin-sdk')
    
    //______add picaso dependency for image loding
    compile 'com.squareup.picasso:picasso:2.5.2'
    
      
  4.  Click on "Sync Now"
  5. Open your main_activity.xml and update it-

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        tools:context="com.pankaj.linkedindemo.MainActivity">
    
        <!--to show user image-->
        <ImageView
            android:id="@+id/ivUser"
            android:layout_width="180dp"
            android:layout_height="180dp"
            android:layout_margin="5dp"
            android:src="@drawable/ic_launcher" />
    
        <!--to show user name-->
        <TextView
            android:id="@+id/tvName"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Point of Android" />
    
        <!--to show user email-->
        <TextView
            android:id="@+id/tvMail"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="e@mail.com" />
    
        <!--for login with linkedin-->
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="login"
            android:text="Login with linkedin" />
    
        <!--for generate keyhash-->
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="generateHashkey"
            android:text="Genrate KeyHash" />
    
        <!--to show package name-->
        <TextView
            android:id="@+id/tvPackage"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="package" />
    
        <!--to show keyhash-->
        <TextView
            android:id="@+id/tvKeyHash"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:text="Keyhash" />
    </LinearLayout>
    
    
    
     
  6. Open your MainActivity.JAVA class and update it -
    package com.pankaj.linkedindemo;
    
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.Signature;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Base64;
    import android.util.Log;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    import android.widget.Toast;
    import com.linkedin.platform.APIHelper;
    import com.linkedin.platform.LISessionManager;
    import com.linkedin.platform.errors.LIApiError;
    import com.linkedin.platform.errors.LIAuthError;
    import com.linkedin.platform.listeners.ApiListener;
    import com.linkedin.platform.listeners.ApiResponse;
    import com.linkedin.platform.listeners.AuthListener;
    import com.linkedin.platform.utils.Scope;
    import com.squareup.picasso.Picasso;
    import org.json.JSONObject;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    
    public class MainActivity extends AppCompatActivity {
    
        //__________create objects
        private TextView tvName, tvMail, tvPackage, tvKeyHash;
        private ImageView ivUser;
    
        private final String TAG = MainActivity.class.getSimpleName();
        private final String PACKAGE = "com.pankaj.linkedindemo";
        private final String host = "api.linkedin.com";
        private final String topCardUrl = "https://" + host + "/v1/people/~:(email-address,formatted-name,phone-numbers,public-profile-url,picture-url,picture-urls::(original))";
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            //___________initialization
            tvName = (TextView) findViewById(R.id.tvName);
            tvMail = (TextView) findViewById(R.id.tvMail);
            tvPackage = (TextView) findViewById(R.id.tvPackage);
            tvKeyHash = (TextView) findViewById(R.id.tvKeyHash);
            ivUser = (ImageView) findViewById(R.id.ivUser);
    
        }
    
        //____________methode will be call when click on login with linkedin
        public void login(View view) {
    
            //____________authentication request
            LISessionManager.getInstance(getApplicationContext()).init(this, buildScope(), new AuthListener() {
    
                @Override
                public void onAuthSuccess() {
                }
    
                @Override
                public void onAuthError(LIAuthError error) {
                    Toast.makeText(getApplicationContext(), "failed " + error.toString(), Toast.LENGTH_LONG).show();
                }
            }, true);
        }
    
        //_________create scope to get permission for access data from linkedin.
        private static Scope buildScope() {
            return Scope.build(Scope.R_BASICPROFILE, Scope.R_EMAILADDRESS);
        }
    
        //___________After complete authentication start new HomePage Activity
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
            getUserData();
        }
    
        //___________get data from linked in server
        private void getUserData() {
    
            //_______add request to get data
            APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
            apiHelper.getRequest(this, topCardUrl, new ApiListener() {
    
                @Override
                public void onApiSuccess(ApiResponse result) {
    
                    //_________set captured data on screen
                    setUserProfile(result.getResponseDataAsJson());
                }
    
                @Override
                public void onApiError(LIApiError error) {
                    error.printStackTrace();
                }
            });
        }
    
        //___________set data to the screen
        public void setUserProfile(JSONObject response) {
    
            try {
    
                Log.e("linkedin response", response.toString());
    
                //__set email address
                tvMail.setText(response.get("emailAddress").toString());
    
                //__set Name
                tvName.setText(response.get("formattedName").toString());
    
                //parce emage address
                String imageUrl = (String) response.getJSONObject("pictureUrls").getJSONArray("values").get(0);
    
                //_________load profile image image
                Picasso.with(this).load(imageUrl).into(ivUser);
    
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
        //______________genrate hashkey
        public void generateHashkey(View view) {
    
            try {
    
                PackageInfo info = getPackageManager().getPackageInfo(PACKAGE, PackageManager.GET_SIGNATURES);
    
                for (Signature signature : info.signatures) {
                    MessageDigest md = MessageDigest.getInstance("SHA");
                    md.update(signature.toByteArray());
    
                    //___________set package name
                    tvPackage.setText(PACKAGE);
    
                    //___________set keyhash
                    tvKeyHash.setText(Base64.encodeToString(md.digest(), Base64.NO_WRAP));
    
                    //___________add package name and key hash into log
                    Log.e(TAG, "_____________________________________________");
                    Log.e("Package", PACKAGE);
                    Log.e("KeyHash", tvKeyHash.getText().toString());
                    Log.e(TAG, "_____________________________________________");
                    Toast.makeText(this, "Check your logcate for keyhash", Toast.LENGTH_SHORT).show();
    
                }
            } catch (PackageManager.NameNotFoundException e) {
                Log.d(TAG, e.getMessage(), e);
            } catch (NoSuchAlgorithmException e) {
                Log.d(TAG, e.getMessage(), e);
            }
        }
    }
    
    

     
  7. Now all the development steps for linkedin integration has completed, Please run the application and see the screen of device.




  8. Now add an application on linkedin developer console(Linkedin Developer Console).

    click on Create application
  9. fill all the information required to create the app and submit it.

  10. Look at the "Default Application Permissions". check the required permission box.

  11. Click on update.
  12. Select mobile from the left menu.

  13. Look on the "Android Settings" add package name and package Key Hash

  14. For package name and key has check your logcate.


     
  15. Click on update.

  16. Now go to the mobile application and click on "Login with Linkedin" and you will see the permission screen, then click on "OK".
  17. You can see the logedin user data(name,email and  image)  on you screen
  18. Good bye, Thanks to read this blog.



Wednesday, December 07, 2016

Facebook Integration


Facebook Integration - To provide the one click signup and signin process in the application, Android developers provide the login with social sites facilities like- facebook, twitter, linkedin, g+ etc. This tutorial guide you for facebook one click signup and signin process.




Steps to use login with facebook in your project.
  1. Crate a project in android studio.
  2. Open build.gradle(project) and add a repositories

    repositories {
        mavenCentral()
    }
    
      
  3. Open build.gradle(app) and add a dependency

    compile 'com.facebook.android:facebook-android-sdk:[4,5)'
    
     
  4.  Click on Sync Now.
  5.  Now create an application on facebook developer console (Create Facebook application on developer consol).

  6. If you are on quick start then skip (6,7,8) steps else follow this-
    1. Select setting from left menu menu.


  7.  Now scroll down the page and add android platform.

  8.  A popup will be open then you select the android as a platform.

  9.  A popup will be shown, Then you select the android as a platform.
  10. fill package name and first activity
  11.  Now copy keyhash from logcat and fill here

  12. Now this setup has finished
  13. Select app review and click on make "Your $App_Name public?"
  14. Now check your application status on the dashboard. Green circle shows that your application is ready to integrate.
  15. Copy "App ID" and open your string.xml and add a string for facebook application id -

     <string name="facebook_app_id">1460300553984844</string> 

  16. Open your main_activity.xml and update it-
    <?xml version="1.0" encoding="utf-8"?>
    
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:id="@+id/activity_main"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center"
        android:orientation="vertical"
        android:padding="10dp"
        tools:context="com.pankaj.fb.integration.demo.MainActivity">
    
        <!--Profile Pic-->
        <com.facebook.login.widget.ProfilePictureView
            android:id="@+id/ppview"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="30dp"
            android:layout_marginTop="30dp" />
    
        <!--Login Button-->
        <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_marginBottom="30dp"
            android:layout_marginTop="30dp" />
    
    </LinearLayout>
    
     
  17. Open manifest and update it-

    <?xml version="1.0" encoding="utf-8"?>
    
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.pankaj.fb.integration.demo">
    
        <!--add permission-->
        <uses-permission android:name="android.permission.INTERNET" />
    
        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
    
            <!--activity-->
            <activity android:name="com.pankaj.fb.integration.demo.MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
    
            <!--add meta data-->
            <meta-data
                android:name="com.facebook.sdk.ApplicationId"
                android:value="@string/facebook_app_id" />
    
        </application>
    </manifest>
    
    
    
     
  18. Open your MainActivity.JAVA class and update it -

    package com.pankaj.fb.integration.demo;
    import android.content.Intent;
    import android.content.pm.PackageInfo;
    import android.content.pm.PackageManager;
    import android.content.pm.Signature;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.Base64;
    import android.util.Log;
    import android.widget.Toast;
    import com.facebook.AccessToken;
    import com.facebook.CallbackManager;
    import com.facebook.FacebookCallback;
    import com.facebook.FacebookException;
    import com.facebook.FacebookSdk;
    import com.facebook.GraphRequest;
    import com.facebook.GraphResponse;
    import com.facebook.appevents.AppEventsLogger;
    import com.facebook.login.LoginResult;
    import com.facebook.login.widget.LoginButton;
    import com.facebook.login.widget.ProfilePictureView;
    import org.json.JSONException;
    import org.json.JSONObject;
    import java.security.MessageDigest;
    import java.security.NoSuchAlgorithmException;
    import java.util.HashMap;
    /*
    *
    * https://developers.facebook.com/apps/
    *
    * */
    public class MainActivity extends AppCompatActivity {
    
        //create objects
        private LoginButton loginButton;
        private CallbackManager callbackManager;
        private ProfilePictureView ppview;
        private HashMap<String, String> userData;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            genrateKeyHash();
    
            //__________initialize facebook sdk
            FacebookSdk.sdkInitialize(getApplicationContext());
    
            //__________Activate application logger
            AppEventsLogger.activateApp(this);
    
            //__________set main activity view
            setContentView(R.layout.activity_main);
    
            //__________initialize objects
            loginButton = (LoginButton) findViewById(R.id.login_button);
            ppview = (ProfilePictureView) findViewById(R.id.ppview);
            callbackManager = CallbackManager.Factory.create();
    
            //__________set permission for access required data
            loginButton.setReadPermissions("email,public_profile");
    
            //__________check for already login
            if (AccessToken.getCurrentAccessToken() != null) {
                //__________set image if already login
                ppview.setProfileId(AccessToken.getCurrentAccessToken().getUserId());
            }
            fbLogin();
        }
    
        public void fbLogin() {
    
            //__________Callback login
            loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
    
                @Override
                public void onSuccess(LoginResult loginResult) {
                    //__________user image url
                    final String image = "https://graph.facebook.com/" + AccessToken.getCurrentAccessToken().getUserId() + "/picture?type=large&width=720&height=720";
    
                    //__________Create a graph request
                    GraphRequest request = GraphRequest.newMeRequest(
                            AccessToken.getCurrentAccessToken(),
                            new GraphRequest.GraphJSONObjectCallback() {
    
                                @Override
                                public void onCompleted(
                                        JSONObject object,
                                        GraphResponse response) {
    
                                    //__________process this data
                                    Log.e("response", response.toString());
                                    Log.e("object", object.toString());
                                    Log.e("image", image);
                                    try {
    
                                        //_______put data into user data map
                                        userData = new HashMap<String, String>();
                                        userData.put("id", object.get("id").toString());
                                        userData.put("email", object.get("email").toString());
                                        userData.put("name", object.get("name").toString());
    
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
    
                                    //__________set user image
                                    ppview.setProfileId(AccessToken.getCurrentAccessToken().getUserId());
    
                                    //___________show the detail in toast message
                                    Toast.makeText(MainActivity.this, "Name : " + userData.get("name") + "\nEmail : " + userData.get("email") + "\nID : " + userData.get("id"), Toast.LENGTH_SHORT).show();
                                }
                            });
    
                    //__________add parameters for required data
                    Bundle parameters = new Bundle();
                    parameters.putString("fields", "id,name,email");
                    request.setParameters(parameters);
    
                    //__________eqecute request
                    request.executeAsync();
                }
    
                @Override
                public void onCancel() {
                    // App code
                }
    
                @Override
                public void onError(FacebookException exception) {
                    // App code
                }
            });
        }
    
        //____________genrate key has
        private void genrateKeyHash() {
            try {
                PackageInfo info = getPackageManager().getPackageInfo("com.pankaj.fb.integration.demo", 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 (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
        }
    
        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            callbackManager.onActivityResult(requestCode, resultCode, data);
        }
    }
    
    
    



  19. Now all the development steps for Login with facebook has completed, Please run the application and see the screen of device.



  20. Now click on "Login with facebook" and see the screen - 


    Fill the credential

  21. Now yow will see a screen to got permission click on "Continue" and see the screen - 




  22. Now see the logcate section-




  23. Finally login with facebook has completed and you got data(id,name,email and profile picture), please see the screen-







  24. Good bye, Thanks to read this blog.