關於Twitter這一塊,自發這篇博文以後有不少人問我,有的驗證成功了不跳轉,或者其它緣由什麼的java
=======我看了一下,這篇博文裏面有寫呀,下面以紅色粗體文字註明一下android
Twitter和Facebook,就相似於國內的微博,或者分享功能,點擊某個按鈕,出來一個提示框,能夠分享到某些地方,這裏實現的就是分享到Twitter,固然得要使用代理,由於這是給老外作的,因此得符合他們的習慣web
先說一下實現的功能吧,首先運行的時候,會檢查是否登錄twitter(經過SharedPreference文件保存登錄狀態),若是沒有登錄的話會跳轉到twitter的登錄認證頁面,提示用戶輸入用戶名和密碼,這些就是OAuth認證的步驟,不懂的看這兒api
http://blog.csdn.net/djy1992/article/details/9378035
app
作過新浪微博的都應該知道,首先要申請成爲開發者,建立本身的應用,而後會給你一些好比Consumer key和Consumer secret之類的東西,這些東西要先記下來,代碼裏面要用到的,其他的不囉嗦了,只是要注意一點,建立Twitter應用的時候千萬不能忘了填那個Callback URL,我當初就沒填,結果整了幾天都整不出來結果,也算是個人一點經驗吧,下面貼代碼,以便於之後查閱ide
首先咱們要用到Twitter封閉好的一些包,這裏用到兩個twitter4j-core-android和twitter4j-media-support-android,百度一下就出來了post
如下是工程目錄結構ui
package
com.twitter;
public
class
CONST {
public
static
final
String CONSUMER_KEY
=
"
IFkj4coaZ9F9Ngfoe1LFuQ
"
;
public
static
final
String CONSUMER_SECRET
=
"
HN2NfE4mtL7OqJaUirWfRnK9XKhyWG2vZmAj6AFwfJ8
"
;
public
static
final
String REQUEST_TOKEN_URL
=
"
https://api.twitter.com/oauth/request_token
"
;
public
static
final
String ACCESS_TOKEN_URL
=
"
https://api.twitter.com/oauth/access_token
"
;
public
static
final
String CALLBACK_URL
=
"
https://api.twitter.com/oauth/authorize
"
;
public
static
final
String TWITPIC_API_KEY
=
"
a77709ebb6c51de0e77f723751a5f9a4
"
;
}
下面是Twitter類(主類)this
package
com.twitter;
import
java.io.IOException;
import
java.io.InputStream;
import
twitter4j.TwitterFactory;
import
twitter4j.conf.ConfigurationBuilder;
import
android.app.Activity;
import
android.app.ProgressDialog;
import
android.content.Context;
import
android.content.Intent;
import
android.content.SharedPreferences;
import
android.content.res.AssetManager;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.text.Editable;
import
android.text.TextWatcher;
import
android.util.Log;
import
android.view.View;
import
android.view.Window;
import
android.view.View.OnClickListener;
import
android.widget.Button;
import
android.widget.EditText;
import
android.widget.TextView;
import
android.widget.Toast;
public
class
Twitter
extends
Activity {
EditText et_content;
//
評論內容
EditText et_des;
//
圖片描述
TextView tv_num;
//
剩餘字數
Button btn_send;
//
發送按鈕
int
num
=
140
;
//
定義總字數
ProgressDialog progressDialog;
//
當點擊發送的時候顯示此進度條
SharedPreferences spf;
TwitterConnect tc;
//
定義一個twitter鏈接對象
boolean
connectionStatus
=
false
;
//
定義當前的鏈接狀態爲false
String content;
String describle;
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter);
tc
=
new
TwitterConnect(
this
);
spf
=
getSharedPreferences(
"
bravesoft
"
, Context.MODE_PRIVATE);
et_content
=
(EditText) findViewById(R.id.et_content);
et_des
=
(EditText) findViewById(R.id.et_des);
tv_num
=
(TextView) findViewById(R.id.tv_num);
tv_num.setText(
"
140
"
);
progressDialog
=
new
ProgressDialog(
this
);
progressDialog.setTitle(
"
正在發送...
"
);
progressDialog.setMessage(
"
正在發送,請稍候...
"
);
et_content.addTextChangedListener(
new
TextWatcher() {
private
CharSequence temp;
private
int
selectionStart;
private
int
selectionEnd;
@Override
public
void
onTextChanged(CharSequence s,
int
start,
int
before,
int
count) {
temp
=
s;
//
顯示當前輸入框中的全部內容
}
@Override
public
void
beforeTextChanged(CharSequence s,
int
start,
int
count,
int
after) {
}
@Override
public
void
afterTextChanged(Editable s) {
int
number
=
num
-
s.length();
tv_num.setText(
""
+
number);
selectionStart
=
et_content.getSelectionStart();
selectionEnd
=
et_content.getSelectionEnd();
if
(temp.length()
>
num) {
s.delete(selectionStart
-
1
, selectionEnd);
int
tempSelection
=
selectionStart;
et_content.setText(s);
et_content.setSelection(tempSelection);
//
設置光標在最後
}
}
});
btn_send
=
(Button) findViewById(R.id.btn_send);
connectionStatus
=
spf.getBoolean(
"
connection_tatus
"
,
false
);
btn_send.setOnClickListener(
new
OnClickListener() {
@Override
public
void
onClick(View v) {
content
=
et_content.getText().toString();
//
獲得評論內容
describle
=
et_des.getText().toString();
//
獲得圖片描述內容
if
(connectionStatus) {
//
若是用戶處於登錄狀態,獲取用戶頭像跟name
progressDialog.show();
GetUserInfoTask getUserInfoTask
=
new
GetUserInfoTask();
getUserInfoTask.execute(
""
);
}
}
});
if
(
!
connectionStatus) {
btn_send.setEnabled(
false
);
sendMessage();
}
}
/**
* 若是用戶處於登錄狀態,獲取用戶頭像跟name
*
*
@author
Administrator
*
*/
class
GetUserInfoTask
extends
AsyncTask
<
String, Integer, String
>
{
@Override
protected
String doInBackground(String... params) {
String result
=
""
;
ConfigurationBuilder confBuild
=
new
ConfigurationBuilder();
confBuild.setOAuthConsumerKey(CONST.CONSUMER_KEY);
confBuild.setOAuthConsumerSecret(CONST.CONSUMER_SECRET);
confBuild.setOAuthAccessToken(spf.getString(
"
oauth_token
"
,
""
));
confBuild.setOAuthAccessTokenSecret(spf.getString(
"
oauth_token_secret
"
,
""
));
twitter4j.conf.Configuration config
=
confBuild.build();
if
(TwitterConnect.twitter
!=
null
)
TwitterConnect.twitter.shutdown();
TwitterConnect.twitter
=
new
TwitterFactory(config).getInstance();
InputStream input
=
null
;
try
{
TwitterConnect.accessToken
=
TwitterConnect.twitter
.getOAuthAccessToken();
boolean
bTest
=
false
;
AssetManager am
=
getAssets();
try
{
input
=
am.open(
"
btn_dokusya_toukou.png
"
);
}
catch
(IOException e) {
e.printStackTrace();
}
if
(tc
==
null
) {
tc
=
new
TwitterConnect(Twitter.
this
);
}
bTest
=
tc.TwitterContribute(content, input, describle);
if
(bTest) {
result
=
"
ok
"
;
}
else
{
result
=
"
failure
"
;
}
}
catch
(Exception e) {
}
return
result;
}
@Override
protected
void
onPostExecute(String result) {
super
.onPostExecute(result);
if
(progressDialog.isShowing()) {
progressDialog.dismiss();
}
if
(result.equals(
"
ok
"
)) {
Toast.makeText(Twitter.
this
,
"
發送成功
"
, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(Twitter.
this
,
"
發送失敗
"
, Toast.LENGTH_LONG).show();
}
}
}
public
void
sendMessage() {
new
Send().start();
}
class
Send
extends
Thread {
@Override
public
void
run() {
super
.run();
try
{
Thread.sleep(
3000
);
}
catch
(InterruptedException e) {
e.printStackTrace();
}
Intent intent
=
new
Intent(Twitter.
this
, TwitterLoginBrowser.
class
);
startActivityForResult(intent,
1
);
}
}
@Override
protected
void
onActivityResult(
int
requestCode,
int
resultCode, Intent data) {
super
.onActivityResult(requestCode, resultCode, data);
if
(requestCode
==
1
) {
if
(resultCode
==
1
) {
//
表示從TwitterLoginBrowser返回
connectionStatus
=
spf.getBoolean(
"
connection_tatus
"
,
false
);
if
(connectionStatus) {
btn_send.setEnabled(
true
);
}
}
}
}
}
TwitterConnect類url
package
com.twitter;
import
java.io.IOException;
import
java.io.InputStream;
import
java.net.URL;
import
twitter4j.Status;
import
twitter4j.Twitter;
import
twitter4j.TwitterException;
import
twitter4j.TwitterFactory;
import
twitter4j.auth.AccessToken;
import
twitter4j.auth.RequestToken;
import
twitter4j.conf.Configuration;
import
twitter4j.conf.ConfigurationBuilder;
import
twitter4j.media.ImageUpload;
import
twitter4j.media.ImageUploadFactory;
import
twitter4j.media.MediaProvider;
import
android.content.Context;
import
android.graphics.Bitmap;
import
android.graphics.BitmapFactory;
public
class
TwitterConnect {
Context context;
public
static
Twitter twitter;
public
static
RequestToken requestToken;
public
static
AccessToken accessToken;
public
TwitterConnect(Context context) {
this
.context
=
context;
twitter
=
new
TwitterFactory().getInstance();
}
public
String twitterLoginOAuth() {
twitter.setOAuthConsumer(CONST.CONSUMER_KEY, CONST.CONSUMER_SECRET);
try
{
requestToken
=
twitter.getOAuthRequestToken();
return
requestToken.getAuthenticationURL()
+
"
&force_login=true
"
;
}
catch
(TwitterException e) {
e.printStackTrace();
return
"
http://www.baidu.com
"
;
}
//
已經獲得臨時訪問令牌
//
Request token=7HMpOfNr5ev1kjcW036mDI1hpvycbb1sRkKK3r6Ax30
//
Request token secret=FAhiBFX04lbQhme392htH1LgL8hQxm2p0IJ5Kzlofk
//
url=
http://api.twitter.com/oauth/authenticate?oauth_token=svrKsiu1ArJ7h24RvHPHeNnzfXqLIebRY7uefydmB9k
}
//
獲得用戶名
public
String getUserName() {
try
{
return
twitter.showUser(accessToken.getUserId()).getName();
}
catch
(Exception e) {
return
""
;
}
}
//
獲得用戶頭像
public
Bitmap getUserImage(String userImageUrl) {
Bitmap image
=
null
;
try
{
URL url
=
new
URL(userImageUrl);
image
=
BitmapFactory.decodeStream(url.openStream());
}
catch
(Exception e) {
e.printStackTrace();
}
return
image;
}
/**
*
*
@param
text
* 評論內容
*
@param
input
* 圖片的一個InputStream
*
@param
description
* 圖片描述
*
@return
*/
public
boolean
TwitterContribute(String text, InputStream input,
String description) {
boolean
isOk
=
false
;
Configuration config
=
null
;
ImageUpload uploads
=
null
;
try
{
Status status
=
null
;
if
(input
!=
null
) {
if
(config
==
null
) {
ConfigurationBuilder confBuild
=
new
ConfigurationBuilder();
confBuild.setOAuthConsumerKey(CONST.CONSUMER_KEY);
confBuild.setOAuthConsumerSecret(CONST.CONSUMER_SECRET);
confBuild.setOAuthAccessToken(accessToken.getToken());
confBuild.setOAuthAccessTokenSecret(accessToken
.getTokenSecret());
confBuild.setMediaProviderAPIKey(CONST.TWITPIC_API_KEY);
//
發送圖片和對圖片的描述
config
=
confBuild.build();
uploads
=
new
ImageUploadFactory(config)
.getInstance(MediaProvider.TWITPIC);
}
String uploadre
=
""
;
uploadre
=
uploads.upload(
"
"
, input, description);
System.out.println(
"
uploadre
"
+
uploadre);
if
(input
!=
null
)
try
{
input.close();
}
catch
(IOException e) {
}
if
(
!
uploadre.equals(
""
)) {
status
=
twitter.updateStatus(text
+
"
"
+
uploadre);
System.out.println(
"
uploadre=
"
+
uploadre);
}
}
else
{
status
=
twitter.updateStatus(text);
}
if
(status
!=
null
) {
System.out.println(
"
發表內容:
"
+
status.getText());
isOk
=
true
;
}
}
catch
(Exception e) {
isOk
=
false
;
}
return
isOk;
}
}
TwitterLoginBrowser類
package
com.twitter;
import
twitter4j.TwitterException;
import
android.app.Activity;
import
android.app.ProgressDialog;
import
android.content.Context;
import
android.content.Intent;
import
android.content.SharedPreferences;
import
android.content.SharedPreferences.Editor;
import
android.graphics.Bitmap;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.view.KeyEvent;
import
android.view.Window;
import
android.webkit.WebChromeClient;
import
android.webkit.WebView;
import
android.webkit.WebViewClient;
import
android.widget.Toast;
public
class
TwitterLoginBrowser
extends
Activity {
WebView webview;
ProgressDialog progressDialog;
//
定義一個進度條
TwitterConnect tc;
String authenticateUrl
=
""
;
ConnectTask task;
String oauthToken;
String oauthVerifier;
Bitmap userImage;
//
用戶頭像
@Override
protected
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.twitter_loginbrowser);
progressDialog
=
new
ProgressDialog(TwitterLoginBrowser.
this
);
progressDialog.setTitle(
"
請等待
"
);
progressDialog.setMessage(
"
正在加載頁面,請稍等...
"
);
progressDialog.show();
//
啓動的時候就讓它顯示
webview
=
(WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(
true
);
webview.requestFocus();
tc
=
new
TwitterConnect(
this
);
task
=
new
ConnectTask(
this
);
task.execute(
"
login
"
);
//
執行載入頁面任務
webview.setWebViewClient(
new
WebViewClient() {
@Override
public
boolean
shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return
true
;
}
@Override
public
void
onPageStarted(WebView view, String url, Bitmap favicon) {
super
.onPageStarted(view, url, favicon);
System.out.println(
"
開始加載頁面:
"
+
url);
}
//
頁面載入完成
@Override
public
void
onPageFinished(WebView view, String url) {
super
.onPageFinished(view, url);
//
url=
https://api.twitter.com/oauth/authorize?oauth_token=9kpqNY7VhmyWC5NRXF2eQ73zN4VKXjQcgZj62sIZU
&oauth_verifier=3B7FBAs9XOYH8I3QEQrFGuqJlgMUfQH5fzmz7j3Ws
Toast.makeText(TwitterLoginBrowser.
this
,
"
頁面加載完成
"
,
Toast.LENGTH_LONG).show();
if
(url
!=
null
&&
url.startsWith(CONST.CALLBACK_URL)) {
String[] param
=
url.split(
"
\\?
"
)[
1
].split(
"
&
"
);
if
(param[
0
].startsWith(
"
oauth_token
"
)) {
oauthToken
=
param[
0
].split(
"
=
"
)[
1
];
}
else
if
(param[
1
].startsWith(
"
oauth_token
"
)) {
oauthToken
=
param[
1
].split(
"
=
"
)[
1
];
}
if
(param[
0
].startsWith(
"
oauth_verifier
"
)) {
oauthVerifier
=
param[
0
].split(
"
=
"
)[
1
];
}
else
if
(param[
1
].startsWith(
"
oauth_verifier
"
)) {
oauthVerifier
=
param[
1
].split(
"
=
"
)[
1
];
}
System.out.println(
"
oauthToken=
"
+
oauthToken);
System.out.println(
"
oauthVerifier=
"
+
oauthVerifier);
try
{
TwitterConnect.accessToken
=
TwitterConnect.twitter
.getOAuthAccessToken(
TwitterConnect.requestToken,
oauthVerifier);
WebTask wt
=
new
WebTask();
wt.execute(
""
);
}
catch
(TwitterException e) {
e.printStackTrace();
System.out.println(
"
發生錯誤了
"
);
}
}
}
});
webview.setWebChromeClient(
new
WebChromeClient() {
//
控制進度條的顯示
@Override
public
void
onProgressChanged(WebView view,
int
newProgress) {
super
.onProgressChanged(view, newProgress);
if
(newProgress
!=
100
) {
if
(
!
progressDialog.isShowing()) {
progressDialog.show();
}
}
else
{
if
(progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
}
});
}
//
獲取用戶名和頭像
class
WebTask
extends
AsyncTask
<
String, Integer, String
>
{
@Override
protected
String doInBackground(String... params) {
String result
=
""
;
if
(oauthToken
!=
null
&&
oauthVerifier
!=
null
) {
System.out.println(
"
開始獲取用戶名和頭像
"
);
String userImageUrl
=
""
;
//
用戶頭像url
try
{
userImageUrl
=
TwitterConnect.twitter
.showUser(TwitterConnect.accessToken.getUserId())
.getProfileImageURL().toString();
}
catch
(TwitterException e) {
e.printStackTrace();
}
String userName
=
tc.getUserName();
if
(userImage
!=
null
) {
userImage.recycle();
}
userImage
=
tc.getUserImage(userImageUrl);
//
登錄成功 回到來的畫面
Intent intent
=
new
Intent();
Bundle bundle
=
new
Bundle();
bundle.putParcelable(
"
userImage
"
, userImage);
bundle.putString(
"
userName
"
, userName);
intent.putExtra(
"
userInfo
"
, bundle);
//
保存登錄狀態
SharedPreferences spf
=
getSharedPreferences(
"
bravesoft
"
,
Context.MODE_PRIVATE);
Editor editor
=
spf.edit();
editor.putString(
"
oauth_token
"
,
TwitterConnect.accessToken.getToken());
editor.putString(
"
oauth_token_secret
"
,
TwitterConnect.accessToken.getTokenSecret());
editor.putBoolean(
"
connection_tatus
"
,
true
);
editor.putString(
"
username
"
, userName);
editor.putString(
"
userimgurl
"
, userImageUrl);
editor.commit();
TwitterLoginBrowser.
this
.setResult(
1
, intent);
bundle.clear();
result
=
"
ok
"
;
}
return
result;
}
@Override
protected
void
onPostExecute(String result) {
super
.onPostExecute(result);
if
(result.equals(
"
ok
"
)) {
Toast.makeText(TwitterLoginBrowser.
this
,
"
登錄成功
"
,
Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(TwitterLoginBrowser.
this
,
"
登錄失敗
"
,
Toast.LENGTH_LONG).show();
}
//
TwitterLoginBrowser.this.finish();
}
}
class
ConnectTask
extends
AsyncTask
<
String, Integer, String
>
{
public
ConnectTask(Context context) {
}
@Override
protected
String doInBackground(String... params) {
authenticateUrl
=
tc.twitterLoginOAuth();
return
authenticateUrl;
}
@Override
protected
void
onPostExecute(String result) {
super
.onPostExecute(result);
if
(
!
result.equals(
""
)) {
webview.loadUrl(result);
//
載入網頁
}
else
{
Toast.makeText(TwitterLoginBrowser.
this
,
"
載入錯誤,請重試
"
,
Toast.LENGTH_LONG).show();
TwitterLoginBrowser.
this
.finish();
}
}
}
@Override
public
boolean
onKeyDown(
int
keyCode, KeyEvent event) {
if
(keyCode
==
KeyEvent.KEYCODE_BACK
&&
webview.canGoBack()) {
webview.goBack();
return
true
;
}
return
super
.onKeyDown(keyCode, event); } }