2013-05-06 81 views
1

,我想分享的是我在下面的代碼用在LinkedIn文本共享對LinkedIn的Android

public class ShareWithLinkedIn extends Activity { 
public static final String CONSUMER_KEY = "YOUR_COUSUMER_KEY"; 
public static final String CONSUMER_SECRET = "YOUR_SECRET_KEY"; 
public static final String APP_NAME = "SharePhotoImage"; 
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin"; 
public static final String OAUTH_CALLBACK_HOST = "litestcalback"; 
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST; 
static final String OAUTH_QUERY_TOKEN = "oauth_token"; 
static final String OAUTH_QUERY_VERIFIER = "oauth_verifier"; 
static final String OAUTH_QUERY_PROBLEM = "oauth_problem"; 
static final String OAUTH_PREF = "AppPreferences"; 
static final String PREF_TOKEN = "linkedin_token"; 
static final String PREF_TOKENSECRET = "linkedin_token_secret"; 
static final String PREF_REQTOKENSECRET = "linkedin_request_token_secret"; 

final LinkedInOAuthService oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(CONSUMER_KEY, CONSUMER_SECRET); 
final LinkedInApiClientFactory factory = LinkedInApiClientFactory.newInstance(CONSUMER_KEY, CONSUMER_SECRET); 
LinkedInRequestToken liToken; 
LinkedInApiClient client; 

TextView tv = null; 

/** Called when the activity is first created. */ 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    tv = new TextView(this); 
    setContentView(tv); 
    final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE); 
    final String token = pref.getString(PREF_TOKEN, null); 
    final String tokenSecret = pref.getString(PREF_TOKENSECRET, null); 
    if (token == null || tokenSecret == null) { 
     startAutheniticate(); 
    } else { 
     LinkedInAccessToken accessToken = new LinkedInAccessToken(token, tokenSecret); 
     showCurrentUser(accessToken); 
    } 
}// end method 

void startAutheniticate() { 
    new Thread() {// added because this will make code work on post API 10 
     @Override 
     public void run() { 
      final LinkedInRequestToken liToken = oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL); 
      final String uri = liToken.getAuthorizationUrl(); 
      final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE); 
      SharedPreferences.Editor editor = pref.edit(); 
      editor.putString(PREF_REQTOKENSECRET, liToken.getTokenSecret()); 
      editor.commit(); 
      Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri)); 
      startActivity(i); 
     } 
    }.start(); 
}// end method 

void finishAuthenticate(final Uri uri) { 
    new Thread() { 
     @Override 
     public void run() { 
      Looper.prepare(); 
      if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) { 
       final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM); 
       if (problem == null) { 
        final SharedPreferences pref = getSharedPreferences(OAUTH_PREF, MODE_PRIVATE); 
        final String request_token_secret = pref.getString(PREF_REQTOKENSECRET, null); 
        final String query_token = uri.getQueryParameter(OAUTH_QUERY_TOKEN); 
        final LinkedInRequestToken request_token = new LinkedInRequestToken(query_token, request_token_secret); 
        final LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(request_token, uri.getQueryParameter(OAUTH_QUERY_VERIFIER)); 
        SharedPreferences.Editor editor = pref.edit(); 
        editor.putString(PREF_TOKEN, accessToken.getToken()); 
        editor.putString(PREF_TOKENSECRET, accessToken.getTokenSecret()); 
        editor.remove(PREF_REQTOKENSECRET); 
        editor.commit(); 
        showCurrentUser(accessToken); 
       } else { 
        Toast.makeText(getApplicationContext(), "Application down due OAuth problem: " + problem, Toast.LENGTH_LONG).show(); 
        finish(); 
       } 
      } 
      Looper.loop(); 
     } 
    }.start(); 
}// end method 

void clearTokens() { 
    getSharedPreferences(OAUTH_PREF, MODE_PRIVATE).edit().remove(PREF_TOKEN).remove(PREF_TOKENSECRET).remove(PREF_REQTOKENSECRET).commit(); 
}// end method 

void showCurrentUser(final LinkedInAccessToken accessToken) { 
    new Thread() { 
     @Override 
     public void run() { 
      Looper.prepare(); 
      final LinkedInApiClient client = factory.createLinkedInApiClient(accessToken); 
      try { 
       final Person p = client.getProfileForCurrentUser(); 
       // ///////////////////////////////////////////////////////// 
       // here you can do client API calls ... 
       // client.postComment(arg0, arg1); 
       // client.updateCurrentStatus(arg0); 
       // or any other API call (this sample only check for current 
       // user 
       // and shows it in TextView) 
       // ///////////////////////////////////////////////////////// 
       runOnUiThread(new Runnable() {// updating UI thread from 
               // different thread not a 
               // good idea... 
        public void run() { 
         tv.setText(p.getLastName() + ", " + p.getFirstName()); 
        } 
       }); 
       // or use Toast 
       // Toast.makeText(getApplicationContext(), 
       // "Lastname:: "+p.getLastName() + ", First name: " + 
       // p.getFirstName(), 1).show(); 
      } catch (LinkedInApiClientException ex) { 
       clearTokens(); 
       Toast.makeText(getApplicationContext(), "Application down due LinkedInApiClientException: " + ex.getMessage() + " Authokens cleared - try run application again.", 
         Toast.LENGTH_LONG).show(); 
       finish(); 
      } 
      Looper.loop(); 
     } 
    }.start(); 
}// end method 

@Override 
protected void onNewIntent(Intent intent) { 
    finishAuthenticate(intent.getData()); 
}// end method 

} //結束類

它讓我登錄,並允許屏幕,這是尋找像下面時我再次單擊該按鈕將顯示相同的屏幕,但我想要時(我點擊該按鈕,它應該與圖像url分享文本)...

可以任何身體幫助我解決這個問題

enter image description here

+0

發佈在Linkedin上分享,您還需要申請'rw_nus'權限。請參閱[Linkedin Share API](https://developer.linkedin.com/documents/share-api) – 2013-05-06 13:01:07

+0

你能舉個例子怎麼做嗎? – 2013-05-06 13:16:30

回答

0

通過下面的代碼,我已經做了

public class ShareInLinkedIn extends Activity implements OnClickListener { 

private LinkedInOAuthService oAuthService; 
private LinkedInApiClientFactory factory; 
private LinkedInRequestToken liToken; 
private LinkedInApiClient client; 
public static final String LINKEDIN_PREF = "GamePrefs"; 

@SuppressLint({ "NewApi", "NewApi", "NewApi" }) 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.linkedin); 

    if (android.os.Build.VERSION.SDK_INT > 9) { 
     StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build(); 
     StrictMode.setThreadPolicy(policy); 
    } 

    oAuthService = LinkedInOAuthServiceFactory.getInstance().createLinkedInOAuthService(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET, Constants.SCOPE_PARAMS); 
    System.out.println("oAuthService : " + oAuthService); 

    factory = LinkedInApiClientFactory.newInstance(Constants.CONSUMER_KEY, Constants.CONSUMER_SECRET); 

    liToken = oAuthService.getOAuthRequestToken(Constants.OAUTH_CALLBACK_URL); 
    System.out.println("onCreate:linktoURL : " + liToken.getAuthorizationUrl()); 
    Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(liToken.getAuthorizationUrl())); 
    startActivity(i); 

} 

@Override 
protected void onNewIntent(Intent intent) { 
    super.onNewIntent(intent); 

    try { 
     linkedInImport(intent); 
    } catch (NullPointerException e) { 
     e.printStackTrace(); 
    } 
} 

private void linkedInImport(Intent intent) { 
    String verifier = intent.getData().getQueryParameter("oauth_verifier"); 
    System.out.println("liToken " + liToken); 
    System.out.println("verifier " + verifier); 

    LinkedInAccessToken accessToken = oAuthService.getOAuthAccessToken(liToken, verifier); 
    //SharedPreferences settings = getSharedPreferences(LINKEDIN_PREF, MODE_PRIVATE); 
    // final Editor edit = settings.edit(); 
    // edit.putString(OAuth.OAUTH_TOKEN, accessToken.getToken()); 
    // edit.putString(OAuth.OAUTH_TOKEN_SECRET, 
    // accessToken.getTokenSecret()); 
    // edit.putString("linkedin_login", "valid"); 
    // edit.commit(); 

    client = factory.createLinkedInApiClient(accessToken); 

    // client.postNetworkUpdate("LinkedIn Android app test"); 

    Person profile = client.getProfileForCurrentUser(EnumSet.of(ProfileField.ID, ProfileField.FIRST_NAME, ProfileField.LAST_NAME, ProfileField.HEADLINE)); 

    System.out.println("First Name :: " + profile.getFirstName()); 
    System.out.println("Last Name :: " + profile.getLastName()); 
    System.out.println("Head Line :: " + profile.getHeadline()); 

    OAuthConsumer consumer = new CommonsHttpOAuthConsumer(Constants.CONSUMER_KEY, Constants.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); 
     post.setHeader("content-type", "text/XML"); 
     String myEntity = "<share><comment>This is a test</comment><visibility><code>anyone</code></visibility></share>"; 
     post.setEntity(new StringEntity(myEntity)); 
     org.apache.http.HttpResponse response = httpclient.execute(post); 
     // Get the response 
     BufferedReader rd = new BufferedReader 
      (new InputStreamReader(response.getEntity().getContent())); 
     StringBuffer strBfr = new StringBuffer(); 
     String line = ""; 
     while ((line = rd.readLine()) != null) { 

      strBfr.append(line); 
     } 
     System.out.println("Response is : "+strBfr.toString()); 
     Toast.makeText(ShareInLinkedIn.this, strBfr.toString(), Toast.LENGTH_LONG).show(); 
    } catch (Exception e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 


} 

@Override 
public void onClick(View v) { 
    // TODO Auto-generated method stub 

} 

}

Constants.java

public class Constants { 

public static final String CONSUMER_KEY = "YOUR_CONSUMER_KEY"; 
public static final String CONSUMER_SECRET = "YOUR_CONSUMER_SECRET_KEY"; 
public static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin"; 
public static final String OAUTH_CALLBACK_HOST = "litestcalback"; 
public static final String OAUTH_CALLBACK_URL = OAUTH_CALLBACK_SCHEME + "://" + OAUTH_CALLBACK_HOST; 
public static final String SCOPE_PARAMS = "rw_nus+r_basicprofile"; 

}

AndroidManifiest.xml文件

 <activity 
     android:name="com.linkedin.ShareInLinkedIn" 
     android:launchMode="singleInstance" > 
     <intent-filter> 
      <action android:name="android.intent.action.VIEW" /> 

      <category android:name="android.intent.category.DEFAULT" /> 
      <category android:name="android.intent.category.BROWSABLE" /> 

      <data 
       android:host="litestcalback" 
       android:scheme="x-oauthflow-linkedin" /> 
     </intent-filter> 
    </activity>