Android allows your application to connect your linkedin account and share data or any kind of update on Linkedin.
Heare we learn about how to integrate linkedin in our android application.
Linkedin provide you to connect acount using diffrent types, like
- Using Sdk
- Using Api
along with this two method, we learn about using api based integration in this artical.
In this connection we can get permission for sharing the post on his profile and get his basic infromation.
this data will getting using accesstoken,
We can start to devloping, follow the below steps,
- Register application on linkedin devloper account, click here
- Get client id and secret key
- Design you custom application
- Integrate code in your application
1) Register application on LinkedIn developer account
In every social account, if you want to access using his account need some permissions and register app on that account.
Similar on LinkedIn, first required to register our application on LinkedIn developer account, click here to register.
Watch full video and follow the the all step to register account on LinkedIn.
2) Get client id and secret key
3) Design you custom application
create activity_main.xml layout file and place one webview inside the layout.
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include android:id="@+id/inHeaderLayout" layout="@layout/header_layout" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" /> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent"> <com.sociosquare.socioadvocacy.customview.CustomWebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:focusable="true" android:focusableInTouchMode="true" /> </RelativeLayout> </LinearLayout> </FrameLayout>
above code , this line have one another layout called as header_layout.
header_layout display like title. so create another layout file called as header_layout.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlHeaderLayout" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:orientation="vertical"> <TextView android:id="@+id/tvScreenTitle" android:layout_width="wrap_content" android:layout_height="wrap_content" android:padding="16dp" android:text="LinkedIn Login" android:textSize="16sp" /> <View android:layout_width="match_parent" android:layout_height="1dp" android:background="@color/colorAccent" /> </LinearLayout>
Now, check in activity_main.xml, contains one CustomWebView, this one we required to create custom webview in our application.
create one new ajva file called as CustomWebView.java
package in.co.lifs.linkedinintegration; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.webkit.WebView; public class CustomWebView extends WebView { public CustomWebView(Context context) { this(context, null); } public CustomWebView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public CustomWebView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } @Override public boolean onCheckIsTextEditor() { return true; } @Override public boolean onTouchEvent(MotionEvent ev) { switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_UP: if (!hasFocus()){ requestFocus(); } break; } return super.onTouchEvent(ev); } }
4) Integrate code in your application
Finaly in our code we have write the following code creating MainActivity.java file.
import android.app.Activity; import android.content.Context; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import com.sociosquare.socioadvocacy.R; import com.sociosquare.socioadvocacy.application.SocioAdvocacyApplication; import com.sociosquare.socioadvocacy.constants.DefaultConstants; import com.sociosquare.socioadvocacy.constants.ScreenNames; import com.sociosquare.socioadvocacy.customview.CustomWebView; import com.sociosquare.socioadvocacy.printlog.Logger; import com.sociosquare.socioadvocacy.services.RequestUtils; import com.sociosquare.socioadvocacy.utils.AnalyticUtility; import com.sociosquare.socioadvocacy.utils.Utility; import org.apache.http.HttpResponse; import org.apache.http.ParseException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.Calendar; import io.fabric.sdk.android.Fabric; public class MainActivity extends Activity { private static String TAG = "MainActivity"; /*CONSTANT FOR THE AUTHORIZATION PROCESS*/ /**** * YOUR LINKEDIN APP INFO HERE *********/ //This is any string we want to use. This will be used for avoid CSRF attacks. You can generate one here: http://strongpasswordgenerator.com/ private static final String STATE = "784a5c0728878e883d4921eda0e31067"; private static final String REDIRECT_URI = DefaultConstants.CONSTANT_LN_OAUTH_CALLBACK_URL; private static final String SCOPES = "r_basicprofile%20w_share"; /*********************************************/ //These are constants used for build the urls private static final String AUTHORIZATION_URL = "https://www.linkedin.com/oauth/v2/authorization"; private static final String ACCESS_TOKEN_URL = "https://www.linkedin.com/oauth/v2/accessToken"; private static final String SECRET_KEY_PARAM = "client_secret"; private static final String RESPONSE_TYPE_PARAM = "response_type"; private static final String GRANT_TYPE_PARAM = "grant_type"; private static final String GRANT_TYPE = "authorization_code"; private static final String RESPONSE_TYPE_VALUE = "code"; private static final String CLIENT_ID_PARAM = "client_id"; private static final String SCOPE_PARAM = "scope"; private static final String STATE_PARAM = "state"; private static final String REDIRECT_URI_PARAM = "redirect_uri"; /*---------------------------------------*/ private static final String QUESTION_MARK = "?"; private static final String AMPERSAND = "&"; private static final String EQUALS = "="; private CustomWebView webView; public boolean closeScreen = false; String authUrl = ""; String myLoadUrl = ""; LayoutInflater inflater; private TextView tvScreenTitle; /*Data Manage*/ View dummyView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Fabric.with(this, new Crashlytics()); setContentView(R.layout.activity_linkedin_webview); AnalyticUtility.logScreen(this, ScreenNames.SCREENS, ScreenNames.SCREEN_LINKEDIN_LOGIN); callAnalytic(LinkedinLoginWebViewMy.this, ScreenNames.SCREEN_LINKEDIN_LOGIN); tvScreenTitle = (TextView) findViewById(R.id.tvScreenTitle); tvScreenTitle.setText(getResources().getString(R.string.edit_network_socioal_login_linkedin)); String LinkedInPermission = ""; for (int i = 0; i < DefaultConstants.LN_PERMISSION.size(); i++) { if (!Utility.validateString(LinkedInPermission)) { LinkedInPermission = DefaultConstants.LN_PERMISSION.get(i); } else { LinkedInPermission = LinkedInPermission + "%20" + DefaultConstants.LN_PERMISSION.get(i); } } // myLoadUrl = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code&client_id=" + mPreferences.getString(PreferenceList.APP_ID_LN_PREF, "") + "&scope="; myLoadUrl = "https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=" + "APP Id WRITE HERE" + "&scope="; final String myLoadUrlFull = myLoadUrl + LinkedInPermission + "&state=784a5c0728878e883d4921eda0e31067&redirect_uri=https://api.socioadvocacy.com/oauth2callback.html"; // Utility.FullScreencall(this); inflater = getLayoutInflater(); webView = (CustomWebView) findViewById(R.id.webView); webView.requestFocus(View.FOCUS_DOWN); /* pd = ProgressDialog.show(this, "", "Loading..", true);*/ closeScreen = getIntent().getBooleanExtra("closeScreen", false); Utility.clearCookies(this); //Set a custom web view client webView.setWebViewClient(new WebViewClient() { @Override public void onPageFinished(WebView view, String url) { } @Override public boolean shouldOverrideUrlLoading(WebView view, String authorizationUrl) { //This method will be called when the Auth proccess redirect to our RedirectUri. //We will check the url looking for our RedirectUri. if (authorizationUrl.startsWith(REDIRECT_URI)) { Uri uri = Uri.parse(authorizationUrl); //We take from the url the authorizationToken and the state token. We have to check that the state token returned by the Service is the same we sent. //If not, that means the request may be a result of CSRF and must be rejected. String stateToken = uri.getQueryParameter(STATE_PARAM); if (stateToken == null || !stateToken.equals(STATE)) { Logger.e(TAG, "State token doesn't match"); return true; } //If the user doesn't allow authorization to our application, the authorizationToken Will be null. String authorizationToken = uri.getQueryParameter(RESPONSE_TYPE_VALUE); if (authorizationToken == null) { Logger.e(TAG, "The user doesn't allow authorization."); return true; } Logger.e(TAG, "Auth token received: " + authorizationToken); //Generate URL for requesting Access Token String accessTokenUrl = getAccessTokenUrl(authorizationToken, "APP Id write Here", "App Secret Write here"); //We make the request in a AsyncTask new PostRequestAsyncTask().execute(accessTokenUrl); } else { //Default behaviour Logger.e(TAG, "Redirecting to: " + authorizationUrl); webView.loadUrl(authorizationUrl); // webView.loadUrl(myLoadUrlFull); } return true; } }); //Get the authorization Url authUrl = getAuthorizationUrl("WRITE APP ID here", "WRITE APP Secret Here"); Logger.e(TAG, "Loading Auth Url: " + authUrl); //Load the authorization URL into the webView // webView.loadUrl(authUrl); webView.loadUrl(myLoadUrlFull); } /** * Method that generates the url for get the access token from the Service * * @return Url */ private static String getAccessTokenUrl(String authorizationToken, String appid, String appSecret) { String URL = ACCESS_TOKEN_URL + QUESTION_MARK + GRANT_TYPE_PARAM + EQUALS + GRANT_TYPE + AMPERSAND + RESPONSE_TYPE_VALUE + EQUALS + authorizationToken + AMPERSAND + CLIENT_ID_PARAM + EQUALS + appid + AMPERSAND + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI + AMPERSAND + SECRET_KEY_PARAM + EQUALS + appSecret; Logger.e(TAG, "" + URL); return URL; } /** * Method that generates the url for get the authorization token from the Service * * @return Url */ private static String getAuthorizationUrl(String appid, String appSecret) { //DefaultConstants.LN_PERMISSION is a Permission which we are required for login and functionality String permissions = ""; for (int i = 0; i < DefaultConstants.LN_PERMISSION.size(); i++) { if (i == DefaultConstants.LN_PERMISSION.size() - 1) { String permission = ""; permission = DefaultConstants.LN_PERMISSION.get(i).toString(); DefaultConstants.lnScopes += permission; } else { String permission = DefaultConstants.LN_PERMISSION.get(i).toString() + "%20"; DefaultConstants.lnScopes += permission; } } DefaultConstants.lnScopeParams = DefaultConstants.lnScopes.replace("%20", "+"); /**/ for (int i = 0; i < DefaultConstants.LN_PERMISSION.size(); i++) { if (i == DefaultConstants.LN_PERMISSION.size() - 1) { String permission = null; permission = DefaultConstants.LN_PERMISSION.get(i).toString(); permissions += permission; } else { String permission = DefaultConstants.LN_PERMISSION.get(i).toString() + "%20"; permissions += permission; } } String URL = AUTHORIZATION_URL + QUESTION_MARK + RESPONSE_TYPE_PARAM + EQUALS + RESPONSE_TYPE_VALUE + AMPERSAND + CLIENT_ID_PARAM + EQUALS + appid + AMPERSAND + SCOPE_PARAM + EQUALS + DefaultConstants.lnScopes + AMPERSAND + STATE_PARAM + EQUALS + STATE + AMPERSAND + REDIRECT_URI_PARAM + EQUALS + REDIRECT_URI; Logger.e(TAG, "" + URL); return URL; } private void callAnalytic(Context mContext, String ScreenName) { SocioAdvocacyApplication mGoogleAnalytics = (SocioAdvocacyApplication) getApplication(); AnalyticUtility.analyticGoogle(mContext, mGoogleAnalytics, ScreenName); } private class PostRequestAsyncTask extends AsyncTask<String, Void, Boolean> { @Override protected void onPreExecute() { } @Override protected Boolean doInBackground(String... urls) { if (urls.length > 0) { String url = urls[0]; HttpClient httpClient = RequestUtils.getHttpsClient(new DefaultHttpClient()); // HttpClient httpClient = new DefaultHttpClient(); HttpPost httpost = new HttpPost(url); try { HttpResponse response = httpClient.execute(httpost); if (response != null) { //If status is OK 200 if (response.getStatusLine().getStatusCode() == 200) { String result = EntityUtils.toString(response.getEntity()); //Convert the string result to a JSON Object JSONObject resultJson = new JSONObject(result); //Extract data from JSON Response int expiresIn = resultJson.has("expires_in") ? resultJson.getInt("expires_in") : 0; String accessToken = resultJson.has("access_token") ? resultJson.getString("access_token") : null; Logger.e(TAG, "" + accessToken); if (expiresIn > 0 && accessToken != null) { Logger.e(TAG, "This is the access Token: " + accessToken + ". It will expires in " + expiresIn + " secs"); //Calculate date of expiration Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.SECOND, expiresIn); long expireDate = calendar.getTimeInMillis(); return true; } } } } catch (IOException e) { Logger.e(TAG, "Error Http response " + e.getLocalizedMessage()); } catch (ParseException e) { Logger.e(TAG, "Error Parsing Http response " + e.getLocalizedMessage()); } catch (JSONException e) { Logger.e(TAG, "Error Parsing Http response " + e.getLocalizedMessage()); } } return false; } @Override protected void onPostExecute(Boolean status) { } } @Override public void onDestroy() { super.onDestroy(); } @Override protected void onStop() { super.onStop(); } @Override public void onBackPressed() { super.onBackPressed(); this.finish(); } }
When we execute this code that time we enter email and password in the linkedIn login page.
After the providing email and password ask for the permission.
we accept the all permission and get accesstoken of the particular user.
Using accesstoken we access that user information, name birthdate etc..
Inside the code mainly used two urls, first for authorisation and another is accesstoken.
“https://www.linkedin.com/oauth/v2/authorization” this url login user and authorised the permission.
While “https://www.linkedin.com/oauth/v2/accessToken” this usrl use for accesstoken to get the user information.
It’s really a great and useful piece of information. I am happy that you just shared this helpful information with us.
Please stay us informed like this. Thanks for sharing.
Appreciation to my father who stated to me about this blog,
this blog is in fact awesome.
FaƄulous, what a blog it is! This website presents helpful informɑtion to us, keep it up.