TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

Integrating LinkedIn API in Android App

Integrating LinkedIn API in Android App with examples of Activity and Intent, Fragments, Menu, Service, alarm manager, storage, sqlite, xml, json, multimedia, speech, web service, telephony, animation and graphics

<< Back to ANDROID

Integrating LinkedIn API in Android App

In this tutorial, we will integrate the LinkedIn Sign-In functionality in our Android application. Implementing LinkedIn API in Android app helps users to login using LinkedIn account, share post, etc.

For integrating the LinkedIn API in our Android app, we need the LinkedIn Authentication Key (Client ID and Client Secret) and app Hash Key.

Steps to generate LinkedIn Authentication Key and APP Hash Key

1. Create LinkedIn developer account at https://www.linkedin.com/developer/apps and click on 'Create Application'.


android LinkedIn Integrating

2. Fill all the required details of Android application in 'Create a New Application' form and accept the LinkedIn API Terms of Use then click 'Submit'.


android LinkedIn Integrating

3. After submitting the application details, it generates LinkedIn Authentication Key. Now we will select the 'Default Application Permissions'. This permission authorizes to access privilege of user account. Here, we are selecting r_basicprofile, and 'r_emailaddress' and click 'Update'.


android LinkedIn Integrating
android LinkedIn Integrating

4. Now, we need the 'Hash Key' for our app. It can be generated by two different ways.

  • Using command on command prompt.

Windows:

keytool -exportcert -keystore %HOMEPATH%\.android\debug.keystore -alias androiddebugkey | openssl sha1 -binary | openssl base64

Mac/Unix

keytool -exportcert -keystore ~/.android/debug.keystore -alias androiddebugkey | openssl sha1 -binary | openssl base64

To generate the Hash Key through command prompt, it requires OpenSSL to be installed in our operating system. We can download it for Windows from www.slproweb.com/products/Win32OpenSSL.html and for Mac/Unix from http://www.openssl.org/source/ .

  • Using the programming code in Activity.java class.
PackageInfo info = getPackageManager().getPackageInfo(
                    "Your Package Nane",
                    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));

For this application, we will use the programming code to generate 'Hash Key' for our application.

Now create our application and simply write the following code and run to generate our 'Hash Key'. It will show the application 'Hash Key' in Logcat.

MainActivity.java

package example.com.linkedinlogindemo;

import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;

import java.security.MessageDigest;


public class MainActivity extends AppCompatActivity {
    public static final String PACKAGE = "example.com.linkedinlogindemo";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        computePakageHash();
    }

    private void computePakageHash() {
        try {
            PackageInfo info = getPackageManager().getPackageInfo(
                    "example.com.linkedinlogindemo",
                    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 (Exception e) {
            Log.e("TAG",e.getMessage());
        }
    }
}

android LinkedIn Integrating

5. Copy the 'Hash Key' from Logcat and paste it in Mobile tab of our LinkedIn application. After that click on 'Add' and 'Update'. This makes our application 'Hash Key' registered with LinkedIn API.


android LinkedIn Integrating

Example to Integrate LinkedIn Login in Android app

Let's create an example of integrating the LinkedIn log-in functionality in our Android application. After successful user log-in, it will redirect user to another activity (ProfileActivity) and display the user information.

We need to add the LinkedIn SDK for Android in our project. It can be downloaded from here https://developer.linkedin.com/downloads#androidsdk.


android LinkedIn Integrating

Required Permission

Add the Internet permission in AndroidMenifest.xml file.

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

settings.gradle

Add the linkedin-sdk in settings.gradle file.

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

build.gradle (Module)

Add the compile project(path: ':linkedin-sdk') in build.gradle file.

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
    compile project(path: ':linkedin-sdk')
}

activity_main.xml

Add the following code in activity_main.xml file. Download the recommended LinkedIn button from LinkedIn developer site https://developer.linkedin.com/downloads and add it as the background of button.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="example.com.linkedinlogindemo.MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:textSize="20dp"
        android:layout_centerHorizontal="true"
        android:text="This is Login Page" />

    <Button
        android:id="@+id/login_button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="17dp"
        android:background="@drawable/loginbutton"
        tools:layout_editor_absoluteX="58dp"
        tools:layout_editor_absoluteY="437dp" />

</RelativeLayout>

MainActivity.java

In the MainActivity.java class, we use the LISessionManager class which provides all functionality to create and manage the LISession object (LinkedIn session object). In the build, scope adds the 'Scope.R_BASICPROFILE' and 'Scope.R_EMAILADDRESS' to access user basic profile information and email address of LinkedIn.

package example.com.linkedinlogindemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIAuthError;
import com.linkedin.platform.listeners.AuthListener;
import com.linkedin.platform.utils.Scope;


public class MainActivity extends AppCompatActivity {
    Button loginBtn;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        loginBtn = (Button) findViewById(R.id.login_button);
        textView=(TextView)findViewById(R.id.textView);
        loginBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                loginHandle();
            }
        });
    }
    public void loginHandle() {
        LISessionManager.getInstance(getApplicationContext()).init(MainActivity.this, buildScope(), new AuthListener() {
                    @Override
                    public void onAuthSuccess() {
                        // Authentication was successful.  You can now do other calls with the SDK.
   
                        Intent intent=new Intent(MainActivity.this,ProfileActivity.class);
                        startActivity(intent);
                    }

                    @Override
                    public void onAuthError(LIAuthError error) {
                        // Handle authentication errors
                        Toast.makeText(getApplicationContext(),"Login Error "+error.toString(),Toast.LENGTH_LONG).show();
                    }
                }, true);
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // Add this line to your existing onActivityResult() method
        LISessionManager.getInstance(getApplicationContext()).onActivityResult(this, requestCode, resultCode, data);
    }


}

activity_profile.xml

Now, add the following code in activity_profile.xml file. In this activity, we will display the user information after successful login.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center_horizontal"
    tools:context="example.com.linkedinlogindemo.ProfileActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to profile" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/userDetail"
        android:text="userdetail"
        android:layout_marginTop="20dp"
        />
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="30dp"
        android:textColor="#FFF"
        android:text="logout"
        android:id="@+id/logout_button"
        android:background="#022885"
        />
</LinearLayout>

ProfileActivity.java

Add the LinkedIn API URL https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address) in getRequest() method of APIHelper class. It will retrieve the user information on success of LinkedIn API.

package example.com.linkedinlogindemo;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.linkedin.platform.APIHelper;
import com.linkedin.platform.LISession;
import com.linkedin.platform.LISessionManager;
import com.linkedin.platform.errors.LIApiError;
import com.linkedin.platform.listeners.ApiListener;
import com.linkedin.platform.listeners.ApiResponse;

import org.json.JSONException;
import org.json.JSONObject;

public class ProfileActivity extends AppCompatActivity {
    TextView user_detail;
    String firstName,lastName,userEmail;
    Button logout;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_profile);
        user_detail=(TextView)findViewById(R.id.userDetail);
        logout=(Button)findViewById(R.id.logout_button);

        fetchuserData();

        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                LISessionManager.getInstance(getApplicationContext()).clearSession();
                Toast.makeText(getApplicationContext(),"Logout Successfully",Toast.LENGTH_LONG).show();
                Intent intent = new Intent(ProfileActivity.this, MainActivity.class);
                startActivity(intent);
            }
        });
   }

    private void fetchuserData() {
        String url = "https://api.linkedin.com/v1/people/~:(id,first-name,last-name,email-address)";

        APIHelper apiHelper = APIHelper.getInstance(getApplicationContext());
        apiHelper.getRequest(this, url, new ApiListener() {
            @Override
            public void onApiSuccess(ApiResponse apiResponse) {
                // Success!
                try {
                    JSONObject jsonObject = apiResponse.getResponseDataAsJson();
                    firstName = jsonObject.getString("firstName");
                    lastName = jsonObject.getString("lastName");
                    userEmail = jsonObject.getString("emailAddress");

                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("First Name " + firstName + "\n\n");
                    stringBuilder.append("Last Name " + lastName + "\n\n");
                    stringBuilder.append("Email " + userEmail);

                    user_detail.setText(stringBuilder);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onApiError(LIApiError liApiError) {
                // Error making GET request!
                Toast.makeText(getApplicationContext(),"API Error"+liApiError.toString(),Toast.LENGTH_LONG).show();
            }
        });
    }
}

Output:

android LinkedIn Integrating android LinkedIn Integrating
android LinkedIn Integrating android LinkedIn Integrating




Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf