This tutorial explains how to integrate LinkedIn integration and login in an Android Application example.

 
 

Creating account in LinkedIn Developer

To integrate LinkedIn with your mobile application, we need to create an new application in LinkedIn Developer’s Account. Go to https://www.linkedin.com/developer/apps and click on the Create Application button and a form will open that need to be filled to successfully create application on LinkedIn.

 

linkedIn developer
 






Set the Permission

We need to set the permission to get the access to retrieve the user’s LinkedIn profile details. We need to select the r_basicprofile and r_emailaddress and click on the update button to set the permission.

 

set the linkedin permission

 

Creating a new project

We need to create a new project in android studio.

 

Set the Internet Permission

We will call the LinkedIn Api through internet. So we need to add the Internet permission in your Android Application.

 

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

 

Download & add Mobile LinkedIn SDK

Download the Mobile LinkedIn SDK from https://developer.linkedin.com/downloads#androidsdk. Unzip the downloaded file and add the linkedin-sdk directory in your project. linkedin-sdk already exist in the unziped directory.

 

Include linked-sdk library in the setting.gradle file

Open setting.gradle file in your project and include linked-sdk directory in your project.

include ':app', ':linkedin-sdk'

 

linkedin-sdk
 

Adding support library in dependencies

To compile LinkedIn SDK, add the sdk in the dependencies. Open your build.gradle(app module) file and add linkedin-sdk in the dependencies. Also add the Picasso library to display Image.

compile project(':linkedin-sdk')
compile 'com.squareup.picasso:picasso:2.5.2'

 

Create Hash Key Layout

To integrate linkedin with Android App, we will generate hash key to integrate your app with linkedin account by adding the hash key into application that is created on LinkedIn Developer Account. To display hash key, we use TextView. So add the TextView in the activity_main.xml file.

<TextView 
      android:id="@+id/hashKey" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:textSize="20dp"/>

 

Generate Hash Key

Generate the has key to integrate your app with LinkedIn Developer Account. Use the following code to generate hash key:

 

public class MainActivity extends AppCompatActivity {
    //replace package string with your package string
    public static final String PACKAGE = "Your Package";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        generateHashkey();
    }
  
    public void generateHashkey(){
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    PACKAGE,
                    PackageManager.GET_SIGNATURES);
            for (Signature signature : info.signatures) {
                MessageDigest md = MessageDigest.getInstance("SHA");
                md.update(signature.toByteArray());

                ((TextView) findViewById(R.id.hashKey))
                            .setText(Base64.encodeToString(md.digest(),
                            Base64.NO_WRAP));
            }
        } catch (PackageManager.NameNotFoundException e) {
            Log.d("Name not found", e.getMessage(), e);

        } catch (NoSuchAlgorithmException e) {
            Log.d("Error", e.getMessage(), e);
        }
    }
}

 

Add hash key in LinkedIn Developer Account

We will add the hash key in LinkedIn Developer account. Goto https://www.linkedin.com/developer/apps and click on your application name and select mobile tab. Add the Package name and hash key in the Android Setting. It will integrate your app with LinkedIn Developer Application.

linkedin has key
 

Create Layout

Once, we add the hash key in the LinkedIn Developer account. Do not need of generateHashkey() method in MainActivity. Now, we implement login process on click the button. So, we need to add the button in the activity_main.xml file.

 

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.linkedinintegration.MainActivity">

   <TextView
        android:id="@+id/linkedtext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Click on the button to ligin"
        android:textSize="20dp"
        android:onClick="login"
        android:layout_marginBottom="20dp"/>

    <Button
        android:layout_below="@+id/linkedtext"
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/signin"
        android:onClick="login"
        android:layout_marginBottom="15dp"/>
</RelativeLayout>

 

login_linkedin

 

Add the LinkedIn App Permission

To retrieve the User’s information, need to set the R_BASICPROFILE and R_EMAILADDRESS permission through scope argument. We request the permission during authentication process. Use the following code in MainActivity file.

 

public class MainActivity extends AppCompatActivity {
    //replace package string with your package string
    public static final String PACKAGE ="your Pacakge";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // set the permission to retrieve basic 
                 information of User's linkedIn account
    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.R_EMAILADDRESS);
    }
}

 

Create Login Process

The LISessionManager provides all necessary object to create and manage LISession object used to perform the additional Mobile SDK functions.

We create a LISessionManager object and pass the context, scope(list of member permission), callback method and a boolean value that determines the behaviour when the LinkedIn app is not installed.

 

public class MainActivity extends AppCompatActivity {
    //replace package string with your package string
    public static final String PACKAGE = "Your Package";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // Authenticate with linkedin and intialize Session.

    public void login(View view){
        LISessionManager.getInstance(getApplicationContext())
                        .init(this, buildScope(), new AuthListener() {
            @Override
            public void onAuthSuccess() {

                 Toast.makeText(getApplicationContext(), "success" +   
                                    LISessionManager
                                    .getInstance(getApplicationContext())
                                    .getSession().getAccessToken().toString(),
                                     Toast.LENGTH_LONG).show();

            }

            @Override
            public void onAuthError(LIAuthError error) {

                Toast.makeText(getApplicationContext(), "failed " 
                    + error.toString(),
                        Toast.LENGTH_LONG).show();
            }
        }, true);
    }

    // set the permission to retrieve basic information of User's linkedIn account
    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, Scope.R_EMAILADDRESS);
    }
}

 

Handle responses from the LinkedIn Android app

You need to handle response result by calling LISessionManager’s implementation of onActivityResult() from within the calling activity’s onActivityResult() method. Here is the final code of MainActivity class:

 

public class MainActivity extends AppCompatActivity {
    //replace package string with your package string
    public static final String PACKAGE = "your Package";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // Authenticate with linkedin and intialize Session.
    public void login(View view){
        LISessionManager.getInstance(getApplicationContext())
                        .init(this, buildScope(), new AuthListener() {
            @Override
            public void onAuthSuccess() {

                 Toast.makeText(getApplicationContext(), "success" + 
                 LISessionManager.getInstance(getApplicationContext())
                 .getSession().getAccessToken().toString(),
                 Toast.LENGTH_LONG).show();
            }

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

   // handle the respone by calling LISessionManager and start new activity
    @Override
    protected void onActivityResult(int requestCode, 
              int resultCode, Intent data) {

        LISessionManager.getInstance(getApplicationContext())
                        .onActivityResult(this,
                        requestCode, resultCode, data);

        Intent intent = new Intent(MainActivity.this, HomePage.class);
        startActivity(intent);
    }

    // set the permission to retrieve basic -
    //information of User's linkedIn account
    private static Scope buildScope() {
        return Scope.build(Scope.R_BASICPROFILE, 
                           Scope.R_EMAILADDRESS);
    }
}

 

Create a new Activity

We display user’s image, name and email address in another activity. So we create a new activity called HomePage.

Create HomePage Layout

We use ImageView and TextView to display profile picture, name and email address. So, add the TextView and ImageView in the activity_home_page.xml file.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.linkedinintegration.HomePage">

    <ImageView 
       android:id="@+id/profile_picture" 
       android:layout_width="80dp" 
       android:layout_height="80dp" />

    <TextView android:id="@+id/name" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:textSize="20dp" 
        android:layout_marginLeft="20dp" 
        android:layout_toRightOf="@+id/profile_picture"/>

    <TextView android:id="@+id/email" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:layout_below="@id/name" 
        android:layout_marginLeft="20dp" 
        android:layout_toRightOf="@+id/profile_picture"/>


</RelativeLayout>

 

Create APIHelper object

Once you have established a LISession or mobile users have authenticated, need to create APIHelper object to retrieve their basic profile data. Final HomePage class is given below:

public class HomePage extends AppCompatActivity {
    private static final String host = "api.linkedin.com";
    private static final String url = "https://" + host
           + "/v1/people/~:" +
           "(email-address,formatted-name,phone-numbers,
            picture-urls::(original))";

    private ProgressDialog progress;
    private TextView user_name, user_email;
    private ImageView profile_picture;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_page);
        // Initialize the progressbar
        progress= new ProgressDialog(this);
        progress.setMessage("Retrieve data...");
        progress.setCanceledOnTouchOutside(false);
        progress.show();

        user_email = (TextView) findViewById(R.id.email);
        user_name = (TextView) findViewById(R.id.name);
        profile_picture = (ImageView) findViewById(R.id.profile_picture);

        linkededinApiHelper();

    }

    public void linkededinApiHelper(){
        APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
        apiHelper.getRequest(HomePage.this, url, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse result) {
                try {
                    showResult(result.getResponseDataAsJson());
                    progress.dismiss();

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onApiError(LIApiError error) {
                
            }
        });
    }

    public  void  showResult(JSONObject response){

        try {
            user_email.setText(response.get("emailAddress").toString());
            user_name.setText(response.get("formattedName").toString());

            Picasso.with(this).load(response.getString("pictureUrl"))
                    .into(profile_picture);

        } catch (Exception e){
            e.printStackTrace();
        }
    }
}

 

login-linkedin

 
linked-profile







  • Npt Npt

    Hello. Nice tutorial! Importing the source code , doesn t resolve the hash key ( R.id.hashKey). do i have to make any special configuration?

    • abhayanand1910

      Generate Hash key and add into your Linkedin Developer Account

  • Mahmudur Rahman

    Image does not show, but other information is shown well ….. by the way….. when I put a log for key hash and run into a device, the device text view and the log shown different key hash. For me device key has work well. And overall your post is rockz.

    • abhayanand1910

      You are doing something wrong, hash key always same for a single device

      • Mahmudur Rahman

        ((TextView) findViewById(R.id.hashKey)).setText(Base64.encodeToString(md.digest(),Base64.NO_WRAP));
        Log.d(“LOG_KEY”, Base64.encodeToString(md.digest(), Base64.NO_WRAP)); —– Use those line of code and see what is different. In my case, given different key hash.

      • Nikhil Mane

        As per the Package change the Hash Key will Change so for those project you need for that project first you make the Hash key and store this with package at the Linkedin Developer Console

  • Rohan Lodhi

    LISessionManager object is not Available …..

  • Sanket Shah

    Thanks for the nice instructions! I just wanted to know is there any way we can use webview for authentication? Because when I click on login button it asks to download the LinkedIn app from Google Play. Because not every user like to download LinkedIn app I would like to know if there is any way to do it using WebView?

    • You need to install LinkedIn App for this