从Android应用程序发布LinkedIn消息

从Android应用程序发布LinkedIn消息,android,integration,linkedin,Android,Integration,Linkedin,我想将我的Android应用程序与LinkedIn集成并发布一条消息。有人能举个例子说明如何做到这一点吗?你有没有试过谷歌? 从我们得到的 编辑: 这是我的示例项目 EDIT2:最小样本,令牌存储在SharedReferences中(因此您不需要每次都进行授权(我将更新LITest.zip)) EDIT3:已添加异步任务代码。。。要避免NetworkOnMainThreadException:) AndroidManifest.xml: <?xml version="1.0" encod

我想将我的Android应用程序与LinkedIn集成并发布一条消息。有人能举个例子说明如何做到这一点吗?

你有没有试过谷歌? 从我们得到的

编辑: 这是我的示例项目

EDIT2:最小样本,令牌存储在SharedReferences中(因此您不需要每次都进行授权(我将更新LITest.zip))

EDIT3:已添加异步任务代码。。。要避免NetworkOnMainThreadException:)

AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pl.selvin.android.LinkedInTest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="4" />

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

    <application android:label="LinkedInTest" >
        <activity
            android:name=".LITestActivity"
            android:label="LinkedIn Test"
            android:launchMode="singleInstance" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
            <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>
    </application>

</manifest>

LiteStativity.java:

package pl.selvin.android.LinkedInTest;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;

import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;

public class LITestActivity extends Activity {

    // /change keysssssssssssssssssssssssssssss!!!!!!!!!!

    static final String CONSUMER_KEY = "keykeykeykey";
    static final String CONSUMER_SECRET = "secretsecret";

    static final String APP_NAME = "LITest";
    static final String OAUTH_CALLBACK_SCHEME = "x-oauthflow-linkedin";
    static final String OAUTH_CALLBACK_HOST = "litestcalback";
    static final String OAUTH_CALLBACK_URL = String.format("%s://%s",
            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";

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

    static final String OAUTH_PREF = "LIKEDIN_OAUTH";
    static final String PREF_TOKEN = "token";
    static final String PREF_TOKENSECRET = "tokenSecret";
    static final String PREF_REQTOKENSECRET = "requestTokenSecret";

    TextView tv = null;

    @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 {
            showCurrentUser(new LinkedInAccessToken(token, tokenSecret));
        }

    }

    void startAutheniticate() {
        new AsyncTask<Void, Void, LinkedInRequestToken>() {

            @Override
            protected LinkedInRequestToken doInBackground(Void... params) {
                return oAuthService.getOAuthRequestToken(OAUTH_CALLBACK_URL);
            }

            @Override
            protected void onPostExecute(LinkedInRequestToken liToken) {
                final String uri = liToken.getAuthorizationUrl();
                getSharedPreferences(OAUTH_PREF, MODE_PRIVATE)
                        .edit()
                        .putString(PREF_REQTOKENSECRET,
                                liToken.getTokenSecret()).commit();
                Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
                startActivity(i);
            }
        }.execute();
    }

    void finishAuthenticate(final Uri uri) {
        if (uri != null && uri.getScheme().equals(OAUTH_CALLBACK_SCHEME)) {
            final String problem = uri.getQueryParameter(OAUTH_QUERY_PROBLEM);
            if (problem == null) {

                new AsyncTask<Void, Void, LinkedInAccessToken>() {

                    @Override
                    protected LinkedInAccessToken doInBackground(Void... params) {
                        final SharedPreferences pref = getSharedPreferences(
                                OAUTH_PREF, MODE_PRIVATE);
                        final LinkedInAccessToken accessToken = oAuthService
                                .getOAuthAccessToken(
                                        new LinkedInRequestToken(
                                                uri.getQueryParameter(OAUTH_QUERY_TOKEN),
                                                pref.getString(
                                                        PREF_REQTOKENSECRET,
                                                        null)),
                                        uri.getQueryParameter(OAUTH_QUERY_VERIFIER));
                        pref.edit()
                                .putString(PREF_TOKEN, accessToken.getToken())
                                .putString(PREF_TOKENSECRET,
                                        accessToken.getTokenSecret())
                                .remove(PREF_REQTOKENSECRET).commit();
                        return accessToken;
                    }

                    @Override
                    protected void onPostExecute(LinkedInAccessToken accessToken) {
                        showCurrentUser(accessToken);
                    }
                }.execute();

            } else {
                Toast.makeText(this,
                        "Appliaction down due OAuth problem: " + problem,
                        Toast.LENGTH_LONG).show();
                finish();
            }

        }
    }

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

    void showCurrentUser(final LinkedInAccessToken accessToken) {
        final LinkedInApiClient client = factory
                .createLinkedInApiClient(accessToken);

        new AsyncTask<Void, Void, Object>() {

            @Override
            protected Object doInBackground(Void... params) {
                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 pass it to onPostExecute)
                    // /////////////////////////////////////////////////////////
                    return p;
                } catch (LinkedInApiClientException ex) {
                    return ex;
                }
            }

            @Override
            protected void onPostExecute(Object result) {
                if (result instanceof Exception) {
                    //result is an Exception :) 
                    final Exception ex = (Exception) result;
                    clearTokens();
                    Toast.makeText(
                            LITestActivity.this,
                            "Appliaction down due LinkedInApiClientException: "
                                    + ex.getMessage()
                                    + " Authokens cleared - try run application again.",
                            Toast.LENGTH_LONG).show();
                    finish();
                } else if (result instanceof Person) {
                    final Person p = (Person) result;
                    tv.setText(p.getLastName() + ", " + p.getFirstName());
                }
            }
        }.execute();

    }

    @Override
    protected void onNewIntent(Intent intent) {
        finishAuthenticate(intent.getData());
    }
}
包pl.selvin.android.linkedinstest;
导入android.app.Activity;
导入android.content.Intent;
导入android.content.SharedReferences;
导入android.net.Uri;
导入android.os.AsyncTask;
导入android.os.Bundle;
导入android.widget.TextView;
导入android.widget.Toast;
导入com.google.code.linkedinapi.client.LinkedInApiClient;
导入com.google.code.linkedinapi.client.LinkedInApiClientException;
导入com.google.code.linkedinapi.client.LinkedInApiClientFactory;
导入com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
导入com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
导入com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
导入com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
导入com.google.code.linkedinapi.schema.Person;
公共类LiteStativity扩展了活动{
///更换钥匙SSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSSS!!!!!!!!!!
静态最终字符串使用者\u KEY=“keykey”;
静态最终字符串使用者\u SECRET=“secretsecret”;
静态最终字符串APP_NAME=“LITest”;
静态最终字符串OAUTH_CALLBACK_SCHEME=“x-oauthflow-linkedin”;
静态最终字符串OAUTH\u CALLBACK\u HOST=“litestcalback”;
静态最终字符串OAUTH\u CALLBACK\u URL=String.format(“%s://%s”,
OAUTH_回调_方案,OAUTH_回调_主机);
静态最终字符串OAUTH\u QUERY\u TOKEN=“OAUTH\u TOKEN”;
静态最终字符串OAUTH\u QUERY\u VERIFIER=“OAUTH\u VERIFIER”;
静态最终字符串OAUTH\u QUERY\u PROBLEM=“OAUTH\u PROBLEM”;
最终LinkedInOAuthService oAuthService=LinkedInOAuthServiceFactory
.getInstance().createLinkedInOAuthService(使用者密钥,
消费者(保密),;
最终LinkedInApiClientFactory工厂=LinkedInApiClientFactory
.newInstance(使用者密钥、使用者密钥);
静态最终字符串OAUTH_PREF=“LIKEDIN_OAUTH”;
静态最终字符串PREF_TOKEN=“TOKEN”;
静态最终字符串PREF_TOKENSECRET=“TOKENSECRET”;
静态最终字符串PREF_REQTOKENSECRET=“requestTokenSecret”;
TextView tv=null;
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
tv=新文本视图(此);
设置内容视图(电视);
final SharedReferences pref=GetSharedReferences(OAUTH_pref,
模式(私人),;
最终字符串标记=pref.getString(pref_标记,null);
最终字符串tokenSecret=pref.getString(pref_tokenSecret,null);
if(token==null | | tokenSecret==null){
startAutheniticate();
}否则{
showCurrentUser(新LinkedInAccessToken(token,tokenSecret));
}
}
void startAutheniticate(){
新建异步任务(){
@凌驾
受保护的LinkedInRequestToken doInBackground(无效…参数){
返回oAuthService.getOAuthRequestToken(OAUTH_回调_URL);
}
@凌驾
PostExecute上受保护的void(LinkedInRequestToken liToken){
最后一个字符串uri=liToken.getAuthorizationUrl();
GetSharedReferences(OAUTH\u PREF,MODE\u PRIVATE)
.edit()
.putString(PREF_),
liToken.getTokenCret()).commit();
Intent i=新的Intent(Intent.ACTION_视图,Uri.parse(Uri));
星触觉(i);
}
}.execute();
}
void finishAuthenticate(最终Uri){
if(uri!=null&&uri.getScheme().equals(OAUTH\u CALLBACK\u SCHEME)){
最后一个字符串问题=uri.getQueryParameter(OAUTH\u QUERY\u问题);
如果(问题==null){
新建异步任务(){
@凌驾
受保护的LinkedInAccessToken doInBackground(无效…参数){
最终SharedReferences pref=GetSharedReferences(
OAUTH_PREF,MODE_PRIVATE);
最终LinkedInAccessToken=oAuthService
.getOAuthAccessToken(
新LinkedInRequestToken(
getQueryParameter(OAUTH\u查询\u令牌),
pref.getString(
PREF_REQTOKENSECRET,
空),
getQueryParameter(OAUTH_QUERY_VERIFIER));
pref.edit()
.putString(PREF_标记,accessToken.getToken())
.putString(PREF_TOKENSECRET,
accessToken.getTokenCret())
.remove(PREF_REQTOKENSECRET).commit();
返回accessToken;
}
@凌驾
受保护的void onPostExecute(LinkedInAccessToken accessToken){
showCurrentUser(accessToken);
}
}.execute();
}否则{
烤面包
package com.package.my;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Looper;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.google.code.linkedinapi.client.LinkedInApiClient;
import com.google.code.linkedinapi.client.LinkedInApiClientException;
import com.google.code.linkedinapi.client.LinkedInApiClientFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInAccessToken;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthService;
import com.google.code.linkedinapi.client.oauth.LinkedInOAuthServiceFactory;
import com.google.code.linkedinapi.client.oauth.LinkedInRequestToken;
import com.google.code.linkedinapi.schema.Person;

public class your_class_name extends Activity {
    public static final String CONSUMER_KEY             = "your_app_key";
    public static final String CONSUMER_SECRET          = "your_app_secret";    
    public static final String APP_NAME                 = "your app name";
    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
}//end class