1、項目概況
該項目文件列表如下:
其AndroidManifest.xml文件內容爲:
- <?xml version="1.0" encoding="utf-8"?>
- <manifest xmlns:android="http://schemas.android.com/apk/res/android"
- package="cn.com.hh.view"
- android:versionCode="1"
- android:versionName="1.0">
- <application android:icon="@drawable/icon" android:label="@string/app_name"
- android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
- <!-- 主Activity -->
- <activity android:name="cn.com.hh.view.MyBlogActivity"
- android:label="@string/app_name">
- <intent-filter>
- <action android:name="android.intent.action.MAIN" />
- <category android:name="android.intent.category.LAUNCHER" />
- </intent-filter>
- </activity>
- <!-- 註冊 授權登錄Activity -->
- <activity android:name="cn.com.hh.view.AuthorizeActivity" android:launchMode="singleTask">
- <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:scheme="myapp" android:host="AuthorizeActivity" />
- </intent-filter>
- </activity>
- <!-- 註冊登錄Activity -->
- <activity android:name="cn.com.hh.view.LoginActivity" >
- <!-- <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:scheme="myapp" android:host="AuthorizeActivity" />-->
- <!-- </intent-filter>-->
- </activity>
- <!-- 註冊登錄Activity -->
- <activity android:name="cn.com.hh.view.HomeActivity" >
- </activity>
- <!-- 註冊登錄Activity -->
- <activity android:name="cn.com.hh.view.ViewActivity" >
- </activity>
- </application>
- <uses-permission android:name="android.permission.INTERNET" />
- </manifest>
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="cn.com.hh.view"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen">
<!-- 主Activity -->
<activity android:name="cn.com.hh.view.MyBlogActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<!-- 註冊 授權登錄Activity -->
<activity android:name="cn.com.hh.view.AuthorizeActivity" android:launchMode="singleTask">
<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:scheme="myapp" android:host="AuthorizeActivity" />
</intent-filter>
</activity>
<!-- 註冊登錄Activity -->
<activity android:name="cn.com.hh.view.LoginActivity" >
<!-- <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:scheme="myapp" android:host="AuthorizeActivity" />-->
<!-- </intent-filter>-->
</activity>
<!-- 註冊登錄Activity -->
<activity android:name="cn.com.hh.view.HomeActivity" >
</activity>
<!-- 註冊登錄Activity -->
<activity android:name="cn.com.hh.view.ViewActivity" >
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
2、oauth2認證
說說關於OAuth授權認證的事情,新浪開放api都必須在這個基礎上才能調用,所以有必要專門來講講,前面的文章中已經提到過關於新浪微博提供了OAuth和Base OAuth兩種認證方式,並且本項目採用OAuth認證方式,至於爲什麼採用這個OAuth認證而不採用Base OAuth認證原因很簡單,自從Twitter只支持OAuth認證方式以來,各大應用都紛紛轉向OAuth認證方式,而新浪微博的開放平臺也將在近日停止Base OAuth的認證方式。
OAuth的基本概念,OAUTH協議爲用戶資源的授權提供了一個安全的、開放而又簡易的標準。與以往的授權方式不同之處是OAUTH的授權不會使第三方觸及到用戶的帳號信息(如用戶名與密碼),即第三方無需使用用戶的用戶名與密碼就可以申請獲得該用戶資源的授權,因此OAUTH是安全的。同樣新浪微博提供OAuth認證也是爲了保證用戶賬號和密碼的安全,在這裏通過OAuth建立普通新浪微博用戶、客戶端程序(我們正在開發的這個android客戶端程序)、新浪微博三者之間的相互信任關係,讓客戶端程序(我們正在開發的這個android客戶端程序)不需要知道用戶的賬號和密碼也能瀏覽、發佈微博,這樣有效的保護了用戶賬號的安全性不需要把賬號密碼透露給客戶端程序又達到了通過客戶端程序寫微博看微博目的。這個是OAuth的作用。
結合新浪微博的OAuth認證來說說具體的功能實現,首先羅列一下關鍵字組,下面四組關鍵字跟我們接下來OAuth認證有非常大的關係。
第一組:(App Key和App Secret),這組參數就是本系列文本第一篇提到的建一個新的應用獲取App Key和App Secret。
第二組:(Request Token和Request Secret)
第三組:(oauth_verifier)
第四組:(user_id、Access Token和Access Secret)
新浪微博的OAuth認證過程,當用戶第一次使用本客戶端軟件時,客戶端程序用第一組作爲參數向新浪微博發起請求,然後新浪微博經過驗證後返回第二組參數給客戶端軟件同時表示新浪微博信任本客戶端軟件,當客戶端軟件獲取第二組參數時作爲參數引導用戶瀏覽器跳至新浪微博的授權頁面,然後用戶在新浪的這個授權頁面裏輸入自己的微博賬號和密碼進行授權,完成授權後根據客戶端設定的回調地址把第三組參數返回給客戶端軟件並表示用戶也信任本客戶端軟件,接下客戶端軟件把第二組參數和第三組參數作爲參數再次向新浪微博發起請求,然後新浪微博返回第四組參數給客戶端軟件,第四組參數需要好好的保存起來這個就是用來代替用戶的新浪賬號和密碼用的,在後面調用api時都需要。從這個過程來看用戶只是在新浪微博的認證網頁輸入過賬戶和密碼並沒有在客戶端軟件裏輸入過賬戶和密碼,客戶端軟件只保存了第四組數據並沒有保存用戶的賬戶和密碼,這樣有效的避免了賬戶和密碼透露給新浪微博之外的第三方應用程序,保證
了安全性。
本項目用爲了方便開發採用了oauth-signpost開源項目進行OAuth認證開發,新建OAuth.java類文件對OA進行簡單的封裝,OAuth類主要有RequestAccessToken、GetAccessToken、SignRequest三個方法,第一個方法RequestAccessToken就是上面過程中用來獲取第三組參數用的,GetAccessToken方法是用來獲取第四組參數用,SignRequest方法是用來調用api用。由於採用了oauth-signpost開源項目簡單了很多。具體代碼如下:
- public class OAuth {
- private CommonsHttpOAuthConsumer httpOauthConsumer;
- private OAuthProvider httpOauthprovider;
- public String consumerKey;
- public String consumerSecret;
- public OAuth()
- {
- // 第一組:(App Key和App Secret)
- // 這組參數就是本系列文本第一篇提到的建一個新的應用獲取App Key和App Secret。
- this("3315495489","e2731e7grf592c0fd7fea32406f86e1b");
- }
- public OAuth(String consumerKey,String consumerSecret)
- {
- this.consumerKey=consumerKey;
- this.consumerSecret=consumerSecret;
- }
- public Boolean RequestAccessToken(Activity activity,String callBackUrl){
- Boolean ret=false;
- try{
- httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
- httpOauthprovider = new DefaultOAuthProvider("http://api.t.sina.com.cn/oauth/request_token","http://api.t.sina.com.cn/oauth/access_token","http://api.t.sina.com.cn/oauth/authorize");
- String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, callBackUrl);
- activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
- ret=true;
- }catch(Exception e){
- }
- return ret;
- }
- public UserInfo GetAccessToken(Intent intent){
- UserInfo user=null;
- Uri uri = intent.getData();
- String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
- try {
- httpOauthprovider.setOAuth10a(true);
- httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
- } catch (OAuthMessageSignerException ex) {
- ex.printStackTrace();
- } catch (OAuthNotAuthorizedException ex) {
- ex.printStackTrace();
- } catch (OAuthExpectationFailedException ex) {
- ex.printStackTrace();
- } catch (OAuthCommunicationException ex) {
- ex.printStackTrace();
- }
- SortedSet<String> user_id= httpOauthprovider.getResponseParameters().get("user_id");
- String userId=user_id.first();
- String userKey = httpOauthConsumer.getToken();
- String userSecret = httpOauthConsumer.getTokenSecret();
- user=new UserInfo();
- user.setUserId(userId);
- user.setToken(userKey);
- user.setTokenSecret(userSecret);
- return user;
- }
- public HttpResponse SignRequest(String token,String tokenSecret,String url,List params)
- {
- HttpPost post = new HttpPost(url);
- //HttpClient httpClient = null;
- try{
- post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
- } catch (UnsupportedEncodingException e) {
- e.printStackTrace();
- }
- //關閉Expect:100-Continue握手
- //100-Continue握手需謹慎使用,因爲遇到不支持HTTP/1.1協議的服務器或者代理時會引起問題
- post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
- return SignRequest(token,tokenSecret,post);
- }
- public HttpResponse SignRequest(String token,String tokenSecret,HttpPost post){
- httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
- httpOauthConsumer.setTokenWithSecret(token,tokenSecret);
- HttpResponse response = null;
- try {
- httpOauthConsumer.sign(post);
- } catch (OAuthMessageSignerException e) {
- e.printStackTrace();
- } catch (OAuthExpectationFailedException e) {
- e.printStackTrace();
- } catch (OAuthCommunicationException e) {
- e.printStackTrace();
- }
- //取得HTTP response
- try {
- response = new DefaultHttpClient().execute(post);
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return response;
- }
- }
public class OAuth {
private CommonsHttpOAuthConsumer httpOauthConsumer;
private OAuthProvider httpOauthprovider;
public String consumerKey;
public String consumerSecret;
public OAuth()
{
// 第一組:(App Key和App Secret)
// 這組參數就是本系列文本第一篇提到的建一個新的應用獲取App Key和App Secret。
this("3315495489","e2731e7grf592c0fd7fea32406f86e1b");
}
public OAuth(String consumerKey,String consumerSecret)
{
this.consumerKey=consumerKey;
this.consumerSecret=consumerSecret;
}
public Boolean RequestAccessToken(Activity activity,String callBackUrl){
Boolean ret=false;
try{
httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
httpOauthprovider = new DefaultOAuthProvider("http://api.t.sina.com.cn/oauth/request_token","http://api.t.sina.com.cn/oauth/access_token","http://api.t.sina.com.cn/oauth/authorize");
String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, callBackUrl);
activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
ret=true;
}catch(Exception e){
}
return ret;
}
public UserInfo GetAccessToken(Intent intent){
UserInfo user=null;
Uri uri = intent.getData();
String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);
try {
httpOauthprovider.setOAuth10a(true);
httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);
} catch (OAuthMessageSignerException ex) {
ex.printStackTrace();
} catch (OAuthNotAuthorizedException ex) {
ex.printStackTrace();
} catch (OAuthExpectationFailedException ex) {
ex.printStackTrace();
} catch (OAuthCommunicationException ex) {
ex.printStackTrace();
}
SortedSet<String> user_id= httpOauthprovider.getResponseParameters().get("user_id");
String userId=user_id.first();
String userKey = httpOauthConsumer.getToken();
String userSecret = httpOauthConsumer.getTokenSecret();
user=new UserInfo();
user.setUserId(userId);
user.setToken(userKey);
user.setTokenSecret(userSecret);
return user;
}
public HttpResponse SignRequest(String token,String tokenSecret,String url,List params)
{
HttpPost post = new HttpPost(url);
//HttpClient httpClient = null;
try{
post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//關閉Expect:100-Continue握手
//100-Continue握手需謹慎使用,因爲遇到不支持HTTP/1.1協議的服務器或者代理時會引起問題
post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
return SignRequest(token,tokenSecret,post);
}
public HttpResponse SignRequest(String token,String tokenSecret,HttpPost post){
httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);
httpOauthConsumer.setTokenWithSecret(token,tokenSecret);
HttpResponse response = null;
try {
httpOauthConsumer.sign(post);
} catch (OAuthMessageSignerException e) {
e.printStackTrace();
} catch (OAuthExpectationFailedException e) {
e.printStackTrace();
} catch (OAuthCommunicationException e) {
e.printStackTrace();
}
//取得HTTP response
try {
response = new DefaultHttpClient().execute(post);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
2、認證界面
根據上文的介紹,我們知道,需要獲得用戶的授權纔可以獲得對該用戶新浪微博的操作權限,在項目中對此是這樣處理的。其界面如下:
用戶進入應用以後,會轉到是否對新浪微博進行授權界面,點擊“開始”後啓動瀏覽器進入新浪微博授權界面,該界面是新浪製作的,與本應用無關。用戶輸入賬號和密碼以後,點擊“授權”,進行授權操作。該界面源碼如下:
- public class AuthorizeActivity extends Activity {
- private Dialog dialog;
- private OAuth auth;
- private static final String CallBackUrl = "myapp://AuthorizeActivity";
- @Override
- protected void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.authorize);
- View diaView=View.inflate(this, R.layout.dialog, null);
- dialog = new Dialog(AuthorizeActivity.this,R.style.dialog);
- dialog.setContentView(diaView);
- dialog.show();
- ImageButton stratBtn=(ImageButton)diaView.findViewById(R.id.btn_start);
- stratBtn.setOnClickListener(new OnClickListener(){
- public void onClick(View arg0) {
- auth=new OAuth("30632531","f539cb169860ed99cf8c1861c5da34f6");
- auth.RequestAccessToken(AuthorizeActivity.this, CallBackUrl);
- }
- });
- }
- @Override
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- //在這裏處理獲取返回的oauth_verifier參數
- UserInfo user= auth.GetAccessToken(intent);
- if(user!=null){
- DataHelper helper=new DataHelper(this);
- String uid=user.getUserId();
- if(helper.HaveUserInfo(uid))
- {
- helper.UpdateUserInfo(user);
- Log.e("UserInfo", "update");
- }else
- {
- helper.SaveUserInfo(user);
- Log.e("UserInfo", "add");
- }
- }
- }
- }
public class AuthorizeActivity extends Activity {
private Dialog dialog;
private OAuth auth;
private static final String CallBackUrl = "myapp://AuthorizeActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.authorize);
View diaView=View.inflate(this, R.layout.dialog, null);
dialog = new Dialog(AuthorizeActivity.this,R.style.dialog);
dialog.setContentView(diaView);
dialog.show();
ImageButton stratBtn=(ImageButton)diaView.findViewById(R.id.btn_start);
stratBtn.setOnClickListener(new OnClickListener(){
public void onClick(View arg0) {
auth=new OAuth("30632531","f539cb169860ed99cf8c1861c5da34f6");
auth.RequestAccessToken(AuthorizeActivity.this, CallBackUrl);
}
});
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//在這裏處理獲取返回的oauth_verifier參數
UserInfo user= auth.GetAccessToken(intent);
if(user!=null){
DataHelper helper=new DataHelper(this);
String uid=user.getUserId();
if(helper.HaveUserInfo(uid))
{
helper.UpdateUserInfo(user);
Log.e("UserInfo", "update");
}else
{
helper.SaveUserInfo(user);
Log.e("UserInfo", "add");
}
}
}
}
從該源碼中我們可以發現,在AuthorizeActivity界面,用戶點擊“授權”以後,又重新進入AuthorizeActivity界面(這一步與AndroidManifest.xml文件中AuthorizeActivity項的配置有關),此時會調用onNewIntent接口。
這裏有個地方需要注意,授權成功後重新進入AuthorizeActivity界面,執行onNewIntent函數後並不會自動跳轉到其他界面。這裏需要添加新的跳轉代碼。
3、onNewIntent調用時機
這一部分介紹一下onNewIntent的調用時機。
在IntentActivity中重寫下列方法:onCreate onStart onRestart onResume onPause onStop onDestroy onNewIntent
3.1、其他應用發Intent,執行下列方法:
I/@@@philn(12410): onCreate
I/@@@philn(12410): onStart
I/@@@philn(12410): onResume
發Intent的方法:
Uri uri = Uri.parse("philn://blog.163.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
3.2、接收Intent聲明:
- <activity android:name="cn.com.hh.view.AuthorizeActivity" android:launchMode="singleTask">
- <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:scheme="myapp" android:host="AuthorizeActivity" />
- </intent-filter>
- </activity>
<activity android:name="cn.com.hh.view.AuthorizeActivity" android:launchMode="singleTask">
<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:scheme="myapp" android:host="AuthorizeActivity" />
</intent-filter>
</activity>
3.3、如果IntentActivity處於任務棧的頂端(AndroidManifest.xml配置中的android:launchMode="singleTask" 項),也就是說之前打開過的Activity,現在處於I/@@@philn(12410): onPause
I/@@@philn(12410): onStop 狀態的話
其他應用再發送Intent的話,執行順序爲:
I/@@@philn(12410): onNewIntent
I/@@@philn(12410): onRestart
I/@@@philn(12410): onStart
I/@@@philn(12410): onResume
在Android應用程序開發的時候,從一個Activity啓動另一個Activity並傳遞一些數據到新的Activity上非常簡單,但是當您需要讓後臺運行的Activity回到前臺並傳遞一些數據可能就會存在一點點小問題。
首先,在默認情況下,當您通過Intent啓到一個Activity的時候,就算已經存在一個相同的正在運行的Activity,系統都會創建一個新的Activity實例並顯示出來。爲了不讓Activity實例化多次,我們需要通過在AndroidManifest.xml配置activity的加載方式(launchMode)以實現單任務模式,如下所示:
- <activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">
- </activity>
<activity android:label="@string/app_name" android:launchmode="singleTask"android:name="Activity1">
</activity>
launchMode爲singleTask的時候,通過Intent啓到一個Activity,如果系統已經存在一個實例,系統就會將請求發送到這個實例上,但這個時候,系統就不會再調用通常情況下我們處理請求數據的onCreate方法,而是調用onNewIntent方法,如下所示:- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- setIntent(intent);//must store the new intent unless getIntent() will return the old one
- processExtraData();
- }
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
processExtraData();
}
不要忘記,系統可能會隨時殺掉後臺運行的Activity,如果這一切發生,那麼系統就會調用onCreate方法,而不調用onNewIntent方法,一個好的解決方法就是在onCreate和onNewIntent方法中調用同一個處理數據的方法,如下所示:
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- setContentView(R.layout.main);
- processExtraData();
- }
- protected void onNewIntent(Intent intent) {
- super.onNewIntent(intent);
- setIntent(intent);//must store the new intent unless getIntent() will return the old one
- processExtraData()
- }
- private void processExtraData(){
- Intent intent = getIntent();
- //use the data received here
- }
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
processExtraData();
}
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);//must store the new intent unless getIntent() will return the old one
processExtraData()
}
private void processExtraData(){
Intent intent = getIntent();
//use the data received here
}
4、獲得微博數據
獲得用戶認證後,就可以獲得第四組參數,就可以依次獲得用戶數據了。
在項目中這一步是在HomeActivity界面中完成的,其中獲得微博數據部分函數的源碼如下:
- private void loadList(){
- if(ConfigHelper.nowUser==null)
- {
- }
- else
- {
- user=ConfigHelper.nowUser;
- //顯示當前用戶名稱
- TextView showName=(TextView)findViewById(R.id.showName);
- showName.setText(user.getUserName());
- OAuth auth=new OAuth();
- String url = "http://api.t.sina.com.cn/statuses/friends_timeline.json";
- // String url = "http://api.t.sina.com.cn/statuses/public_timeline.json";
- List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
- params.add(new BasicNameValuePair("source", auth.consumerKey));
- HttpResponse response = auth.SignRequest(user.getToken(), user.getTokenSecret(), url, params);
- if (200 == response.getStatusLine().getStatusCode()){
- try {
- InputStream is = response.getEntity().getContent();
- Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
- StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());
- try {
- char[] tmp = new char[1024];
- int l;
- while ((l = reader.read(tmp)) != -1) {
- buffer.append(tmp, 0, l);
- }
- } finally {
- reader.close();
- }
- String string = buffer.toString();
- //Log.e("json", "rs:" + string);
- ((org.apache.http.HttpResponse) response).getEntity().consumeContent();
- JSONArray data=new JSONArray(string);
- for(int i=0;i<data.length();i++)
- {
- JSONObject d=data.getJSONObject(i);
- //Log.e("json", "rs:" + d.getString("created_at"));
- if(d!=null){
- JSONObject u=d.getJSONObject("user");
- if(d.has("retweeted_status")){
- JSONObject r=d.getJSONObject("retweeted_status");
- }
- //微博id
- String id=d.getString("id");
- String userId=u.getString("id");
- String userName=u.getString("screen_name");
- String userIcon=u.getString("profile_image_url");
- // Log.e("userIcon", userIcon);
- String time=d.getString("created_at");
- String text=d.getString("text");
- Boolean haveImg=false;
- if(d.has("thumbnail_pic")){
- haveImg=true;
- //String thumbnail_pic=d.getString("thumbnail_pic");
- //Log.e("thumbnail_pic", thumbnail_pic);
- }
- Date startDate=new Date(time);
- Date nowDate = Calendar.getInstance().getTime();
- time=new DateUtilsDef().twoDateDistance(startDate,nowDate);
- if(wbList==null){
- wbList=new ArrayList<WeiBoInfo>();
- }
- WeiBoInfo w=new WeiBoInfo();
- w.setId(id);
- w.setUserId(userId);
- w.setUserName(userName);
- w.setTime(time +" 前");
- w.setText(text);
- w.setHaveImage(haveImg);
- w.setUserIcon(userIcon);
- wbList.add(w);
- }
- }
- }catch (IllegalStateException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } catch (JSONException e) {
- e.printStackTrace();
- }
- }
- if(wbList!=null)
- {
- WeiBoAdapater adapater = new WeiBoAdapater();
- ListView Msglist=(ListView)findViewById(R.id.Msglist);
- Msglist.setOnItemClickListener(new OnItemClickListener(){
- public void onItemClick(AdapterView<?> arg0, View view,int arg2, long arg3) {
- Object obj=view.getTag();
- if(obj!=null){
- String id=obj.toString();
- Intent intent = new Intent(HomeActivity.this,ViewActivity.class);
- Bundle b=new Bundle();
- b.putString("key", id);
- intent.putExtras(b);
- startActivity(intent);
- }
- }
- });
- Msglist.setAdapter(adapater);
- }
- }
- loadingLayout.setVisibility(View.GONE);
- }
private void loadList(){
if(ConfigHelper.nowUser==null)
{
}
else
{
user=ConfigHelper.nowUser;
//顯示當前用戶名稱
TextView showName=(TextView)findViewById(R.id.showName);
showName.setText(user.getUserName());
OAuth auth=new OAuth();
String url = "http://api.t.sina.com.cn/statuses/friends_timeline.json";
// String url = "http://api.t.sina.com.cn/statuses/public_timeline.json";
List<BasicNameValuePair> params=new ArrayList<BasicNameValuePair>();
params.add(new BasicNameValuePair("source", auth.consumerKey));
HttpResponse response = auth.SignRequest(user.getToken(), user.getTokenSecret(), url, params);
if (200 == response.getStatusLine().getStatusCode()){
try {
InputStream is = response.getEntity().getContent();
Reader reader = new BufferedReader(new InputStreamReader(is), 4000);
StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());
try {
char[] tmp = new char[1024];
int l;
while ((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
} finally {
reader.close();
}
String string = buffer.toString();
//Log.e("json", "rs:" + string);
((org.apache.http.HttpResponse) response).getEntity().consumeContent();
JSONArray data=new JSONArray(string);
for(int i=0;i<data.length();i++)
{
JSONObject d=data.getJSONObject(i);
//Log.e("json", "rs:" + d.getString("created_at"));
if(d!=null){
JSONObject u=d.getJSONObject("user");
if(d.has("retweeted_status")){
JSONObject r=d.getJSONObject("retweeted_status");
}
//微博id
String id=d.getString("id");
String userId=u.getString("id");
String userName=u.getString("screen_name");
String userIcon=u.getString("profile_image_url");
// Log.e("userIcon", userIcon);
String time=d.getString("created_at");
String text=d.getString("text");
Boolean haveImg=false;
if(d.has("thumbnail_pic")){
haveImg=true;
//String thumbnail_pic=d.getString("thumbnail_pic");
//Log.e("thumbnail_pic", thumbnail_pic);
}
Date startDate=new Date(time);
Date nowDate = Calendar.getInstance().getTime();
time=new DateUtilsDef().twoDateDistance(startDate,nowDate);
if(wbList==null){
wbList=new ArrayList<WeiBoInfo>();
}
WeiBoInfo w=new WeiBoInfo();
w.setId(id);
w.setUserId(userId);
w.setUserName(userName);
w.setTime(time +" 前");
w.setText(text);
w.setHaveImage(haveImg);
w.setUserIcon(userIcon);
wbList.add(w);
}
}
}catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
if(wbList!=null)
{
WeiBoAdapater adapater = new WeiBoAdapater();
ListView Msglist=(ListView)findViewById(R.id.Msglist);
Msglist.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View view,int arg2, long arg3) {
Object obj=view.getTag();
if(obj!=null){
String id=obj.toString();
Intent intent = new Intent(HomeActivity.this,ViewActivity.class);
Bundle b=new Bundle();
b.putString("key", id);
intent.putExtras(b);
startActivity(intent);
}
}
});
Msglist.setAdapter(adapater);
}
}
loadingLayout.setVisibility(View.GONE);
}
其中根據新浪提供的API對用戶數據進行操作。這裏只是獲得用戶所發佈的微博信息,其api爲http://api.t.sina.com.cn/statuses/friends_timeline.json。這裏同時需要提供第四組參數,params.add(new BasicNameValuePair("source", auth.consumerKey));。其返回的數據格式是json需要對其進行解析。