原文: www blogs /and_he/archive/2011/05/23/2054494.html
转载留在以后参考~~
关于twitter这一块,自发这篇博文之后有很多人问我,有的验证成功了不跳转,或者其它原因什么的,我看了一下,这篇博文里面有写呀,下面以红色粗体文字注明一下
刚进公司,叫我先学习twitter和facebook,就类似于国内的微博,或者分享功能,点击某个按钮,出来一个提示框,可以分享到某些地方,这里实现的就是分享到twitter,当然得要使用代理,因为这是给老外做的,所以得符合他们的习惯
先说一下实现的功能吧,首先运行的时候,会检查是否登陆twitter(通过sharedpreference文件保存登陆状态),如果没有登陆的话会跳转到twitter的登陆认证页面,提示用户输入用户名和密码,这些就是oauth认证的步骤,不懂的看这儿 www blogs /and_he/archive/2011/05/22/2053477.html
做过新浪微博的都应该知道,首先要申请成为开发者,创建自己的应用,然后会给你一些比如consumer key和consumer secret之类的东西,这些东西要先记下来,代码里面要用到的,其余的不啰嗦了,只是要注意一点,创建twitter应用的时候造成不能忘了填那个callback url,我当初就没填,结果整了几天都整不出来结果,也算是我的一点经验吧,下面贴代码,以便于以后查阅
首先我们要用到twitter封闭好的一些包,这里用到两个twitter4j-core-android和twitter4j-media-support-android,百度一下就出来了
以下是工程目录结构
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
=
"
api.twitter /oauth/request_token
"
;
public
static
final
string access_token_url
=
"
api.twitter /oauth/access_token
"
;
public
static
final
string callback_url
=
"
api.twitter /oauth/authorize
"
;
public
static
final
string twitpic_api_key
=
"
a77709ebb6c51de0e77f723751a5f9a4
"
; }
下面是twitter类(主类)
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
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类
package
com.twitter;
import
java.io.ioexception;
import
java.io.inputstream;
import
java .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.getauthentication
"
&force_login=true
"
; }
catch
(twitterexception e) { e.printstacktrace();
return
"
baidu
"
; }
//
已经得到临时访问令牌
//
request token=7hmpofnr5ev1kjcw036mdi1hpvycbb1srkkk3r6ax30
//
request token secret=fahibfx04lbqhme392hth1lgl8hqxm2p0ij5kzlofk
//
url=
api.twitter /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
; 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.load;
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=
api.twitter /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()) .getprofileimage.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 mit(); 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.load;
//
载入网页
}
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); } }
join the conversation! twitter is your go-to social networking app and the source for what's happening in the world. from world news to local news, entertainment to sports and gaming, politics to fun stories that go viral, when it happens in the world, it happens on twitter first. find friends or follow influential people - every voice can impact the world! join over 2 billion users worldwide!
tweet, retweet, reply to tweets, share or like - twitter is easy to use
chat privately or go big and initiate a group conversation with anyone who follows you. track your friends & other twitter followers or follow your favorite celebrity alongside hundreds of interesting twitter users, to read their content at a glance. engage your social network with noteworthy links, photos and videos. discover which of your tweets were liked or retweeted.
create your free twitter account today!
twitter allows you to find interesting people or build a following of people who are interested in you. maintaining a social connection has never been easier!twitter allows celebs to build a personal connection with their fans. this is why twitter has become one of the most used social media platforms in the world.
build an engaging profile
customize your profile, add a photo, description, location, and background photo
tweet often and optimize your posting times
post visual content
use hashtags in your tweets
draw in followers outside of twitter
know what’s trending now
discover top trending hashtags and breaking news headlines. whether you’re interested in sports highlights, pop culture and entertainment or politics, twitter is your source of information.
live streaming events
join the conversation or watch live videos to deeply engage with large audiences directly from your mobile device. go live, create your own live streaming events, share videos or sit back and watch events from around the world.
privacy policy: twitter /en/privacy
terms and conditions: twitter /en/tos
?
twitter曾经举行了自己四年以来的第一场开发者大会。而这场名为“flight”的大会,也是以后它的年度惯例。
这次大会的主题也完全围绕开发者进行。大会的焦点是一个名叫fabric的新sdk,里面包括三个开发者工具包:面向twitter本身的 twitter kit、面向twitter广告网络的mopub,以及基于twitter 2013年收购的移动应用崩溃分析工具crashlytics的crashlytics kit。
我还是先贴上twitter登录的官方网站: dev.twitter /twitterkit/android/log-in-with-twitter,不过都是英文,当然,我们还需要爬过一堵墙才能够上网。
首先我们要先去注册twitter开发者账号,并且创建应用, apps.twitter .
点击右上角创建应用:
然后会进入下图:
我们需要填入应用的名称,还有应用的描述,至于website,下面解释的意思大概是:您的应用程序的可公开访问的8797威尼斯老品牌主页,用户可以下载,使用或查找有关您的应用程序的更多信息。该完全限定的url用于源应用程序创建的tweets,并将显示在面向用户的授权屏幕中。 (如果你还没有url,只需在这里放置一个占位符,但记住稍后再改变它。)
?
?
应用创建完成之后,我们可以进入应用查看相关的设置,点击keys and access tokens,可以看到consumer key (api key)和consumer secret (api secret),这两个需要用到
?
好了,创建应用就到这里,接下来讲讲如何集成到我们的项目:
(一)首先我们要集成twitter相关的sdk,8797威尼斯老品牌官网上写得比较多,如果仅仅需要登录功能,那么就只需要
在build.gradle(app)里面写上
dependencies {
compile 'com.twitter.sdk.android:twitter-core:3.1.1'
}
在build.gradle(project)的?repositories里写上
repositories {
jcenter()
}
(二)在我们的资源文件里面添加api key,这个api key在twitter的应用管理可以看到,就是我们上面说的那两个
?
(三)建立一个自定义的application,在oncreate()方法里面初始化
twitter.initialize(this);
twitterconfig config = new twitterconfig.builder(this)
.logger(new defaultlogger(log.debug))
.twitterauthconfig(new twitterauthconfig("consumer_key", "consumer_secret"))
.debug(true)
.build();
twitter.initialize(config);
?
(四)我们可以用twitter提供好的登录按钮,当然也可以自定义,接下来会讲。
android:id="@ id/login_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
?
(五)在代码中:
loginbutton = (twitterloginbutton) findviewbyid(r.id.login_button);
loginbutton.setcallback(new callback
@override
public void success(result
// do something with result, which provides a twittersession for making api calls
result里面包含了用户的信息,我们可以从中取出token,tokensecret (如果我们有自己的后台服务器,发送这两个到我们自己的后台,后台再去验证)
twitterauthtoken authtoken = result.data.getauthtoken(); string token = authtoken.token;
string appid = getresources().getstring(r.string.twitter_app_id); string tokensecret = authtoken.secret;
}
@override public void failure(twitterexception exception) { // do something on failure } });
@override
protected void onactivityresult(int requestcode, int resultcode, intent data) { super.onactivityresult(requestcode, resultcode, data); // pass the activity result to the login button. loginbutton.onactivityresult(requestcode, resultcode, data); }
?
?如果登录按钮是在fragment中的话,那么onactivityresult应该用如下代码:
应该
@override
protected void onactivityresult(int requestcode, int resultcode, intent data) {
super.onactivityresult(requestcode, resultcode, data);
// pass the activity result to the fragment, which will then pass the result to the login
// button.
fragment fragment = getfragmentmanager().findfragmentbyid(r.id.your_fragment_id);
if (fragment != null) {
fragment.onactivityresult(requestcode, resultcode, data);
}
}
其余的可以参考8797威尼斯老品牌官网
?
接下来讲的一个是自定义登录按钮,其实有一个妙计,请看下面界面代码:
android:id="@ id/framelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@ id/facebook"
android:layout_margintop="@dimen/login_button_margin_bottom"
android:layout_centerhorizontal="true">
android:id="@ id/login_button"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_height"
android:layout_margintop="@dimen/button_margin_bottom"
android:visibility="gone"/>
android:id="@ id/login_image"
android:layout_width="@dimen/button_width"
android:layout_height="@dimen/button_height"
android:src="@drawable/twitter" />
然后代码中:
@override
public void onclick(view view) {
switch (view.getid()){case r.id.login_image:
loginbutton.performclick();
break;
default:
break;
}
}
即,点击我们自定义的按钮的时候,让twitter登录按钮执行点击操作。
先到这里,以后慢慢补充。
?转载请标明出处: www blogs /tangzh/p/8206569.html
转载于: www blogs /tangzh/p/8206569.html
还没有评论,来说两句吧...