Integrate linkedin login in android application

Posted By : Keshav Gupta | 29-Oct-2017

Configuration to be done on server side :

1.Create a application on developer.linkedin.com.

2. Edit all the field and generate clientId and secret key.

3.Now you are all done on server side.

Integration to be done in application:

1.Download mobile sdk for linkedin from console.

2.Integrate sdk in application as library module.

Code in java file:

1.We will create a separate controller class for linkedin login which will be named as "LinkedinController" and will declare all keyname,topcardurl and hostname.Code will be like this:

    Context context;
    // linkedin JSON key
    public static final String KEY_LINKED_IN_STATUS_CODE ="StatusCode";
    public static final String KEY_LINKED_IN_RESPONSE_DATA="responseData";
    public static final String KEY_LINKED_IN_EMAIL_ID ="emailAddress";
    public static final String KEY_LINKED_IN_FIRST_NAME ="firstName";
    public static final String KEY_LINKED_IN_LAST_NAME ="lastName";
    public static final String KEY_LINKED_IN_PROFILE_URL="pictureUrl";
    public static final String KEY_LINKED_IN_LOCATION ="location";
    private String email="",urlPath="",firstname="",lastname="",location_name="";
    private String linkedInAccessToken ="";
    private static final String host = "api.linkedin.com";
    private static final String topCardUrl = "https://" + host + "/v1/people/~:(first-name,last-name,picture-url,email-address,location)";

2.Instantiate class using default constructor and declare a method "loginWithLinkedin".Code wll be like this

public LinkedInController(Context con)
    {
        context = con;
        loginWithLinkedIn();
    }

    public void loginWithLinkedIn()
    {
        LISessionManager.getInstance(context).init((Activity) context, buildScope(), this, true);
        printKeyHash((Activity) context);
    }

3.Furthermore this class will implement AuthListener which will override method onAuthSuccess() and onAuthError().Code snippet will be like this.

@Override
    public void onAuthSuccess() {

        linkedInAccessToken = LISessionManager.getInstance(context).getSession().getAccessToken().toString();
        APIHelper apiHelper = APIHelper.getInstance(context);

        apiHelper.getRequest(context, topCardUrl, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse s) {
                Log.e(" server response comes", s.getResponseDataAsJson().toString());
                try {
                    JSONObject obj = s.getResponseDataAsJson();
                    if (obj.has(KEY_LINKED_IN_EMAIL_ID)) {
                        email = obj.optString(KEY_LINKED_IN_EMAIL_ID);
                    }
                    if (obj.has(KEY_LINKED_IN_PROFILE_URL)) {
                        urlPath = obj.optString(KEY_LINKED_IN_PROFILE_URL);
                    }
                    if (obj.has(KEY_LINKED_IN_FIRST_NAME)) {
                        firstname = obj.optString(KEY_LINKED_IN_FIRST_NAME);
                    }
                    if (obj.has(KEY_LINKED_IN_LAST_NAME)) {
                        lastname = obj.optString(KEY_LINKED_IN_LAST_NAME);
                    }
                    JSONObject location_obj=obj.optJSONObject(KEY_LINKED_IN_LOCATION);
                    if(location_obj!=null)
                    {
                       location_name=location_obj.optString("name");
                    }

                    Log.e("First", firstname);
                    Log.e("last", lastname);
                    Log.e("email",email);
                    Log.e("path",urlPath);
                    new JsonUserLinkedInLogin().execute(new String[]{firstname,lastname,email,urlPath,location_name});
                } catch (Exception e) {
                    //  Debug.printLog(" problem comes to parse json "+e);
                }
            }

            @Override
            public void onApiError(LIApiError error) {

            
             }
        });
    }

    @Override
    public void onAuthError(LIAuthError error) {
//        Toast.makeText(context, "failed " + error.toString(), Toast.LENGTH_LONG).show();
       Toast.makeText(context,"failed", Toast.LENGTH_LONG).show();
    }

4. In onAuthError() method user can print any error message. 

5. In onAuthSuccess() method first we will be getting linkedinaccesstoken and using Apihelper  we will be getting profile in onApiSuccess() method. Code snippet will be like this.

@Override
    public void onAuthSuccess() {

        linkedInAccessToken = LISessionManager.getInstance(context).getSession().getAccessToken().toString();
        APIHelper apiHelper = APIHelper.getInstance(context);

        apiHelper.getRequest(context, topCardUrl, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse s) {
                Log.e(" server response comes", s.getResponseDataAsJson().toString());
                try {
                    JSONObject obj = s.getResponseDataAsJson();
                    if (obj.has(KEY_LINKED_IN_EMAIL_ID)) {
                        email = obj.optString(KEY_LINKED_IN_EMAIL_ID);
                    }
                    if (obj.has(KEY_LINKED_IN_PROFILE_URL)) {
                        urlPath = obj.optString(KEY_LINKED_IN_PROFILE_URL);
                    }
                    if (obj.has(KEY_LINKED_IN_FIRST_NAME)) {
                        firstname = obj.optString(KEY_LINKED_IN_FIRST_NAME);
                    }
                    if (obj.has(KEY_LINKED_IN_LAST_NAME)) {
                        lastname = obj.optString(KEY_LINKED_IN_LAST_NAME);
                    }
                    JSONObject location_obj=obj.optJSONObject(KEY_LINKED_IN_LOCATION);
                    if(location_obj!=null)
                    {
                       location_name=location_obj.optString("name");
                    }

                    Log.e("First", firstname);
                    Log.e("last", lastname);
                    Log.e("email",email);
                    Log.e("path",urlPath);
                    new JsonUserLinkedInLogin().execute(new String[]{firstname,lastname,email,urlPath,location_name});
                } catch (Exception e) {
                    //  Debug.printLog(" problem comes to parse json "+e);
                }
            }

            @Override
            public void onApiError(LIApiError error) {

                //Debug.printLog(" server response comes  for error "+error.toString());
            }
        });
    }

    @Override
    public void onAuthError(LIAuthError error) {
//        Toast.makeText(context, "failed " + error.toString(), Toast.LENGTH_LONG).show();
       Toast.makeText(context,"failed", Toast.LENGTH_LONG).show();
    }

6.One more method buildScope() will be there.Code snippet will be like this:

private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE,Scope.R_EMAILADDRESS);
    }

7.Final code will be like

public class LinkedInController1 implements AuthListener
{
    Context context;
    // linkedin JSON key
    public static final String KEY_LINKED_IN_STATUS_CODE ="StatusCode";
    public static final String KEY_LINKED_IN_RESPONSE_DATA="responseData";
    public static final String KEY_LINKED_IN_EMAIL_ID ="emailAddress";
    public static final String KEY_LINKED_IN_FIRST_NAME ="firstName";
    public static final String KEY_LINKED_IN_LAST_NAME ="lastName";
    public static final String KEY_LINKED_IN_PROFILE_URL="pictureUrl";
    public static final String KEY_LINKED_IN_LOCATION ="location";
    private String email="",urlPath="",firstname="",lastname="",location_name="";
    private String linkedInAccessToken ="";
    private static final String host = "api.linkedin.com";
    private static final String topCardUrl = "https://" + host + "/v1/people/~:(first-name,last-name,picture-url,email-address,location)";
    public LinkedInController1(Context con)
    {
        context = con;
        loginWithLinkedIn();
    }

    public void loginWithLinkedIn()
    {
        LISessionManager.getInstance(context).init((Activity) context, buildScope(), this, true);
        printKeyHash((Activity) context);
    }

    @Override
    public void onAuthSuccess() {

        linkedInAccessToken = LISessionManager.getInstance(context).getSession().getAccessToken().toString();
        APIHelper apiHelper = APIHelper.getInstance(context);

        apiHelper.getRequest(context, topCardUrl, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse s) {
                Log.e(" server response comes", s.getResponseDataAsJson().toString());
                try {
                    JSONObject obj = s.getResponseDataAsJson();
                    if (obj.has(KEY_LINKED_IN_EMAIL_ID)) {
                        email = obj.optString(KEY_LINKED_IN_EMAIL_ID);
                    }
                    if (obj.has(KEY_LINKED_IN_PROFILE_URL)) {
                        urlPath = obj.optString(KEY_LINKED_IN_PROFILE_URL);
                    }
                    if (obj.has(KEY_LINKED_IN_FIRST_NAME)) {
                        firstname = obj.optString(KEY_LINKED_IN_FIRST_NAME);
                    }
                    if (obj.has(KEY_LINKED_IN_LAST_NAME)) {
                        lastname = obj.optString(KEY_LINKED_IN_LAST_NAME);
                    }
                    JSONObject location_obj=obj.optJSONObject(KEY_LINKED_IN_LOCATION);
                    if(location_obj!=null)
                    {
                       location_name=location_obj.optString("name");
                    }

                    Log.e("First", firstname);
                    Log.e("last", lastname);
                    Log.e("email",email);
                    Log.e("path",urlPath);
                    //new JsonUserLinkedInLogin().execute(new String[]{firstname,lastname,email,urlPath,location_name});
                } catch (Exception e) {
                    //  Debug.printLog(" problem comes to parse json "+e);
                }
            }

            @Override
            public void onApiError(LIApiError error) {

                //Debug.printLog(" server response comes  for error "+error.toString());
            }
        });
    }

    @Override
    public void onAuthError(LIAuthError error) {
//        Toast.makeText(context, "failed " + error.toString(), Toast.LENGTH_LONG).show();
       Toast.makeText(context,"failed", Toast.LENGTH_LONG).show();
    }
    public static String printKeyHash(Activity context) {
        PackageInfo packageInfo;
        String key = null;
        try {
            //getting application package name, as defined in manifest
            String packageName = context.getApplicationContext().getPackageName();

            //Retriving package info
            packageInfo = context.getPackageManager().getPackageInfo(packageName,
                    PackageManager.GET_SIGNATURES);

            Log.e("Package Name=", context.getApplicationContext().getPackageName());

            for (Signature signature : packageInfo.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());
                key = new String(Base64.encode(md.digest(), 0));

                // String key = new String(Base64.encodeBytes(md.digest()));
                Log.e("Key Hash=", key);
            }
        } catch (PackageManager.NameNotFoundException e1) {
            Log.e("Name not found", e1.toString());
        }
        catch (NoSuchAlgorithmException e) {
            Log.e("No such an algorithm", e.toString());
        } catch (Exception e) {
            Log.e("Exception", e.toString());
        }

        return key;
    }

   
    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.W_SHARE,Scope.R_EMAILADDRESS);
    }
}

7.Now to use this in Activity class.Code will be like this.

onButtonClick of linkedin instantiate LinkedinController class and onActivityResult 

LinkedInController linkedin= new LinkedInController(mContext);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  
     if(linkedin !=null)
   {
      linkedin.onActivityResultComesOnFragment(requestCode,resultCode,data);
   }
}

8.All Done.

About Author

Author Image
Keshav Gupta

Keshav Gupta is Android Developer in Oodles, he always look forward for new tasks and new things to learn more.

Request for Proposal

Name is required

Comment is required

Sending message..