Thursday, November 13, 2014

Integration with Linkedin in android

Libraryes are as follows


add some libraryes of linked in as u can add :-

1 linkedin-j-android
2 signpost-commonshttp4-1.2.1.1
3 signpost-core-1.2.1.1
4 signpost-jetty6-1.2.1.1

activity are as below:-
1

<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"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/hello_world" />

</RelativeLayout>

2:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/blue_bg_rect"
    android:orientation="vertical" >

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <LinearLayout
            android:id="@+id/header"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:background="@drawable/blue_gradient_header"
            android:orientation="vertical" >

            <Button
                android:id="@+id/logo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="false"
                android:layout_centerVertical="true"
                android:layout_gravity="center"
                android:layout_marginLeft="8dp"
                android:background="@drawable/logo"
                android:padding="4dp"
                android:text="" />

            <TextView
                android:id="@+id/txtTitle"
                android:layout_width="wrap_content"
                android:layout_height="32dp"
                android:layout_centerHorizontal="true"
                android:layout_centerVertical="true"
                android:text="Linkedin"
                android:textColor="@android:color/white"
                android:textSize="22sp"
                android:textStyle="bold"
                android:typeface="sans" >
            </TextView>

            <TextView
                android:id="@+id/name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_below="@+id/header"
                android:padding="15dp"
                android:text="Name"
                android:textColor="@android:color/white"
                android:textSize="16sp"
                android:textStyle="bold"
                android:visibility="invisible" />

            <TextView
                android:id="@+id/tviId"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="ID" />

            <TextView
                android:id="@+id/tviAddress"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Address" />

            <TextView
                android:id="@+id/tviDOB"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="DOB" />

            <TextView
                android:id="@+id/tviCurrentStatus"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="CurrentStatus" />

            <TextView
                android:id="@+id/tviLocation"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Location" />

            <TextView
                android:id="@+id/tviPhoneNum"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="PhoneNum" />

            <TextView
                android:id="@+id/tviPositions"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Positions" />

            <Button
                android:id="@+id/share"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_below="@+id/et_share"
                android:layout_marginTop="22dp"
                android:background="@drawable/linkedin_share"
                android:visibility="invisible" />

            <Button
                android:id="@+id/login"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:layout_centerInParent="true"
                android:layout_centerVertical="true"
                android:background="@drawable/btn_active_pressed"
                android:gravity="center_vertical|center_horizontal"
                android:padding="8dp"
                android:text="Login"
                android:textColor="@android:color/white"
                android:textStyle="bold" />

            <ImageView
                android:id="@+id/photo"
                android:layout_width="72dp"
                android:layout_height="72dp"
                android:layout_alignRight="@+id/et_share"
                android:layout_alignTop="@+id/name"
                android:layout_marginTop="22dp"
                android:background="@drawable/photo"
                android:padding="5dp"
                android:visibility="invisible" />

            <EditText
                android:id="@+id/et_share"
                android:layout_width="match_parent"
                android:layout_height="100dp"
                android:layout_alignBottom="@+id/login"
                android:layout_alignParentRight="true"
                android:ems="10"
                android:gravity="top|center_vertical"
                android:hint="Enter Your Text to Share"
                android:visibility="invisible" >

                <requestFocus />
            </EditText>
        </LinearLayout>
    </ScrollView>

</LinearLayout>
3:-

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="280dip"
    android:layout_height="420dip"
    android:orientation="vertical" >
      <WebView
        android:id="@+id/webkitWebView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />
</RelativeLayout>


.class are as below:-


package com.mukesh.linkedin;

import com.example.linkedin.R;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;

public class MainActivity extends Activity {

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

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
   
}





public class LinkedInSampleActivity extends Activity {
Button login;
Button share;
EditText et;
TextView name;
ImageView photo;
Profile t;
Profile profileMap = t;
TextView tviId,tviAddress,tviDOB,tviCurrentStatus,tviLocation,tviPhoneNum,tviPositions;
public static final String OAUTH_CALLBACK_HOST = "litestcalback";

final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
            .getInstance().createLinkedInOAuthService(
                    Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
final LinkedInApiClientFactory factory = LinkedInApiClientFactory
.newInstance(Config.LINKEDIN_CONSUMER_KEY,
Config.LINKEDIN_CONSUMER_SECRET);
LinkedInRequestToken liToken;
LinkedInApiClient client;
LinkedInAccessToken accessToken = null;

@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if( Build.VERSION.SDK_INT >= 9){
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy); 
}
share = (Button) findViewById(R.id.share);
name = (TextView) findViewById(R.id.name);
et = (EditText) findViewById(R.id.et_share);
login = (Button) findViewById(R.id.login);
photo = (ImageView) findViewById(R.id.photo);

tviId= (TextView) findViewById(R.id.tviId);
tviAddress= (TextView) findViewById(R.id.tviAddress);
tviDOB= (TextView) findViewById(R.id.tviDOB);
tviCurrentStatus= (TextView) findViewById(R.id.tviCurrentStatus);
tviLocation= (TextView) findViewById(R.id.tviLocation);
tviPhoneNum= (TextView) findViewById(R.id.tviPhoneNum);
tviPositions= (TextView) findViewById(R.id.tviPositions);
login.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
linkedInLogin();
}
});

// share on linkedin
share.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {
String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);
   consumer.setTokenWithSecret(accessToken.getToken(), accessToken.getTokenSecret());
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost("https://api.linkedin.com/v1/people/~/shares");
try {
consumer.sign(post);
} catch (OAuthMessageSignerException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (OAuthCommunicationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // here need the consumer for sign in for post the share
post.setHeader("content-type", "text/XML");
String myEntity = "<share><comment>"+ share +"</comment><visibility><code>anyone</code></visibility></share>";
try {
post.setEntity(new StringEntity(myEntity));
org.apache.http.HttpResponse response = httpclient.execute(post);
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}
/*String share = et.getText().toString();
if (null != share && !share.equalsIgnoreCase("")) {
client = factory.createLinkedInApiClient(accessToken);
client.postNetworkUpdate(share);
et.setText("");
Toast.makeText(LinkedInSampleActivity.this,
"Shared sucessfully", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(LinkedInSampleActivity.this,
"Please enter the text to share",
Toast.LENGTH_SHORT).show();
}*/
}
});
}

private void linkedInLogin() {
ProgressDialog progressDialog = new ProgressDialog(
LinkedInSampleActivity.this);

LinkedinDialog d = new LinkedinDialog(LinkedInSampleActivity.this,
progressDialog);
d.show();

// set call back listener to get oauth_verifier value
d.setVerifierListener(new OnVerifyListener() {
@Override
public void onVerify(String verifier) {
try {
 
accessToken = LinkedinDialog.oAuthService
.getOAuthAccessToken(LinkedinDialog.liToken,
verifier);
LinkedinDialog.factory.createLinkedInApiClient(accessToken);
client = factory.createLinkedInApiClient(accessToken);
// client.postNetworkUpdate("Testing by Mukesh!!! LinkedIn wall post from Android app");
 
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getToken());
Log.i("LinkedinSample",
"ln_access_token: " + accessToken.getTokenSecret());
Person p = client.getProfileForCurrentUser();
 
name.setText("Welcome " + p.getFirstName() + " "
+ p.getLastName());
System.out.println(p);
 
tviId.setText(",Id:- "+p.getId());
 
tviAddress.setText(" Address:- "+p.getMainAddress());
tviDOB.setText(" DOB:- "+p.getDateOfBirth());
tviCurrentStatus.setText(" CurrentStatus:-"+p.getCurrentStatusTimestamp());
tviLocation.setText(" Location:-"+p.getLocation());
tviPhoneNum.setText(" PhoneNum:-"+p.getPhoneNumbers());
tviPositions.setText(" Positions :-"+p.getPositions());
 
name.setVisibility(0);
login.setVisibility(4);
share.setVisibility(0);
et.setVisibility(0);

} catch (Exception e) {
Log.i("LinkedinSample", "error to get verifier");
e.printStackTrace();
}
}
});

// set progress dialog
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
progressDialog.show();
}
}



third class:-



public class LinkedinDialog extends Dialog {
private ProgressDialog progressDialog = null;

public static LinkedInApiClientFactory factory;
public static LinkedInOAuthService oAuthService;
public static LinkedInRequestToken liToken;

/**
* Construct a new LinkedIn dialog
* @param context
*            activity {@link Context}
* @param progressDialog
*            {@link ProgressDialog}
*/
public LinkedinDialog(Context context, ProgressDialog progressDialog) {
super(context);
this.progressDialog = progressDialog;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_NO_TITLE);// must call before super.
super.onCreate(savedInstanceState);
setContentView(R.layout.ln_dialog);

setWebView();
}

/**
* set webview.
*/
private void setWebView() {
LinkedinDialog.oAuthService = LinkedInOAuthServiceFactory.getInstance()
.createLinkedInOAuthService(Config.LINKEDIN_CONSUMER_KEY,
Config.LINKEDIN_CONSUMER_SECRET);
LinkedinDialog.factory = LinkedInApiClientFactory.newInstance(
Config.LINKEDIN_CONSUMER_KEY, Config.LINKEDIN_CONSUMER_SECRET);

LinkedinDialog.liToken = LinkedinDialog.oAuthService
.getOAuthRequestToken(Config.OAUTH_CALLBACK_URL);

WebView mWebView = (WebView) findViewById(R.id.webkitWebView1);
mWebView.getSettings().setJavaScriptEnabled(true);

Log.i("LinkedinSample", LinkedinDialog.liToken.getAuthorizationUrl());
mWebView.loadUrl(LinkedinDialog.liToken.getAuthorizationUrl());
mWebView.setWebViewClient(new HelloWebViewClient());

mWebView.setPictureListener(new PictureListener() {
@Override
public void onNewPicture(WebView view, Picture picture) {
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}

}
});

}

/**
* webview client for internal url loading
* callback url: "https://www.linkedin.com/uas/oauth/mukeshyadav4u.blogspot.in"
*/
class HelloWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains(Config.OAUTH_CALLBACK_URL)) {
Uri uri = Uri.parse(url);
String verifier = uri.getQueryParameter("oauth_verifier");

cancel();

for (OnVerifyListener d : listeners) {
// call listener method
d.onVerify(verifier);
}
} else if (url
.contains("https://www.linkedin.com/uas/oauth/mukeshyadav4u.blogspot.in")) {
cancel();
} else {
Log.i("LinkedinSample", "url: " + url);
view.loadUrl(url);
}

return true;
}
}

/**
* List of listener.
*/
private List<OnVerifyListener> listeners = new ArrayList<OnVerifyListener>();

/**
* Register a callback to be invoked when authentication have finished.
* @param data
*            The callback that will run
*/
public void setVerifierListener(OnVerifyListener data) {
listeners.add(data);
}

/**
* Listener for oauth_verifier.
*/
interface OnVerifyListener {
/**
* invoked when authentication have finished.
* @param verifier
*            oauth_verifier code.
*/
public void onVerify(String verifier);
}
}


4th class:-


public class Config {

public static String LINKEDIN_CONSUMER_KEY = "75hwellbdyour keys tzd";
public static String LINKEDIN_CONSUMER_SECRET = "VsY your secrates 9dcwqc0Lk";
public static String scopeParams = "rw_nus+r_basicprofile";
public static String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
public static String OAUTH_CALLBACK_HOST = "callback";
public static String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST;
}


manifest :-



    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="16" />

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


have a great luck get enjoy.... it will help u more friends 





3 comments:

  1. i implement the same as above but my application get crash because that scope parameter

    ReplyDelete
  2. final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
    .getInstance().createLinkedInOAuthService(
    Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);

    if i remove the above code my app run well but after adding this code
    final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory
    .getInstance().createLinkedInOAuthService(
    Config.LINKEDIN_CONSUMER_KEY,Config.LINKEDIN_CONSUMER_SECRET, Config.scopeParams);
    my app get crash
    i want to add this permision "Config.scopeParams" but how my app get crash on adding it please help me

    ReplyDelete
  3. x-oauthflow-linkedin is this is the callback url that we get from linkdin

    ReplyDelete