android開發新浪微博客戶端 完整攻略 [新手必讀]

android開發新浪微博客戶端 完整攻略 [新手必讀][轉]2011-04-06  10:49:19
http://www.eoeandroid.com/forum-viewthread-tid-67298-fromuid-106432.html

 

開始接觸學習android已經有3個禮拜了,一直都是對着android的sdk文檔寫Tutorials從Hello World到Notepad Tutorial算是初步入門了吧,剛好最近對微博感興趣就打算開發個android版本的新浪微博客戶端作爲練手項目,並且以隨筆的方式詳細的記錄開發的全過程。本人對java語言以及eclipse Ide都是初次應用基本上屬於邊學邊用,做移動設備上的東西也是第一次,總的來說屬於無基礎、無經驗、無天賦的純三無人員,還請廣大同學們多多給予指點。

  開發第一件事情,那就是開發工具以及環境,我的配置是Eclipse Helios (3.6.1) + Adroid2.2,具體的環境搭建我就不羅嗦了,google一下一大堆,光博客園裏都能搜到很多篇了。

  開發第二件事情,既然是開發新浪的微博客戶端,那就先去新浪申請微博賬號然後登陸後到新浪的開放平臺,新浪的開放平臺提供的新浪微博對外的api接口,在我的應用中創建一個新的應用獲取App Key和App Secret,這2個值後面會有用到先記錄下來。在新浪的開放平臺中提供了開發文檔、SDK、接口測試工具等,本人決定直接通過新浪的Rest Api進行開發並不打算使用新浪提供的SDK,據說新浪提供的java版的SDK並不能直接用來進行android的開發需要進行一定的修改才能使用,只是聽說我沒有試過不一定準確。

  最後在說一下,我準備分爲UI和功能兩部分分別進行說明講解,據我自己的情況大部分的時間都花在的UI的設計和實現上了,編碼倒反而工作量小多了,所以特別把UI部分分出來講。

  最後還要在說一下,很抱歉上面內容基本上屬於廢話沒有什麼實質內容了但是既然是第一篇還是得象徵性的交代一下,從下篇開始講具體的內容。

本軟件設定用戶第一個接觸到的功能就是頁面載入等待功能,這個功能對使用者來說就是一個持續1、2秒鐘的等待頁面,在用戶等待的同時程序做一些必要的檢查以及數據準備工作,載入頁面分爲UI篇和功能篇,從表及裏首先是UI的實現,一個軟件除功能之外還得有一個光鮮的外表也是非常重要的,儘管本人設計水平一般但是還是親自操刀用ps先做了一下設計效果圖如下:

212541nwfnvtwfd7s2vpvt.png

6 天前 上傳
下載附件 (131.9 KB)

 



  一、接下來的任務就是在android中實現這樣的效果顯示,從這個效果的設計分別把圖片分成背景、版本號部分、軟件名稱和圖標、作者名稱和blog四個部分,按照這樣的思路把分別生成4張png的圖片,背景部分考慮實現橫屏和豎屏切換額外添加一張橫屏背景圖,然後新建android工程,我這裏的名稱爲MySinaWeibo,android版本勾選2.2,並且創建名爲MainActivity的Activity作爲整個軟件的起始頁面,然後把上面的這些圖片保存到項目的res/drawable-mdpi文件夾下,關於res目錄下的drawable-mdpi、drawable-ldpi,、drawable-hdpi三個文件夾的區別,mdpi 裏面主要放中等分辨率的圖片,如HVGA (320x480)。ldpi裏面主要放低分辨率的圖片,如QVGA (240x320)。hdpi裏面主要放高分辨率的圖片,如WVGA (480x800),FWVGA (480x854)。android系統會根據機器的分辨率來分別到這幾個文件夾裏面去找對應的圖片,在開發程序時爲了兼容不同平臺不同屏幕,建議各自文件夾根據需求均存放不同版本圖片,我這裏就不進行這麼多的考慮了。

  二、完成圖片資源的準備後接下就是layout文件的編寫, 在res/layout文件夾下新建main.xml文件,這個layout採用LinearLayout控件作爲頂層控件,然後用ImageView控件分別實現版本號圖片頂部靠左對齊顯示、軟件名稱和圖標圖片居中對齊、作者名稱和blog圖片底部靠右對齊。注意在版本號圖片顯示ImageView控件下面添加一個RelativeLayout控件作爲軟件名稱和圖標圖片ImageVIew和作者名稱和blog圖片ImageView的父控件用來控制居中對齊已經底部對齊的實現,具體代碼如下:代碼

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3. android:id="@+id/layout"  
  4. android:orientation="vertical"  
  5. android:layout_width="fill_parent"  
  6. android:layout_height="fill_parent">  
  7. <ImageView  
  8. android:layout_width="wrap_content"  
  9. android:layout_height="wrap_content"  
  10. android:src="@drawable/ver"  
  11. android:layout_marginTop="15dip"  
  12. android:layout_marginLeft="15dip">  
  13. </ImageView>  
  14. <RelativeLayout  
  15. android:layout_width="fill_parent"  
  16. android:layout_height="fill_parent">  
  17. <ImageView  
  18. android:layout_width="wrap_content"  
  19. android:layout_height="wrap_content"  
  20. android:src="@drawable/logo"  
  21. android:layout_centerInParent="true">  
  22. </ImageView>  
  23.   
  24. <ImageView  
  25. android:layout_width="wrap_content"  
  26. android:layout_height="wrap_content"  
  27. android:src="@drawable/dev"  
  28. android:layout_alignParentBottom="true"  
  29. android:layout_alignParentRight="true"  
  30. android:layout_marginRight="5dip"  
  31. android:layout_marginBottom="35dip">  
  32. </ImageView>  
  33. </RelativeLayout>  
  34. </LinearLayout>  

 

三、在ec打開名爲MainActivity的Activity源代碼文件進行編輯,onCreate部分代碼如下:

  1. public void onCreate(Bundle savedInstanceState) {  
  2. super.onCreate(savedInstanceState);  
  3. setContentView(R.layout.main);  
  4. }  

      然後運行項目可以在模擬器中顯示,上面的幾個圖片都按照設計的位置和效果進行顯示只是整個頁面的背景還是黑色的,接下來就是背景部分的顯示實現,由於爲了實現橫豎屏切換顯示,背景圖的顯示採用代碼進行控制顯示,首先用如下方法獲取當前手機是橫屏還是豎屏:

  1. //獲取屏幕方向   
  2. public static int ScreenOrient(Activity activity)  
  3. {  
  4. int orient = activity.getRequestedOrientation();   
  5. if(orient != ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE && orient != ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {  
  6. //寬>高爲橫屏,反正爲豎屏    
  7. WindowManager windowManager = activity.getWindowManager();   
  8. Display display = windowManager.getDefaultDisplay();   
  9. int screenWidth = display.getWidth();   
  10. int screenHeight = display.getHeight();   
  11. orient = screenWidth < screenHeight ? ActivityInfo.SCREEN_ORIENTATION_PORTRAIT : ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;  
  12. }  
  13. return orient;  
  14. }  

       然後編寫一個名爲AutoBackground的公共方法用來實現屏幕背景的自動切換,後面的幾乎每一個功能頁面都需要用到這個方法

  1. public static void AutoBackground(Activity activity,View view,int Background_v, int Background_h)  
  2. {  
  3. int orient=ScreenOrient(activity);  
  4. if (orient == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) { //縱向    
  5. view.setBackgroundResource(Background_v);  
  6. }else//橫向   
  7. view.setBackgroundResource(Background_h);  
  8. }   
  9. }  

      完成上述兩方法後在 MainActivity的onCreate方法中調用AutoBackground方法進行屏幕自動切換:

  1. LinearLayout layout=(LinearLayout)findViewById(R.id.layout);  
  2. //背景自動適應   
  3. AndroidHelper.AutoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);  

到此完成了載入頁面的UI部分的實現,測試運行模擬器中查看效果,基本上跟最上面的設計效果圖相符,測試效果圖如下:

2.png

6 天前 上傳
下載附件 (94.6 KB)

 

3.png

      通過上一篇文章(android開發我的新浪微博客戶端-載入頁面UI篇(1.1))已經完成了載入頁面的UI部分的實現,效果如上圖,接下來在上面的基礎上完成載入頁面的功能代碼。

2.png

6 天前 上傳
下載附件 (94.6 KB)

 

  首先說明一下新浪微博提供了OAuth和Base OAuth兩種認證方式(如果不知道什麼是OAuth和Base OAuth請自己google一下惡補,同時接下來的2篇隨筆也會對這方面進行詳細的說明以及具體實現),本項目是採用OAuth認證方式,採用這種方式就需要有用戶的新浪UserID、Access Token、Access Secret這3樣東西才能自由便利的調用新浪的開放接口,本項目是這樣做的當用戶第一次使用軟件時進行授權認證獲取這3樣東西的時候存儲到sqlite庫中以便用戶下次使用時不需要重新進行繁瑣的授權認證操作直接從sqlite庫中讀取出來即可,由於這樣的需求載入頁面的功能設定是這樣:當用戶打開軟件顯示載入頁面時開始檢查sqlite庫中是否已經保存有用戶的新浪微博的UserID號、Access Token、Access Secret的記錄,如果一條記錄都沒有那就說明用戶是第一次使用本軟件那麼跳到認證授權頁面進行授權認證操作(認證授權功能在接下來的兩篇中進行實現講解)獲取這3個值保存到sqlite庫中,如果已經包括了記錄,那麼讀取這些記錄的UserID號、Access Token、Access Secret值然後根據這3個值調用新浪的api接口獲取這些記錄對應的用戶暱稱和用戶頭像圖標等信息。

  上面功能設定中涉及到sqlite數據庫的創建、數據表的創建、數據記錄的添加、數據記錄的讀取等操作,這裏新建名爲SqliteHelper.java類文件提供sqlite數據表的創建、更新等,代碼如下:

  1. public class SqliteHelper extends SQLiteOpenHelper{  
  2. //用來保存    
  3. UserID、Access Token、Access Secret  
  4. 的表名  
  5. public static final String TB_NAME="users";  
  6. public SqliteHelper(Context context, String name, CursorFactory factory, int version) {  
  7. super(context, name, factory, version);  
  8. }  
  9. //創建表   
  10. @Override  
  11. public void onCreate(SQLiteDatabase db) {  
  12. db.execSQL("CREATE TABLE IF NOT EXISTS "+  
  13. TB_NAME+"("+  
  14. UserInfo.ID+" integer primary key,"+  
  15. UserInfo.USERID+" varchar,"+  
  16. UserInfo.TOKEN+" varchar,"+  
  17. UserInfo.TOKENSECRET+" varchar,"+  
  18. UserInfo.USERNAME+" varchar,"+  
  19. UserInfo.USERICON+" blob"+  
  20. ")"  
  21. );  
  22. Log.e("Database","onCreate");  
  23. }  
  24. //更新表   
  25. @Override  
  26. public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {  
  27. db.execSQL("DROP TABLE IF EXISTS " + TB_NAME);  
  28. onCreate(db);  
  29. Log.e("Database","onUpgrade");  
  30. }  
  31. //更新列   
  32. public void updateColumn(SQLiteDatabase db, String oldColumn, String newColumn, String typeColumn){  
  33. try{  
  34. db.execSQL("ALTER TABLE " +  
  35. TB_NAME + " CHANGE " +  
  36. oldColumn + " "+ newColumn +  
  37. " " + typeColumn  
  38. );  
  39. }catch(Exception e){  
  40. e.printStackTrace();  
  41. }  
  42. }  
  43. }  

       接下來新建名爲DataHelper.java類文件實現用戶記錄的創建、更新、刪除等,代碼如下

  1. public class DataHelper {  
  2. //數據庫名稱   
  3. private static String DB_NAME = "mysinaweibo.db";  
  4. //數據庫版本   
  5. private static int DB_VERSION = 2;  
  6. private SQLiteDatabase db;  
  7. private SqliteHelper dbHelper;  
  8.   
  9. public DataHelper(Context context){  
  10. dbHelper=new SqliteHelper(context,DB_NAME, null, DB_VERSION);  
  11. db= dbHelper.getWritableDatabase();  
  12. }  
  13.   
  14. public void Close()  
  15. {  
  16. db.close();  
  17. dbHelper.close();  
  18. }  
  19. //獲取users表中的UserID、Access Token、Access Secret的記錄   
  20. public List<UserInfo> GetUserList(Boolean isSimple)  
  21. {  
  22. List<UserInfo> userList = new ArrayList<UserInfo>();  
  23. Cursor cursor=db.query(SqliteHelper.TB_NAME, nullnullnullnullnull, UserInfo.ID+" DESC");  
  24. cursor.moveToFirst();  
  25. while(!cursor.isAfterLast()&& (cursor.getString(1)!=null)){  
  26. UserInfo user=new UserInfo();  
  27. user.setId(cursor.getString(0));  
  28. user.setUserId(cursor.getString(1));  
  29. user.setToken(cursor.getString(2));  
  30. user.setTokenSecret(cursor.getString(3));  
  31. if(!isSimple){  
  32. user.setUserName(cursor.getString(4));  
  33. ByteArrayInputStream stream = new ByteArrayInputStream(cursor.getBlob(5));   
  34. Drawable icon= Drawable.createFromStream(stream, "image");  
  35. user.setUserIcon(icon);  
  36. }  
  37. userList.add(user);  
  38. cursor.moveToNext();  
  39. }  
  40. cursor.close();  
  41. return userList;  
  42. }  
  43.   
  44. //判斷users表中的是否包含某個UserID的記錄   
  45. public Boolean HaveUserInfo(String UserId)  
  46. {  
  47. Boolean b=false;  
  48. Cursor cursor=db.query(SqliteHelper.TB_NAME, null, UserInfo.USERID + "=" + UserId, nullnullnull,null);  
  49. b=cursor.moveToFirst();  
  50. Log.e("HaveUserInfo",b.toString());  
  51. cursor.close();  
  52. return b;  
  53. }  
  54.   
  55. //更新users表的記錄,根據UserId更新用戶暱稱和用戶圖標   
  56. public int UpdateUserInfo(String userName,Bitmap userIcon,String UserId)  
  57. {  
  58. ContentValues values = new ContentValues();  
  59. values.put(UserInfo.USERNAME, userName);  
  60. // BLOB類型    
  61. final ByteArrayOutputStream os = new ByteArrayOutputStream();   
  62. // 將Bitmap壓縮成PNG編碼,質量爲100%存儲    
  63. userIcon.compress(Bitmap.CompressFormat.PNG, 100, os);   
  64. // 構造SQLite的Content對象,這裏也可以使用raw    
  65. values.put(UserInfo.USERICON, os.toByteArray());  
  66. int id= db.update(SqliteHelper.TB_NAME, values, UserInfo.USERID + "=" + UserId, null);  
  67. Log.e("UpdateUserInfo2",id+"");  
  68. return id;  
  69. }  
  70.   
  71. //更新users表的記錄   
  72. public int UpdateUserInfo(UserInfo user)  
  73. {  
  74. ContentValues values = new ContentValues();  
  75. values.put(UserInfo.USERID, user.getUserId());  
  76. values.put(UserInfo.TOKEN, user.getToken());  
  77. values.put(UserInfo.TOKENSECRET, user.getTokenSecret());  
  78. int id= db.update(SqliteHelper.TB_NAME, values, UserInfo.USERID + "=" + user.getUserId(), null);  
  79. Log.e("UpdateUserInfo",id+"");  
  80. return id;  
  81. }  
  82.   
  83. //添加users表的記錄   
  84. public Long SaveUserInfo(UserInfo user)  
  85. {  
  86. ContentValues values = new ContentValues();  
  87. values.put(UserInfo.USERID, user.getUserId());  
  88. values.put(UserInfo.TOKEN, user.getToken());  
  89. values.put(UserInfo.TOKENSECRET, user.getTokenSecret());  
  90. Long uid = db.insert(SqliteHelper.TB_NAME, UserInfo.ID, values);  
  91. Log.e("SaveUserInfo",uid+"");  
  92. return uid;  
  93. }  
  94.   
  95. //刪除users表的記錄   
  96. public int DelUserInfo(String UserId){  
  97. int id= db.delete(SqliteHelper.TB_NAME, UserInfo.USERID +"="+UserId, null);  
  98. Log.e("DelUserInfo",id+"");  
  99. return id;  
  100. }  
  101. }  

       完成上面的代碼後,我們需要在載入頁面中調用上面的方法實現sqlite庫中是否已經保存有用戶的新浪微博的UserID號、Access Token、Access Secret的記錄的功能在MainActivity的onCreate方法添加代碼:

  1. public void onCreate(Bundle savedInstanceState) {  
  2. super.onCreate(savedInstanceState);  
  3. setContentView(R.layout.main);  
  4.   
  5. ......  
  6.   
  7. //獲取賬號列表   
  8. dbHelper=new DataHelper(this);  
  9. List<UserInfo> userList= dbHelper.GetUserList(true);  
  10. if(userList.isEmpty())//如果爲空說明第一次使用跳到AuthorizeActivity頁面進行OAuth認證   
  11. {  
  12. Intent intent = new Intent();  
  13. intent.setClass(MainActivity.this, AuthorizeActivity.class);  
  14. startActivity(intent);  
  15. }  
  16. else//如果不爲空讀取這些記錄的UserID號、Access Token、Access Secret值   
  17. //然後根據這3個值調用新浪的api接口獲取這些記錄對應的用戶暱稱和用戶頭像圖標等信息。   
  18. {  
  19. for(UserInfo user:userList){  
  20. ......  
  21. }  
  22. }  
  23. }  

 

      本篇說說關於OAuth授權認證的事情,新浪開放api都必須在這個基礎上才能調用,所以有必要專門來講講,前面的文章中已經提到過關於新浪微博提供了OAuth和Base OAuth兩種認證方式,並且本項目採用OAuth認證方式,至於爲什麼採用這個OAuth認證而不採用Base OAuth認證原因很簡單,自從Twitter只支持OAuth認證方式以來,各大應用都紛紛轉向OAuth認證方式,而新浪微博的開放平臺也將在近日停止Base OAuth的認證方式。

4.png

6 天前 上傳
下載附件 (30.41 KB)

 

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開源項目簡單了很多。具體代碼如下:

  1. public class OAuth {  
  2. private CommonsHttpOAuthConsumer httpOauthConsumer;  
  3. private OAuthProvider httpOauthprovider;  
  4. public String consumerKey;  
  5. public String consumerSecret;  
  6.   
  7. public OAuth()  
  8. {   
  9. // 第一組:(App Key和App Secret)   
  10. // 這組參數就是本系列文本第一篇提到的建一個新的應用獲取App Key和App Secret。   
  11. this("3315495489","e2731e7grf592c0fd7fea32406f86e1b");  
  12. }  
  13. public OAuth(String consumerKey,String consumerSecret)  
  14. {  
  15. this.consumerKey=consumerKey;  
  16. this.consumerSecret=consumerSecret;  
  17. }  
  18.   
  19. public Boolean RequestAccessToken(Activity activity,String callBackUrl){  
  20. Boolean ret=false;  
  21. try{  
  22. httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);  
  23. 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");  
  24. String authUrl = httpOauthprovider.retrieveRequestToken(httpOauthConsumer, callBackUrl);  
  25. activity.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));  
  26. ret=true;  
  27. }catch(Exception e){  
  28. }  
  29. return ret;  
  30. }  
  31.   
  32. public UserInfo GetAccessToken(Intent intent){  
  33. UserInfo user=null;  
  34. Uri uri = intent.getData();  
  35. String verifier = uri.getQueryParameter(oauth.signpost.OAuth.OAUTH_VERIFIER);  
  36. try {  
  37. httpOauthprovider.setOAuth10a(true);   
  38. httpOauthprovider.retrieveAccessToken(httpOauthConsumer,verifier);  
  39. catch (OAuthMessageSignerException ex) {  
  40. ex.printStackTrace();  
  41. catch (OAuthNotAuthorizedException ex) {  
  42. ex.printStackTrace();  
  43. catch (OAuthExpectationFailedException ex) {  
  44. ex.printStackTrace();  
  45. catch (OAuthCommunicationException ex) {  
  46. ex.printStackTrace();  
  47. }  
  48. SortedSet<String> user_id= httpOauthprovider.getResponseParameters().get("user_id");  
  49. String userId=user_id.first();  
  50. String userKey = httpOauthConsumer.getToken();  
  51. String userSecret = httpOauthConsumer.getTokenSecret();  
  52. user=new UserInfo();  
  53. user.setUserId(userId);  
  54. user.setToken(userKey);  
  55. user.setTokenSecret(userSecret);  
  56. return user;  
  57. }  
  58.   
  59. public HttpResponse SignRequest(String token,String tokenSecret,String url,List params)  
  60. {  
  61. HttpPost post = new HttpPost(url);  
  62. //HttpClient httpClient = null;   
  63. try{  
  64. post.setEntity(new UrlEncodedFormEntity(params,HTTP.UTF_8));  
  65. catch (UnsupportedEncodingException e) {  
  66. e.printStackTrace();  
  67. }  
  68. //關閉Expect:100-Continue握手   
  69. //100-Continue握手需謹慎使用,因爲遇到不支持HTTP/1.1協議的服務器或者代理時會引起問題   
  70. post.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);  
  71. return SignRequest(token,tokenSecret,post);  
  72. }  
  73.   
  74. public HttpResponse SignRequest(String token,String tokenSecret,HttpPost post){  
  75. httpOauthConsumer = new CommonsHttpOAuthConsumer(consumerKey,consumerSecret);  
  76. httpOauthConsumer.setTokenWithSecret(token,tokenSecret);  
  77. HttpResponse response = null;  
  78. try {  
  79. httpOauthConsumer.sign(post);  
  80. catch (OAuthMessageSignerException e) {  
  81. e.printStackTrace();  
  82. catch (OAuthExpectationFailedException e) {  
  83. e.printStackTrace();  
  84. catch (OAuthCommunicationException e) {  
  85. e.printStackTrace();  
  86. }  
  87. //取得HTTP response   
  88. try {  
  89. response = new DefaultHttpClient().execute(post);  
  90. catch (ClientProtocolException e) {  
  91. e.printStackTrace();  
  92. catch (IOException e) {  
  93. e.printStackTrace();  
  94. }  
  95. return response;  
  96. }  
  97. }  

   這樣就完成了OAuth功能類的開發,後面都會用到這個類相關的方法。本篇到這裏就算是完結請繼續關注後面的文章。

上一篇講了講OAuth授權認證的事情,大概的介紹了OAuth的原理,並且完成了一個OAuth.java的類庫,提供了幾個OAuth認證必要的方法,本篇開始具體講本項目的用戶授權功能,用戶授權頁面是當用戶第一次使用本軟件的時候自動從載入頁面跳轉過來的顯示的頁面,涉及OAuth認證相關都是在上一篇的OAuth.java的類基礎上開發。用戶授權頁面分爲UI篇和功能篇兩篇,本篇先來講講UI的實現,這次就不貼PS的效果圖了直接貼實現後的功能截圖如下:

5.png

6 天前 上傳
下載附件 (84.47 KB)

 

  看上面的圖,其實這個頁面的UI實現不復雜,首先是背景部分的實現這個參考 android開發我的新浪微博客戶端-載入頁面UI篇(1.1),重點來講講這個半透明的彈出對話框窗口是如何實現的,首先新建名爲AuthorizeActivity.java的Activity,並且在AndroidManifest.xml文件中添加這個Activity,這樣這個Activity才能被使用,接下來爲這個Activity新建名爲authorize.xml的Layout,這個Layout很簡單隻負責logo小圖標顯示,背景部分和透明窗口都是有代碼來實現,所以非常簡單參考 android開發我的新浪微博客戶端-載入頁面UI篇(1.1)。

  完成Layout建立後在AuthorizeActivity的onCreate方法添加如下代碼,設置authorize.xml爲AuthorizeActivity的頁面Layout:

  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3. super.onCreate(savedInstanceState);  
  4. setContentView(R.layout.authorize);  
  5. .......  
  6. }  

      接下來是本文的重點部分,半透明彈窗用Dialog控件進行實現,首先爲這個半透明彈窗新建一個名爲dialog.xml的Layout,這個Layout主要是對4個元素進行佈局,如圖所示分別爲i小圖標、信息提示、中間文字、開始按鈕,首先用LinearLayout對i小圖標和信息提示進行水平佈局,中間文字以一個TextView跟在下面,對於開始按鈕是用RelativeLayout進行底部對齊顯示。具體代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:layout_width="wrap_content"  
  5. android:layout_height="wrap_content"  
  6. android:orientation="vertical"  
  7. android:padding="10dip">  
  8. <LinearLayout  
  9. android:layout_width="wrap_content"  
  10. android:layout_height="wrap_content"  
  11. android:orientation="horizontal">  
  12. <ImageView  
  13. android:layout_width="wrap_content"  
  14. android:layout_height="wrap_content"  
  15. android:src="@drawable/info_icon">  
  16. </ImageView>  
  17. <TextView  
  18. android:layout_width="wrap_content"  
  19. android:layout_height="wrap_content"  
  20. android:text="信息提示"  
  21. android:textSize="13px"  
  22. android:textColor="#219ac6"  
  23. android:layout_marginLeft="5dip">  
  24. </TextView>  
  25. </LinearLayout>  
  26. <TextView  
  27. android:id="@+id/text_info"  
  28. android:layout_marginTop="6px"  
  29. android:layout_width="200px"  
  30. android:layout_height="wrap_content"  
  31. android:textColor="#686767"  
  32. android:textSize="14px"  
  33. android:text="第一次使用需要輸入您的新浪微博賬號和密碼進行登錄授權">  
  34. </TextView>  
  35. <RelativeLayout  
  36. android:layout_width="fill_parent"  
  37. android:layout_height="40px">  
  38. <LinearLayout  
  39. android:layout_width="wrap_content"  
  40. android:layout_height="wrap_content"  
  41. android:orientation="horizontal"  
  42. android:layout_centerHorizontal="true"  
  43. android:layout_alignParentBottom="true">  
  44. <ImageButton  
  45. android:id="@+id/btn_start"  
  46. android:layout_width="80px"  
  47. android:layout_height="31px"  
  48. android:src="@drawable/btn_start_selector">  
  49. </ImageButton>  
  50. <ImageButton  
  51. android:id="@+id/btn_cancel"  
  52. android:layout_width="80px"  
  53. android:layout_height="31px"  
  54. android:layout_marginLeft="8px"  
  55. android:src="@drawable/btn_cancel_selector">  
  56. </ImageButton>  
  57. </LinearLayout>  
  58. </RelativeLayout>  
  59.   
  60. </LinearLayout>  

     完成了半透明彈窗的Layout定義接下來我們要做的就是爲它寫一個自定義樣式來實現我們想要的顯示效果,首先我們需準備一個圓角的半透明png圖片名爲dia_bg.png並且添加到drawable中,接下來再res/values文件夾新建名爲 dialogStyle.xml的resources樣式文件,具體代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3. <mce:style name="dialog" parent="@android:style/Theme.Dialog"><!--  
  4. <item name="android:windowFrame">@null</item>  
  5. <item name="android:windowIsFloating">true</item>  
  6. <item name="android:windowIsTranslucent">false</item>  
  7. <item name="android:windowNoTitle">true</item>  
  8. <item name="android:windowBackground">@drawable/dia_bg</item>  
  9. <item name="android:backgroundDimEnabled">false</item>  
  10. --></mce:style><style name="dialog" parent="@android:style/Theme.Dialog" mce_bogus="1"><item name="android:windowFrame">@null</item>  
  11. <item name="android:windowIsFloating">true</item>  
  12. <item name="android:windowIsTranslucent">false</item>  
  13. <item name="android:windowNoTitle">true</item>  
  14. <item name="android:windowBackground">@drawable/dia_bg</item>  
  15. <item name="android:backgroundDimEnabled">false</item></style>  
  16. </resources>  

這個樣式文件的說明如下

  parent="@android:style/Theme.Dialog" :在系統Dialog樣式基礎上,相當於繼承系統樣式

  <item name="android:windowFrame">@null</item> :Dialog的windowFrame框爲無

  <item name="android:windowIsFloating">true</item>:是否浮現在activity之上

  <item name="android:windowIsTranslucent">false</item>:是否半透明

  <item name="android:windowNoTitle">true</item>:是否顯示title

  <item name="android:windowBackground">@drawable/dia_bg</item>:設置dialog的背景

  <item name="android:backgroundDimEnabled">false</item>: 背景是否模糊顯示

  接下來寫java代碼把這個半透明彈窗顯示出來,在AuthorizeActivity的onCreate方法添加如下代碼:

  1. ......  
  2. View diaView=View.inflate(this, R.layout.dialog, null);  
  3. dialog=new Dialog(AuthorizeActivity.this,R.style.dialog);  
  4. dialog.setContentView(diaView);  
  5. dialog.show();  
  6. ......  

最後運行查看效果,到這裏我們的任務已經完成了。請關注下一篇功能篇。

 

android開發我的新浪微博客戶端-用戶授權頁面功能篇(3.2)

7.png

6 天前 上傳
下載附件 (30.41 KB)

6.png

6 天前 上傳
下載附件 (84.47 KB)


    在上一篇實現了用戶授權頁面的UI,如上圖,接下來要做的就是在這個基礎上完成功能部分真正實現用戶的授權認證,這一篇是android開發我的新浪微博客戶端-OAuth篇(2.1)的具體應用篇原理就不多解釋了不懂的看OAuth篇即可。認證過程從點擊開始按鈕然後跳轉到新浪的授權頁面,接着用戶在新浪的頁面裏輸入自己的賬戶和密碼確定後返回用戶授權頁面。首先給開始按鈕添加點擊事件代碼,代碼中主要是調用我們前面android開發我的新浪微博客戶端-OAuth篇(2.1)完成的OAuth類的RequestAccessToken方法用來獲取oauth_verifier,具體代碼如下:

  1. ImageButton stratBtn=(ImageButton)diaView.findViewById(R.id.btn_start);  
  2. stratBtn.setOnClickListener(new OnClickListener(){  
  3.   
  4. @Override  
  5. public void onClick(View arg0) {  
  6. auth=new OAuth();  
  7. auth.RequestAccessToken(AuthorizeActivity.this, CallBackUrl);  
  8. }  
  9.   
  10. });  

     上面的代碼中重點來說明一下 RequestAccessToken方法的第二參數CallBackUrl,這個參數是用戶在新浪的頁面中輸入賬戶密碼後完成認證後返回的地址,我這裏是這樣設置的CallBackUrl = "myapp://AuthorizeActivity",在AndroidManifest.xml中配置給AuthorizeActivity添加如下配置把myapp://AuthorizeActivity指向到AuthorizeActivity,這樣當頁面返回到AuthorizeActivity中就可以獲取到傳過來的oauth_verifier參數。

  1. <intent-filter>  
  2. <action android:name="android.intent.action.VIEW" />  
  3. <category android:name="android.intent.category.DEFAULT" />  
  4. <category android:name="android.intent.category.BROWSABLE" />  
  5. <data android:scheme="myapp" android:host="AuthorizeActivity" />   
  6. </intent-filter>  

      再AuthorizeActivity如果來接收返回的oauth_verifier參數呢?接下來在AuthorizeActivity添加如下方法:

  1. @Override  
  2. protected void onNewIntent(Intent intent) {  
  3. super.onNewIntent(intent);  
  4. //在這裏處理獲取返回的oauth_verifier參數   
  5. }  

      關於onNewIntent的說明是這樣的,onCreate是用來創建一個Activity也就是創建一個窗體,但一個Activty處於任務棧的頂端,若再次調用startActivity去創建它,則不會再次創建。若你想利用已有的Acivity去處理別的Intent時,你就可以利用onNewIntent來處理。在onNewIntent裏面就會獲得新的Intent,在這裏AuthorizeActivity是屬於已有的Acivity,所以需要onNewIntent來處理接收返回的參數,獲取oauth_verifier參數後OAuth還沒有結束從android開發我的新浪微博客戶端-OAuth篇(2.1)描述來看還需要進行根據這個參數繼續向新浪微博請求獲取User_id、Access Token和Access Secret,在這裏我把這些操作全部寫在了GetAccessToken方法中。在onNewIntent添加如下代碼:

  1. UserInfo user= auth.GetAccessToken(intent);  
  2. if(user!=null){  
  3. DataHelper helper=new DataHelper(this);  
  4. String uid=user.getUserId();  
  5. if(helper.HaveUserInfo(uid))  
  6. {  
  7. helper.UpdateUserInfo(user);  
  8. Log.e("UserInfo""update");  
  9. }else  
  10. {  
  11. helper.SaveUserInfo(user);  
  12. Log.e("UserInfo""add");  
  13. }  
  14. }  

      通過上面的代碼完成了User_id、Access Token和Access Secret 獲取並且保存到了sqlite庫中,這樣就完成了用戶的OAuth認證,當需要調用新浪的api時只需要去sqlite庫中找該用戶的User_id、Access Token和Access Secret 即可。到這裏本篇就結束了,請關注下一篇。

 

android開發我的新浪微博客戶端-登錄頁面UI篇(4.1)

9.png

6 天前 上傳
下載附件 (83.17 KB)

 

8.png

6 天前 上傳
下載附件 (85.15 KB)

 

首先回顧一下功能流程當用戶開啓軟件顯示載入頁面時程序首先去sqlite庫查詢是否已經保存有用戶的新浪微博的UserID號、Access Token、Access Secret的記錄如果沒有一條記錄那麼跳轉到用戶授權功能頁面,這個已經由上面兩篇文章實現了,如果有記錄那麼頁面跳轉到用戶登錄頁面,也就是本篇以及下篇要實現的功能,本篇講UI的實現,本項目支持多微博賬號了,也就是用戶可以設置多個微博賬號,登錄的時候選擇其中的一個登錄,具體效果如上圖,新建名LoginActivity.java的Activity並且在AndroidManifest.xml中進行相應配置,這個頁面就是我們要實現的用戶登錄頁面。

      看上面的效果,首先頁面分3部分實現,背景部分、底部菜單部分、用戶選擇以及頭像顯示部分,首先在res/layout的目錄下新建名爲login.xml的layout,然後根據頁面顯示要求編寫如下的佈局控制:

 

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:id="@+id/layout"  
  5. android:orientation="vertical"  
  6. android:layout_width="fill_parent"  
  7. android:layout_height="fill_parent">  
  8. <ImageView  
  9. android:layout_width="wrap_content"  
  10. android:layout_height="wrap_content"  
  11. android:src="@drawable/logo_s"  
  12. android:layout_marginTop="5dip"  
  13. android:layout_marginLeft="5dip">  
  14. </ImageView>  
  15. <RelativeLayout  
  16. android:layout_width="fill_parent"  
  17. android:layout_height="fill_parent">  
  18. <RelativeLayout  
  19. android:id="@+id/iconBtn"  
  20. android:layout_width="90px"  
  21. android:layout_height="80px"  
  22. android:background="@drawable/icon_selector"  
  23. android:layout_above="@+id/selectLayout"  
  24. android:layout_centerHorizontal="true"  
  25. android:layout_marginBottom="20dip">  
  26. <ImageView  
  27. android:id="@+id/icon"  
  28. android:layout_width="wrap_content"  
  29. android:layout_height="wrap_content"  
  30. android:layout_centerInParent="true">  
  31. </ImageView>  
  32. </RelativeLayout>  
  33.   
  34. <RelativeLayout  
  35. android:id="@+id/selectLayout"  
  36. android:layout_width="wrap_content"  
  37. android:layout_height="wrap_content"  
  38. android:layout_centerInParent="true">  
  39. <EditText  
  40. android:id="@+id/iconSelect"  
  41. android:layout_width="200px"  
  42. android:layout_height="wrap_content"   
  43. android:maxLength="10"   
  44. android:paddingLeft="20px"  
  45. android:editable="false"  
  46. android:enabled="false"  
  47. android:textSize="13px"  
  48. android:background="@drawable/input_over" >  
  49. </EditText>  
  50. <ImageButton   
  51. android:id="@+id/iconSelectBtn"  
  52. android:layout_width="wrap_content"  
  53. android:layout_height="wrap_content"   
  54. android:layout_marginRight="1.0dip"  
  55. android:layout_alignTop="@+id/iconSelect"  
  56. android:layout_alignRight="@+id/iconSelect"  
  57. android:layout_alignBottom="@+id/iconSelect"  
  58. android:background="@drawable/more_selector" >  
  59. </ImageButton>  
  60. <ImageButton   
  61. android:id="@+id/login"  
  62. android:layout_width="40px"  
  63. android:layout_height="40px"   
  64. android:layout_marginLeft="5dip"  
  65. android:layout_alignTop="@+id/iconSelectBtn"  
  66. android:layout_toRightOf="@+id/iconSelectBtn"  
  67. android:layout_alignBottom="@+id/iconSelectBtn"  
  68. android:background="@drawable/btn_in_selector" >  
  69. </ImageButton>  
  70. </RelativeLayout>  
  71.   
  72. <RelativeLayout  
  73. android:layout_width="fill_parent"  
  74. android:layout_height="44dip"  
  75. android:layout_alignParentBottom="true"  
  76. android:background="#BB768e95">  
  77. <LinearLayout  
  78. android:id="@+id/addLayout"  
  79. android:layout_width="wrap_content"  
  80. android:layout_height="wrap_content"  
  81. android:orientation="vertical"  
  82. android:layout_alignParentLeft="true"  
  83. android:gravity="center"  
  84. android:layout_marginTop="3px">  
  85. <ImageButton  
  86. android:id="@+id/addIcon"  
  87. android:layout_width="wrap_content"  
  88. android:layout_height="wrap_content"  
  89. android:background="@drawable/add_selector">  
  90. </ImageButton>  
  91. <TextView  
  92. android:layout_width="wrap_content"  
  93. android:layout_height="wrap_content"  
  94. android:textColor="#ffffff"  
  95. android:textSize="12px"  
  96. android:text="添加賬號">  
  97. </TextView>  
  98. </LinearLayout>  
  99. <LinearLayout  
  100. android:id="@+id/exitLayout"  
  101. android:layout_width="wrap_content"  
  102. android:layout_height="wrap_content"  
  103. android:orientation="vertical"  
  104. android:layout_centerInParent="true"  
  105. android:gravity="center"  
  106. android:layout_marginTop="3px">  
  107. <ImageButton  
  108. android:id="@+id/exitIcon"  
  109. android:layout_width="wrap_content"  
  110. android:layout_height="wrap_content"  
  111. android:background="@drawable/exit_selector">  
  112. </ImageButton>  
  113. <TextView  
  114. android:layout_width="wrap_content"  
  115. android:layout_height="wrap_content"  
  116. android:textColor="#ffffff"  
  117. android:textSize="12px"  
  118. android:text="退出軟件">  
  119. </TextView>  
  120. </LinearLayout>  
  121. <LinearLayout  
  122. android:id="@+id/delLayout"  
  123. android:layout_width="wrap_content"  
  124. android:layout_height="wrap_content"  
  125. android:orientation="vertical"  
  126. android:layout_alignParentRight="true"  
  127. android:gravity="center"  
  128. android:layout_marginTop="3px">  
  129. <ImageButton  
  130. android:id="@+id/delIcon"  
  131. android:layout_width="wrap_content"  
  132. android:layout_height="wrap_content"  
  133. android:background="@drawable/del_selector">  
  134. </ImageButton>  
  135. <TextView  
  136. android:layout_width="wrap_content"  
  137. android:layout_height="wrap_content"  
  138. android:textColor="#ffffff"  
  139. android:textSize="12px"  
  140. android:text="刪除賬號">  
  141. </TextView>  
  142. </LinearLayout>  
  143. </RelativeLayout>  
  144. </RelativeLayout>  
  145. </LinearLayout>  

      正對上面的login.xml的layout進行一下說明,背景部分前面已經講過了這裏也就不重複。
  底部菜單實現,原本我是採用GridView實現的非常的方便但是後來由於顯示位置不好控制改成了用RelativeLayout和LinearLayout嵌套的方式,實現的比較土但是達到了顯示需求,首先是一個最外面的RelativeLayout目的是用來實現底部對齊顯示,並且把這個RelativeLayout的背景設置爲淺藍色半透明的效果,關鍵這2行:android:layout_alignParentBottom="true"和android:background="#BB768e95"。然後是在RelativeLayout內部添加3個LinearLayout分別是用來顯示添加賬號、退出軟件、刪除賬號3個功能按鈕菜單,並且分別設置爲左對齊、居中對齊、右對齊,3個LinearLayout都設置爲垂直佈局androidrientation="vertical",然後每LinearLayout添加相應的圖片和文字。
  用戶選擇以及頭像顯示部分,這塊分成3小塊,用來顯示用戶頭像的ImageView、用來顯示用戶名字並且點擊可以出現選擇列表的EditText、用來點擊進入當前選擇用戶首頁的功能按鈕ImageButton,這3小塊的佈局實現也是採用elativeLayout和LinearLayout相互嵌套配合的方式實現的具體參考login.xml。這裏重點說說這個賬號選擇列表彈出窗口的實現,當點擊下拉箭頭按鈕的時候彈出並顯示,這個是用Dialog控件實現,首先準備好圓角的半透明背景圖mask_bg.png然後添加到res/drawable-mdpi文件夾下,接着自定義一個Dialog樣式文件,在res/values目錄下新建名爲dialogStyles2.xml的resources文件,在用戶授權驗證頁面的時候我們也自定義過類似的Dialog的樣式,具體解釋可以參考前面的戶授權驗證頁面功能,內容如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3. <mce:style name="dialog2" parent="@android:style/Theme.Dialog"><!--  
  4. <item name="android:windowFrame">@null</item>  
  5. <item name="android:windowIsFloating">true</item>  
  6. <item name="android:windowIsTranslucent">false</item>  
  7. <item name="android:windowNoTitle">true</item>  
  8. <item name="android:windowBackground">@drawable/mask_bg</item>  
  9. <item name="android:backgroundDimEnabled">true</item>  
  10. --></mce:style><style name="dialog2" parent="@android:style/Theme.Dialog" mce_bogus="1"><item name="android:windowFrame">@null</item>  
  11. <item name="android:windowIsFloating">true</item>  
  12. <item name="android:windowIsTranslucent">false</item>  
  13. <item name="android:windowNoTitle">true</item>  
  14. <item name="android:windowBackground">@drawable/mask_bg</item>  
  15. <item name="android:backgroundDimEnabled">true</item></style>  
  16. </resources>  

      接下來還需要定義選擇列表的layout,新建名爲dialog2.xml的layout文件,內容如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:layout_width="wrap_content"  
  5. android:layout_height="wrap_content"  
  6. android:orientation="vertical"  
  7. android:padding="4dip">  
  8. <ListView  
  9. android:id="@+id/list"  
  10. android:layout_width="240px"  
  11. android:layout_height="220px"  
  12. android:divider="#f1f2f2"  
  13. android:dividerHeight="1px"  
  14. android:layout_margin="5px"  
  15. android:background="#ffffff"  
  16. android:cacheColorHint="#00000000">  
  17. </ListView>  
  18. </LinearLayout>  

     完成了layout和樣式文件的編寫,接下來就是把dialogStyles2.xml樣式文件和dialog2.xml的列表layout用起來,當點擊id爲iconSelectBtn的ImageButton時顯示用戶選擇窗口,在LoginActivity的onCreate方法中添加如下代碼:

  1. public void onCreate(Bundle savedInstanceState) {  
  2. super.onCreate(savedInstanceState);  
  3. setContentView(R.layout.login);  
  4.   
  5. LinearLayout layout=(LinearLayout)findViewById(R.id.layout);  
  6. //背景自動適應   
  7. AndroidHelper.AutoBackground(this, layout, R.drawable.bg_v, R.drawable.bg_h);  
  8.   
  9. ImageButton iconSelectBtn=(ImageButton)findViewById(R.id.iconSelectBtn);  
  10. iconSelectBtn.setOnClickListener(new OnClickListener(){  
  11. @Override  
  12. public void onClick(View v) {  
  13. View diaView=View.inflate(LoginActivity.this, R.layout.dialog2, null);  
  14. dialog=new Dialog(LoginActivity.this,R.style.dialog2);  
  15. dialog.setContentView(diaView);  
  16. dialog.show();  
  17.   
  18. ......  
  19. }  
  20.   
  21. });  

      到這裏登錄的UI部分就實現的差不多了,剩下的都是一些功能部分代碼用來實現從sqlite中賬號列表的獲取,以及點擊選擇等交互操作等,這些在下一篇中來繼續的講。

android開發我的新浪微博客戶端-登錄頁面功能篇(4.2)

上一篇中完成了如上圖的UI部分的實現,現在繼續來講功能的實現,用戶登錄操作主要就是賬號列表顯示和選擇賬號登錄兩個功能其他的都是些簡單的輔助功能,首先是點擊id爲iconSelectBtn的ImageButton時顯示用戶選擇窗口,這個時候去數據庫中獲取賬號記錄然後在選擇窗口中以列表方式顯示出來,通過上一篇已經知道Id爲list的ListView控件來顯示賬號列表,首先是從數據庫中獲取所有的賬戶記錄然後設置默認選中的用戶賬號代碼如下:

  1. private void initUser(){  
  2. //獲取賬號列表   
  3. dbHelper=new DataHelper(this);  
  4. userList = dbHelper.GetUserList(false);  
  5. if(userList.isEmpty())  
  6. {  
  7. Intent intent = new Intent();  
  8. intent.setClass(LoginActivity.this, AuthorizeActivity.class);  
  9. startActivity(intent);  
  10. }  
  11. else  
  12. {  
  13. SharedPreferences preferences = getSharedPreferences(Select_Name, Activity.MODE_PRIVATE);  
  14. String str= preferences.getString("name""");  
  15. UserInfo user=null;  
  16. if(str!="")  
  17. {  
  18. user=GetUserByName(str);  
  19. }  
  20. if(user==null)  
  21. {  
  22. user=userList.get(0);  
  23. }  
  24. icon.setImageDrawable(user.getUserIcon());  
  25. iconSelect.setText(user.getUserName());  
  26. }  
  27. }  

      這個initUser() 初始賬號的方法在LoginActivity的onCreate中調用,主要完成兩件事情,第一件獲取通過userList = dbHelper.GetUserList(false);獲取所有的賬戶記錄,關於DataHelper前面已經有說過了,如果獲取的用戶記錄爲空那麼就跳轉到用戶授權功能頁面讓用戶添加賬號,如果不爲空那麼通過SharedPreferences去讀取用戶上一次選擇的賬號名稱,如果沒有或者數據庫裏賬號記錄不包括這個賬戶名稱那麼默認顯示記錄的第一個賬號和頭像,如果有那麼顯示這個賬戶的名稱和頭像。關於SharedPreferences,是android提供給開發者用來存儲一些簡單的數據用的,非常方便類似於網站的Cookie,在這裏我就是用這個來保存上一次用戶選擇的是哪個賬號,非常實用。
     接下類首先爲Id爲list的ListView控件準備數據Adapter,這個Adapter非常簡單就是普通的adapter繼承BaseAdapter即可,代碼如下:

  1. public class UserAdapater extends BaseAdapter{  
  2.   
  3. @Override  
  4. public int getCount() {  
  5. return userList.size();  
  6. }  
  7.   
  8. @Override  
  9. public Object getItem(int position) {  
  10. return userList.get(position);  
  11. }  
  12.   
  13. @Override  
  14. public long getItemId(int position) {  
  15. return position;  
  16. }  
  17.   
  18. @Override  
  19. public View getView(int position, View convertView, ViewGroup parent) {  
  20. convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.item_user, null);  
  21.   
  22. ImageView iv = (ImageView) convertView.findViewById(R.id.iconImg);  
  23. TextView tv = (TextView) convertView.findViewById(R.id.showName);  
  24. UserInfo user = userList.get(position);  
  25. try {  
  26. //設置圖片顯示   
  27. iv.setImageDrawable(user.getUserIcon());  
  28. //設置信息   
  29. tv.setText(user.getUserName());  
  30.   
  31.   
  32. catch (Exception e) {  
  33. e.printStackTrace();  
  34. }  
  35. return convertView;  
  36. }  

       接下就是爲這個ListView設定數據源Adapter,在賬號選擇窗口顯示的時候進行設置,添加到id爲iconSelectBtn的ImageButton的OnClickListener中代碼如下:

  1. ImageButton iconSelectBtn=(ImageButton)findViewById(R.id.iconSelectBtn);  
  2. iconSelectBtn.setOnClickListener(new OnClickListener(){  
  3. @Override  
  4. public void onClick(View v) {  
  5. ......  
  6. dialog.show();  
  7.   
  8. UserAdapater adapater = new UserAdapater();  
  9. ListView listview=(ListView)diaView.findViewById(R.id.list);  
  10. listview.setVerticalScrollBarEnabled(false);// ListView去掉下拉條   
  11. listview.setAdapter(adapater);  
  12. listview.setOnItemClickListener(new OnItemClickListener(){  
  13. @Override  
  14. public void onItemClick(AdapterView<?> arg0, View view,int arg2, long arg3) {  
  15. TextView tv=(TextView)view.findViewById(R.id.showName);  
  16. iconSelect.setText(tv.getText());  
  17. ImageView iv=(ImageView)view.findViewById(R.id.iconImg);  
  18. icon.setImageDrawable(iv.getDrawable());  
  19. dialog.dismiss();  
  20. }  
  21.   
  22. });  
  23. }  
  24.   
  25. });  

      通過上面代碼完成了賬號選擇的功能,接下來給id爲login的ImageButton添加OnClickListener,使得點擊後以當前選擇賬號進入微博首頁,代碼如下:

  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3. super.onCreate(savedInstanceState);  
  4. setContentView(R.layout.login);  
  5. ......  
  6. ImageButton login=(ImageButton)findViewById(R.id.login);  
  7. login.setOnClickListener(new OnClickListener(){  
  8. @Override  
  9. public void onClick(View v) {  
  10. GoHome();  
  11. }  
  12.   
  13. });  
  14. }  
  15.   
  16. //進入用戶首頁   
  17. private void GoHome(){  
  18. if(userList!=null)  
  19. {  
  20. String name=iconSelect.getText().toString();  
  21. UserInfo u=GetUserByName(name);  
  22. if(u!=null)  
  23. {  
  24. ConfigHelper.nowUser=u;//獲取當前選擇的用戶並且保存   
  25. }  
  26. }  
  27. if(ConfigHelper.nowUser!=null)  
  28. {  
  29. //進入用戶首頁   
  30. Intent intent = new Intent();  
  31. intent.setClass(LoginActivity.this, HomeActivity.class);  
  32. startActivity(intent);  
  33. }  
  34. }  

     在上面的GoHome方法中ConfigHelper.nowUser是類型爲UserInfo的static類型用來保存當前登錄賬號的信息,替代web中session使用。
最後添加如下方法,用來當這個登錄LoginActivity結束的時候保存當前選擇的賬戶名稱到SharedPreferences中,以便幫用戶記住登錄賬號的功能,就是前面的initUser() 初始賬號的方法中會獲取保存在SharedPreferences中的賬戶名稱,代碼如下:

  1. @Override  
  2. protected void onStop() {  
  3. //獲得SharedPreferences對象   
  4. SharedPreferences MyPreferences = getSharedPreferences(Select_Name, Activity.MODE_PRIVATE);  
  5. //獲得SharedPreferences.Editor對象   
  6. SharedPreferences.Editor editor = MyPreferences.edit();  
  7. //保存組件中的值   
  8. editor.putString("name", iconSelect.getText().toString());  
  9. editor.commit();  
  10. super.onStop();  
  11. }  

至此登錄頁面功能篇結束,請繼續關注下一篇。

 

android開發我的新浪微博客戶端-用戶首頁面UI篇(5.1) 

 

12.png

6 天前 上傳
下載附件 (101.43 KB)

 

在前篇完成了用戶登錄功能後開始用戶首頁的開發,用戶的首頁主要的內容是當前登錄用戶關注的微博列表,本篇先來講講UI的實現,效果如上圖,整個頁面分爲上、中、下三部分,上面部分是工具條,顯示當前登錄用戶的暱稱以及寫微博、刷新兩個功能按鈕;中間部分是當前用戶關注的最新微博列表,下面部分是功能切換欄,用來進行各個功能之間的切換。

      首先新建名爲HomeActivity.java的Activity作爲用戶首頁,然後在res/layout目錄下新建名爲home.xml的Layout,具體代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:id="@+id/layout"  
  5. android:orientation="vertical"  
  6. android:layout_width="fill_parent"  
  7. android:layout_height="fill_parent">  
  8.   
  9. <RelativeLayout  
  10. android:layout_width="fill_parent"  
  11. android:layout_height="wrap_content"  
  12. android:layout_margin="3px">  
  13. <ImageView  
  14. android:layout_width="wrap_content"  
  15. android:layout_height="wrap_content"  
  16. android:src="@drawable/logo_ss">  
  17. </ImageView>  
  18. <TextView  
  19. android:id="@+id/showName"  
  20. android:layout_width="wrap_content"  
  21. android:layout_height="wrap_content"  
  22. android:layout_centerInParent="true"  
  23. android:textColor="#343434"  
  24. android:textSize="15px">  
  25. </TextView>  
  26. <ImageButton  
  27. android:id="@+id/writeBtn"  
  28. android:layout_width="wrap_content"  
  29. android:layout_height="wrap_content"  
  30. android:layout_toLeftOf="@+id/refreshBtn"  
  31. android:background="@drawable/btn_write_selector">  
  32. </ImageButton>  
  33. <ImageButton  
  34. android:id="@+id/refreshBtn"  
  35. android:layout_width="wrap_content"  
  36. android:layout_height="wrap_content"  
  37. android:layout_alignParentRight="true"  
  38. android:layout_marginLeft="12px"  
  39. android:background="@drawable/btn_refresh_selector">  
  40. </ImageButton>  
  41. </RelativeLayout>  
  42.   
  43. <LinearLayout  
  44. android:layout_width="fill_parent"  
  45. android:layout_height="wrap_content"  
  46. android:background="@drawable/hr">  
  47. </LinearLayout>  
  48.   
  49. <RelativeLayout  
  50. android:layout_width="fill_parent"  
  51. android:layout_height="fill_parent">  
  52.   
  53. <ListView  
  54. android:id="@+id/Msglist"  
  55. android:layout_width="fill_parent"  
  56. android:layout_height="match_parent"  
  57. android:divider="@drawable/divider"  
  58. android:dividerHeight="2px"  
  59. android:layout_margin="0px"  
  60. android:background="#BBFFFFFF"  
  61. android:cacheColorHint="#00000000"  
  62. android:layout_above="@+id/toolbarLayout"  
  63. android:fastScrollEnabled="true"   
  64. android:focusable="true">  
  65. </ListView>  
  66.   
  67. <LinearLayout  
  68. android:id="@+id/loadingLayout"  
  69. android:layout_width="wrap_content"  
  70. android:layout_height="wrap_content"  
  71. android:orientation="vertical"  
  72. android:visibility="invisible"  
  73. android:layout_centerInParent="true">  
  74. <ProgressBar  
  75. android:id="@+id/loading"  
  76. android:layout_width="31px"  
  77. android:layout_height="31px"  
  78. android:layout_gravity="center"  
  79. style="@style/progressStyle">  
  80. </ProgressBar>  
  81. <TextView  
  82. android:layout_width="wrap_content"  
  83. android:layout_height="wrap_content"  
  84. android:text="正在載入"  
  85. android:textSize="12px"  
  86. android:textColor="#9c9c9c"  
  87. android:layout_gravity="center"  
  88. android:layout_below="@+id/loading">  
  89. </TextView>  
  90. </LinearLayout>  
  91.   
  92.   
  93. <LinearLayout  
  94. android:id="@+id/toolbarLayout"  
  95. android:layout_width="fill_parent"  
  96. android:layout_height="44dip"  
  97. android:layout_alignParentBottom="true">  
  98. </LinearLayout>  
  99. </RelativeLayout>  
  100. </LinearLayout>  
 

      這個佈局首先是一個豎直的根LinearLayout,在這個根LinearLayout裏面分別是兩個RelativeLayout, 第一個RelativeLayout 用來顯示頁面的工具條,第二個RelativeLayout用來顯示列表以及底部的功能欄,特別主要在這第二個RelativeLayout中有一個id爲loadingLayout的LinearLayout是用來顯示數據載入中的動畫,它的android:visibility屬性爲invisible(也可以設置成gone,區別:invisible這個View在ViewGroupt中仍保留它的位置,不重新layout
gone>不可見,但這個View在ViewGroupt中不保留位置,重新layout,那後面的view就會取代他的位置。 ),也就是一開始不顯示的意思,接下來看看
<ProgressBar

android:id="@+id/loading"
        android:layout_width="31px"
        android:layout_height="31px"

android:layout_gravity="center"

style="@style/progressStyle">
</ProgressBar>
      這個ProgressBar控件就是用來顯示動畫用的,關鍵就是 style="@style/progressStyle",在res/values目錄下新建名爲loadingstyles.xml,內容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <resources>  
  3. <mce:style name="progressStyle" width="38" height="38" parent="@android:style/Widget.ProgressBar.Small"><!--  
  4. <item name="android:indeterminateDrawable">@anim/loading</item>  
  5. --></mce:style><style name="progressStyle" width="38" height="38" parent="@android:style/Widget.ProgressBar.Small" mce_bogus="1"><item name="android:indeterminateDrawable">@anim/loading</item></style>  
  6. </resources>  
 

接着準備好r1.png - r8.png,

 a7.png

6 天前 上傳
下載附件 (998 Bytes)

a6.png

6 天前 上傳
下載附件 (980 Bytes)

a5.png

6 天前 上傳
下載附件 (1013 Bytes)

a4.png

6 天前 上傳
下載附件 (1014 Bytes)

a3.png

6 天前 上傳
下載附件 (986 Bytes)

a2.png

6 天前 上傳
下載附件 (992 Bytes)

a1.png

6 天前 上傳
下載附件 (1010 Bytes)

a8.png

6 天前 上傳
下載附件 (1 KB)

八張不同的小圖片分別代表每旋轉45度圖片,八張剛好是360度。把這些圖片添加到res/drawable-mdpi目錄中。然後在res/anim目錄下新建名爲loading.xml動畫文件,內容如下:

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <animation-list android:oneshot="false"  
  3. xmlns:android="http://schemas.android.com/apk/res/android">  
  4. <item android:duration="200" android:drawable="@drawable/r1" />  
  5. <item android:duration="200" android:drawable="@drawable/r2" />  
  6. <item android:duration="200" android:drawable="@drawable/r3" />  
  7. <item android:duration="200" android:drawable="@drawable/r4" />  
  8. <item android:duration="200" android:drawable="@drawable/r5" />  
  9. <item android:duration="200" android:drawable="@drawable/r6" />  
  10. <item android:duration="200" android:drawable="@drawable/r7" />  
  11. <item android:duration="200" android:drawable="@drawable/r8" />  
  12. </animation-list>  
 

 

    關於Android播放動畫實現我是參考http://www.eoeandroid.com/forum.php?mod=viewthread&tid=67311&extra=
    本篇到這裏就結束了,下一篇繼續講用戶首頁的功能實現,請關注。

android開發我的新浪微博客戶端-用戶首頁面功能篇(5.2)

13.png

6 天前 上傳
下載附件 (101.43 KB)

 


       上一篇完成用戶首頁的UI實現,本篇接下來講功能部分的實現,本頁面主要的功能就用戶關注的最新微博列表,從上一篇中知道本列表是用ID爲Msglist的ListView控件來實現,本篇的主要就講解如果獲取微博列表數據給這個ListView提供顯示數據。ListView每一條子數據分別由用戶頭像、用戶暱稱、發佈時間、是否包含照片、微博內容這五部分組成,根據這五部分定義一個名爲WeiBoInfo.java實體類,代碼如下:

  1. public class WeiBoInfo {  
  2. //文章id   
  3. private String id;  
  4. public String getId(){  
  5. return id;  
  6. }  
  7. public void setId(String id){  
  8. this.id=id;  
  9. }  
  10. //發佈人id   
  11. private String userId;  
  12. public String getUserId(){  
  13. return userId;  
  14. }  
  15. public void setUserId(String userId){  
  16. this.userId=userId;  
  17. }  
  18.   
  19. //發佈人名字   
  20. private String userName;  
  21. public String getUserName(){  
  22. return userName;  
  23. }  
  24. public void setUserName(String userName){  
  25. this.userName=userName;  
  26. }  
  27.   
  28. //發佈人頭像   
  29. private String userIcon;  
  30. public String getUserIcon(){  
  31. return userIcon;  
  32. }  
  33. public void setUserIcon(String userIcon){  
  34. this.userIcon=userIcon;  
  35. }  
  36.   
  37. //發佈時間   
  38. private String time;  
  39. public String getTime(){  
  40. return time;  
  41. }  
  42. public void setTime(String time)  
  43. {  
  44. this.time=time;  
  45. }  
  46.   
  47. //是否有圖片   
  48. private Boolean haveImage=false;  
  49. public Boolean getHaveImage(){  
  50. return haveImage;  
  51. }  
  52. public void setHaveImage(Boolean haveImage){  
  53. this.haveImage=haveImage;  
  54. }  
  55.   
  56. //文章內容   
  57. private String text;  
  58. public String getText(){  
  59. return text;  
  60. }  
  61. public void setText(String text){  
  62. this.text=text;  
  63. }  
  64.   
  65. }  
 

       然後在res/layout目錄下新建名爲weibo.xml的Layout用來控制ListView子項的顯示部件,代碼很簡單不多解釋了,直接看下面代碼:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3. xmlns:android="http://schemas.android.com/apk/res/android"  
  4. android:layout_width="wrap_content"  
  5. android:layout_height="wrap_content"  
  6. android:orientation="horizontal">  
  7. <ImageView  
  8. android:id="@+id/wbicon"  
  9. android:layout_width="wrap_content"  
  10. android:layout_height="wrap_content"  
  11. android:src="@drawable/usericon"  
  12. android:layout_margin="8px">  
  13. </ImageView>  
  14. <LinearLayout  
  15. android:layout_width="fill_parent"  
  16. android:layout_height="wrap_content"  
  17. android:orientation="vertical"  
  18. android:paddingLeft="0px"  
  19. android:paddingRight="5px"  
  20. android:layout_marginTop="5px"  
  21. android:layout_marginBottom="5px">  
  22. <RelativeLayout  
  23. android:layout_width="fill_parent"  
  24. android:layout_height="wrap_content">  
  25. <TextView  
  26. android:id="@+id/wbuser"  
  27. android:layout_width="wrap_content"  
  28. android:layout_height="wrap_content"  
  29. android:textSize="15px"  
  30. android:textColor="#424952"  
  31. android:layout_alignParentLeft="true">  
  32. </TextView>  
  33. <ImageView  
  34. android:id="@+id/wbimage"  
  35. android:layout_width="wrap_content"  
  36. android:layout_height="wrap_content"  
  37. android:layout_marginTop="3px"  
  38. android:layout_marginRight="5px"  
  39. android:layout_toLeftOf="@+id/wbtime">  
  40. </ImageView>  
  41. <TextView  
  42. android:id="@+id/wbtime"  
  43. android:layout_width="wrap_content"  
  44. android:layout_height="wrap_content"  
  45. android:layout_alignParentRight="true"  
  46. android:textColor="#f7a200"  
  47. android:textSize="12px">  
  48. </TextView>  
  49. </RelativeLayout>  
  50. <TextView  
  51. android:id="@+id/wbtext"  
  52. android:layout_width="wrap_content"  
  53. android:layout_height="wrap_content"  
  54. android:textColor="#424952"  
  55. android:textSize="13px"  
  56. android:layout_marginTop="4px">  
  57. </TextView>  
  58. </LinearLayout>  
  59. </LinearLayout>  
 

接下來爲列表控件定義一個數據Adapter,代碼如下:

  1. private List<WeiBoInfo> wbList;  
  2.   
  3. //微博列表Adapater   
  4. public class WeiBoAdapater extends BaseAdapter{  
  5.   
  6. private AsyncImageLoader asyncImageLoader;  
  7.   
  8. @Override  
  9. public int getCount() {  
  10. return wbList.size();  
  11. }  
  12.   
  13. @Override  
  14. public Object getItem(int position) {  
  15. return wbList.get(position);  
  16. }  
  17.   
  18. @Override  
  19. public long getItemId(int position) {  
  20. return position;  
  21. }  
  22.   
  23. @Override  
  24. public View getView(int position, View convertView, ViewGroup parent) {  
  25. asyncImageLoader = new AsyncImageLoader();  
  26. convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.weibo, null);  
  27. WeiBoHolder wh = new WeiBoHolder();  
  28. wh.wbicon = (ImageView) convertView.findViewById(R.id.wbicon);  
  29. wh.wbtext = (TextView) convertView.findViewById(R.id.wbtext);  
  30. wh.wbtime = (TextView) convertView.findViewById(R.id.wbtime);  
  31. wh.wbuser = (TextView) convertView.findViewById(R.id.wbuser);  
  32. wh.wbimage=(ImageView) convertView.findViewById(R.id.wbimage);  
  33. WeiBoInfo wb = wbList.get(position);  
  34. if(wb!=null){  
  35. convertView.setTag(wb.getId());  
  36. wh.wbuser.setText(wb.getUserName());  
  37. wh.wbtime.setText(wb.getTime());  
  38. wh.wbtext.setText(wb.getText(), TextView.BufferType.SPANNABLE);  
  39. textHighlight(wh.wbtext,new char[]{'#'},new char[]{'#'});  
  40. textHighlight(wh.wbtext,new char[]{'@'},new char[]{':',' '});  
  41. textHighlight2(wh.wbtext,"http://"," ");  
  42.   
  43. if(wb.getHaveImage()){  
  44. wh.wbimage.setImageResource(R.drawable.images);  
  45. }  
  46. Drawable cachedImage = asyncImageLoader.loadDrawable(wb.getUserIcon(),wh.wbicon, new ImageCallback(){  
  47.   
  48. @Override  
  49. public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl) {  
  50. imageView.setImageDrawable(imageDrawable);  
  51. }  
  52.   
  53. });  
  54. if (cachedImage == null) {  
  55. wh.wbicon.setImageResource(R.drawable.usericon);  
  56. }else{  
  57. wh.wbicon.setImageDrawable(cachedImage);  
  58. }  
  59. }  
  60.   
  61. return convertView;  
  62. }  
 

      上面的這個Adapter實現沒有什麼特別的很普通,不過這個中使用了AsyncImageLoader的方法,這個是用來實現用戶頭像圖標的異步載入顯示,這樣能提高列表顯示的速度,提高用戶體驗,AsyncImageLoader的代碼如下:

  1. public class AsyncImageLoader {  
  2. //SoftReference是軟引用,是爲了更好的爲了系統回收變量   
  3. private HashMap<String, SoftReference<Drawable>> imageCache;  
  4. public AsyncImageLoader() {  
  5. imageCache = new HashMap<String, SoftReference<Drawable>>();  
  6. }  
  7.   
  8. public Drawable loadDrawable(final String imageUrl,final ImageView imageView, final ImageCallback imageCallback){  
  9. if (imageCache.containsKey(imageUrl)) {  
  10. //從緩存中獲取   
  11. SoftReference<Drawable> softReference = imageCache.get(imageUrl);  
  12. Drawable drawable = softReference.get();  
  13. if (drawable != null) {  
  14. return drawable;  
  15. }  
  16. }  
  17. final Handler handler = new Handler() {  
  18. public void handleMessage(Message message) {  
  19. imageCallback.imageLoaded((Drawable) message.obj, imageView,imageUrl);  
  20. }  
  21. };  
  22. //建立新一個新的線程下載圖片   
  23. new Thread() {  
  24. @Override  
  25. public void run() {  
  26. Drawable drawable = loadImageFromUrl(imageUrl);  
  27. imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));  
  28. Message message = handler.obtainMessage(0, drawable);  
  29. handler.sendMessage(message);  
  30. }  
  31. }.start();  
  32. return null;  
  33. }  
  34.   
  35. public static Drawable loadImageFromUrl(String url){  
  36. URL m;  
  37. InputStream i = null;  
  38. try {  
  39. m = new URL(url);  
  40. i = (InputStream) m.getContent();  
  41. catch (MalformedURLException e1) {  
  42. e1.printStackTrace();  
  43. catch (IOException e) {  
  44. e.printStackTrace();  
  45. }  
  46. Drawable d = Drawable.createFromStream(i, "src");  
  47. return d;  
  48. }  
  49.   
  50. //回調接口   
  51. public interface ImageCallback {  
  52. public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl);  
  53. }  
  54. }  
 

     完成上述的工作後,接下來就是顯示微薄列表, 在HomeActivity的onCreate方法中調用loadList();代碼如下:

  1. @Override  
  2.     public void onCreate(Bundle savedInstanceState) {  
  3.         super.onCreate(savedInstanceState);  
  4.         setContentView(R.layout.home);  
  5.           
  6.         。。。。。。  
  7.         loadList();  
  8.     }  
  9.   
  10. private void loadList(){  
  11.         if(ConfigHelper.nowUser==null)  
  12.         {  
  13.               
  14.         }  
  15.         else  
  16.         {  
  17.             user=ConfigHelper.nowUser;  
  18.             //顯示當前用戶名稱   
  19.             TextView showName=(TextView)findViewById(R.id.showName);  
  20.             showName.setText(user.getUserName());  
  21.               
  22.             OAuth auth=new OAuth();  
  23.             String url = "http://api.t.sina.com.cn/statuses/friends_timeline.json";  
  24.             List params=new ArrayList();  
  25.             params.add(new BasicNameValuePair("source", auth.consumerKey));   
  26.             HttpResponse response =auth.SignRequest(user.getToken(), user.getTokenSecret(), url, params);  
  27.             if (200 == response.getStatusLine().getStatusCode()){  
  28.                 try {  
  29.                     InputStream is = response.getEntity().getContent();  
  30.                     Reader reader = new BufferedReader(new InputStreamReader(is), 4000);  
  31.                     StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());  
  32.                     try {  
  33.                         char[] tmp = new char[1024];  
  34.                         int l;  
  35.                         while ((l = reader.read(tmp)) != -1) {  
  36.                             buffer.append(tmp, 0, l);  
  37.                         }  
  38.                     } finally {  
  39.                         reader.close();  
  40.                     }  
  41.                     String string = buffer.toString();  
  42.                     //Log.e("json", "rs:" + string);   
  43.                     response.getEntity().consumeContent();  
  44.                     JSONArray data=new JSONArray(string);  
  45.                     for(int i=0;i<data.length();i++)  
  46.                     {  
  47.                         JSONObject d=data.getJSONObject(i);  
  48.                         //Log.e("json", "rs:" + d.getString("created_at"));   
  49.                         if(d!=null){  
  50.                             JSONObject u=d.getJSONObject("user");  
  51.                             if(d.has("retweeted_status")){  
  52.                                 JSONObject r=d.getJSONObject("retweeted_status");  
  53.                             }  
  54.                               
  55.                             //微博id   
  56.                             String id=d.getString("id");  
  57.                             String userId=u.getString("id");  
  58.                             String userName=u.getString("screen_name");  
  59.                             String userIcon=u.getString("profile_image_url");  
  60.                             Log.e("userIcon", userIcon);  
  61.                             String time=d.getString("created_at");  
  62.                             String text=d.getString("text");  
  63.                             Boolean haveImg=false;  
  64.                             if(d.has("thumbnail_pic")){  
  65.                                 haveImg=true;  
  66.                                 //String thumbnail_pic=d.getString("thumbnail_pic");   
  67.                                 //Log.e("thumbnail_pic", thumbnail_pic);   
  68.                             }  
  69.                               
  70.                             Date date=new Date(time);  
  71.                             time=ConvertTime(date);  
  72.                             if(wbList==null){  
  73.                                 wbList=new ArrayList<WeiBoInfo>();  
  74.                             }  
  75.                             WeiBoInfo w=new WeiBoInfo();  
  76.                             w.setId(id);  
  77.                             w.setUserId(userId);  
  78.                             w.setUserName(userName);  
  79.                             w.setTime(time);  
  80.                             w.setText(text);  
  81.                               
  82.                             w.setHaveImage(haveImg);  
  83.                             w.setUserIcon(userIcon);  
  84.                             wbList.add(w);  
  85.                         }  
  86.                     }  
  87.                       
  88.                 }catch (IllegalStateException e) {  
  89.                     e.printStackTrace();  
  90.                 } catch (IOException e) {  
  91.                     e.printStackTrace();  
  92.                 } catch (JSONException e) {  
  93.                     e.printStackTrace();  
  94.                 }   
  95.             }  
  96.               
  97.             if(wbList!=null)  
  98.             {  
  99.                 WeiBoAdapater adapater = new WeiBoAdapater();  
  100.                 ListView Msglist=(ListView)findViewById(R.id.Msglist);  
  101.                 Msglist.setOnItemClickListener(new OnItemClickListener(){  
  102.                     @Override  
  103.                     public void onItemClick(AdapterView<?> arg0, View view,int arg2, long arg3) {  
  104.                         Object obj=view.getTag();  
  105.                         if(obj!=null){  
  106.                             String id=obj.toString();  
  107.                             Intent intent = new Intent(HomeActivity.this,ViewActivity.class);  
  108.                             Bundle b=new Bundle();  
  109.                             b.putString("key", id);  
  110.                             intent.putExtras(b);  
  111.                             startActivity(intent);  
  112.                         }  
  113.                     }  
  114.                       
  115.                 });  
  116.                 Msglist.setAdapter(adapater);  
  117.             }  
  118.         }  
  119.         loadingLayout.setVisibility(View.GONE);  
  120.     }  
 

      上面的loadList() 方法通過新浪Api接口http://api.t.sina.com.cn/statuses/friends_timeline.json獲取當前登錄用戶及其所關注用戶的最新微博消息,然後顯示到列表中。
      這樣就完成了用戶首頁功能的開發。

android開發我的新浪微博客戶端-閱讀微博UI篇(6.1)

14.png

6 天前 上傳
下載附件 (154.98 KB)

 

      上一篇完成了微博列表的功能,本篇接着做預讀微博的功能,本篇主要講講UI部分的實現,最終實現的效果如上圖所示。整個顯示頁面從上往下分爲四部分,第一部分頂部工具條、第二部分作者頭像和名稱、第三部分微博正文、第四部分功能按鈕區。新建名爲ViewActivity.java作爲閱讀微博的頁面,再res/layout目錄下新建名爲view.xml的Layout,代碼如下:

  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:id="@+id/layout"  
  5.   android:orientation="vertical"  
  6.   android:layout_width="fill_parent"  
  7.   android:layout_height="fill_parent">  
  8.   <RelativeLayout  
  9.   android:layout_width="fill_parent"  
  10.   android:layout_height="wrap_content"  
  11.   android:layout_margin="3px">  
  12.   <ImageView  
  13.   android:layout_width="wrap_content"  
  14.   android:layout_height="wrap_content"  
  15.   android:src="@drawable/logo_ss">  
  16.   </ImageView>  
  17.   <TextView  
  18.   android:id="@+id/showName"  
  19.   android:layout_width="wrap_content"  
  20.   android:layout_height="wrap_content"  
  21.   android:layout_centerInParent="true"  
  22.   android:textColor="#343434"  
  23.   android:text="閱讀微博"  
  24.   android:textSize="16px">  
  25.   </TextView>  
  26.   <ImageButton  
  27.   android:id="@+id/returnBtn"  
  28.   android:layout_width="wrap_content"  
  29.   android:layout_height="wrap_content"  
  30.   android:layout_toLeftOf="@+id/homeBtn"  
  31.   android:background="@drawable/bnt_return_selector">  
  32.   </ImageButton>  
  33.   <ImageButton  
  34.   android:id="@+id/homeBtn"  
  35.   android:layout_width="wrap_content"  
  36.   android:layout_height="wrap_content"  
  37.   android:layout_alignParentRight="true"  
  38.   android:layout_marginLeft="12px"  
  39.   android:background="@drawable/btn_home_selector">  
  40.   </ImageButton>  
  41.   </RelativeLayout>  
  42.   <LinearLayout  
  43.   android:layout_width="fill_parent"  
  44.   android:layout_height="wrap_content"  
  45.   android:background="@drawable/hr">  
  46.   </LinearLayout>  
  47.     
  48.   <RelativeLayout  
  49.   android:id="@+id/user_bg"  
  50.   android:layout_width="fill_parent"  
  51.   android:layout_height="78px"  
  52.   android:paddingTop="8px"  
  53.   android:paddingLeft="15px"  
  54.   android:background="@drawable/u_bg_v">  
  55.       <ImageView  
  56.       android:id="@+id/user_icon"  
  57.       android:layout_width="wrap_content"  
  58.       android:layout_height="wrap_content"  
  59.       android:layout_alignParentLeft="true"  
  60.       android:src="@drawable/usericon">  
  61.       </ImageView>  
  62.       <TextView  
  63.       android:id="@+id/user_name"  
  64.       android:layout_width="wrap_content"  
  65.       android:layout_height="wrap_content"  
  66.       android:layout_toRightOf="@+id/user_icon"  
  67.       android:layout_marginLeft="10px"  
  68.       android:layout_marginTop="18px"  
  69.       android:textColor="#000000">  
  70.       </TextView>  
  71.       <ImageView  
  72.       android:layout_width="wrap_content"  
  73.       android:layout_height="wrap_content"  
  74.       android:layout_alignParentRight="true"  
  75.       android:layout_marginRight="5px"  
  76.       android:layout_marginTop="10px"  
  77.       android:src="@drawable/sjjt">  
  78.       </ImageView>  
  79.   </RelativeLayout>  
  80.   <RelativeLayout  
  81.     android:layout_width="fill_parent"  
  82.     android:layout_height="fill_parent">  
  83.         <ScrollView  
  84.         android:layout_width="fill_parent"  
  85.         android:layout_height="fill_parent"  
  86.         android:paddingLeft="17px"  
  87.         android:paddingRight="17px"  
  88.         android:paddingBottom="5px"  
  89.         android:layout_above="@+id/menu_layout">  
  90.         <LinearLayout  
  91.         android:layout_width="fill_parent"  
  92.         android:layout_height="fill_parent"  
  93.         android:orientation="vertical">  
  94.             <TextView  
  95.             android:id="@+id/text"  
  96.             android:layout_width="wrap_content"  
  97.             android:layout_height="wrap_content"  
  98.             android:textColor="#000000"  
  99.             android:textSize="15px">  
  100.             </TextView>  
  101.             <ImageView  
  102.             android:id="@+id/pic"  
  103.             android:layout_width="wrap_content"  
  104.             android:layout_height="wrap_content">  
  105.             </ImageView>  
  106.         </LinearLayout>  
  107.         </ScrollView>  
  108.           
  109.         <LinearLayout  
  110.         android:id="@+id/loadingLayout"  
  111.         android:layout_width="wrap_content"  
  112.         android:layout_height="wrap_content"  
  113.         android:orientation="vertical"  
  114.         android:visibility="gone"  
  115.         android:layout_centerInParent="true">  
  116.             <ProgressBar  
  117.             android:id="@+id/loading"  
  118.             android:layout_width="31px"  
  119.             android:layout_height="31px"  
  120.             android:layout_gravity="center"  
  121.             style="@style/progressStyle">  
  122.             </ProgressBar>  
  123.             <TextView  
  124.             android:layout_width="wrap_content"  
  125.             android:layout_height="wrap_content"  
  126.             android:text="正在載入"  
  127.             android:textSize="12px"  
  128.             android:textColor="#9c9c9c"  
  129.             android:layout_gravity="center"  
  130.             android:layout_below="@+id/loading">  
  131.             </TextView>  
  132.         </LinearLayout>  
  133.   
  134.         <TableLayout  
  135.         android:id="@+id/menu_layout"  
  136.         android:layout_width="fill_parent"  
  137.         android:layout_height="wrap_content"  
  138.         android:gravity="center"  
  139.         android:layout_alignParentBottom="true"  
  140.         android:layout_marginBottom="5px">  
  141.             <TableRow  
  142.             android:layout_width="wrap_content"  
  143.             android:layout_height="wrap_content"  
  144.             android:gravity="center">  
  145.             <Button  
  146.             android:id="@+id/btn_gz"  
  147.             android:layout_width="wrap_content"  
  148.             android:layout_height="wrap_content"  
  149.             android:textColor="#3882b8"  
  150.             android:textSize="15px"  
  151.             android:text="        關注(1231)"  
  152.             android:background="@drawable/lt_selector">  
  153.             </Button>  
  154.             <Button  
  155.             android:id="@+id/btn_pl"  
  156.             android:layout_width="wrap_content"  
  157.             android:layout_height="wrap_content"  
  158.             android:textColor="#3882b8"  
  159.             android:textSize="15px"  
  160.             android:text="        評論(31)"  
  161.             android:background="@drawable/rt_selector">  
  162.             </Button>  
  163.             </TableRow>  
  164.             <TableRow  
  165.             android:layout_width="wrap_content"  
  166.             android:layout_height="wrap_content"  
  167.             android:gravity="center">  
  168.             <Button  
  169.             android:layout_width="wrap_content"  
  170.             android:layout_height="wrap_content"  
  171.             android:textColor="#3882b8"  
  172.             android:textSize="15px"  
  173.             android:layout_gravity="left"  
  174.             android:text="刷新"  
  175.             android:background="@drawable/lb_selector">  
  176.             </Button>  
  177.             <Button  
  178.             android:layout_width="wrap_content"  
  179.             android:layout_height="wrap_content"  
  180.             android:textColor="#3882b8"  
  181.             android:textSize="15px"  
  182.             android:text="收藏"  
  183.             android:background="@drawable/rb_selector">  
  184.             </Button>  
  185.             </TableRow>  
  186.               
  187.         </TableLayout>  
  188.           
  189.   </RelativeLayout>  
  190. </LinearLayout>   
 

     上面這個佈局實現起來並不複雜, 主要看看功能按鈕區的4個按鈕的點擊上去的切換背景的效果,以關注按鈕爲例子看這行設置,android:background="@drawable/lt_selector",在res/drawable-mdpi目錄下新建名爲lt_selector.xml用來實現點擊上去切換圖片的效果,具體代碼如下:

  1. <?xml version="1.0" encoding="UTF-8"?>   
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">   
  3. <item android:state_focused="false" android:state_selected="false" android:state_pressed="false" android:drawable="@drawable/tbtn_1" />   
  4. <item android:state_pressed="true" android:drawable="@drawable/tbtn_h_1" />   
  5. </selector>   
 

     本篇雖然看layout文件非常的長,其實仔細看看非常的簡單了沒有什麼難和複雜的了,就是按照前面的經驗控制好圖片以及控件的顯示位置和樣式即可,本篇中用了一個ScrollView控件這個是前面沒有用到過的,主要是用來當微博的內容超出顯示區域的時候出現滾動條用的這個非常容易使用,所以就簡單寫一下到此結束了,請繼續關注下一篇閱讀微博的功能篇。


android開發我的新浪微博客戶端-閱讀微博功能篇(6.2)

15.png

6 天前 上傳
下載附件 (154.98 KB)

 

注:最近由於OAuth上傳圖片碰到了難題,一直在做這方面的研究導致博客很久沒有更新。

  在上面一篇中已經實現了預讀微博的UI界面,效果如上圖,接下來完成功能部分的代碼,當用戶在上一個列表界面的列表中點擊某一條微博的時候顯示這個閱讀微博的界面,在這個界面中根據傳來的微博ID,然後根據這個ID通過api獲取微博的具體內容進行顯示。

  在ViewActivity.class的onCreate方法中添加如下代碼:

  1. private UserInfo user;  
  2. private String key="";  
  3. @Override  
  4. public void onCreate(Bundle savedInstanceState) {  
  5. super.onCreate(savedInstanceState);  
  6. setContentView(R.layout.view);  
  7.   
  8. 。。。。。  
  9.   
  10. //獲取上一個頁面傳遞過來的key,key爲某一條微博的id   
  11. Intent i=this.getIntent();  
  12. if(!i.equals(null)){  
  13. Bundle b=i.getExtras();  
  14. if(b!=null){  
  15. if(b.containsKey("key")){  
  16. key = b.getString("key");  
  17. view(key);  
  18. }  
  19. }  
  20. }  
  21. }  
 

 

 接下來就是view方法具體獲取微博內容的方法,在這個方法中如果獲取的本條微博如果包含圖片那麼就用前面AsyncImageLoader的方法異步載入圖片並且進行顯示,同時在這個方法中還要獲取本條微博被轉發的次數以及評論的次數,具體代碼如下:

  1. private void view(String id){  
  2. user=ConfigHelper.nowUser;  
  3. OAuth auth=new OAuth();  
  4. String url = "http://api.t.sina.com.cn/statuses/show/:id.json";  
  5. List params=new ArrayList();  
  6. params.add(new BasicNameValuePair("source", auth.consumerKey));   
  7. params.add(new BasicNameValuePair("id", id));  
  8. HttpResponse response =auth.SignRequest(user.getToken(), user.getTokenSecret(), url, params);  
  9. if (200 == response.getStatusLine().getStatusCode()){  
  10. try {  
  11. InputStream is = response.getEntity().getContent();  
  12. Reader reader = new BufferedReader(new InputStreamReader(is), 4000);  
  13. StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());  
  14. try {  
  15. char[] tmp = new char[1024];  
  16. int l;  
  17. while ((l = reader.read(tmp)) != -1) {  
  18. buffer.append(tmp, 0, l);  
  19. }  
  20. finally {  
  21. reader.close();  
  22. }  
  23. String string = buffer.toString();  
  24. //Log.e("json", "rs:" + string);   
  25. response.getEntity().consumeContent();  
  26. JSONObject data=new JSONObject(string);  
  27. if(data!=null){  
  28. JSONObject u=data.getJSONObject("user");  
  29. String userName=u.getString("screen_name");  
  30. String userIcon=u.getString("profile_image_url");  
  31. Log.e("userIcon", userIcon);  
  32. String time=data.getString("created_at");  
  33. String text=data.getString("text");  
  34.   
  35. TextView utv=(TextView)findViewById(R.id.user_name);  
  36. utv.setText(userName);  
  37. TextView ttv=(TextView)findViewById(R.id.text);  
  38. ttv.setText(text);  
  39.   
  40. ImageView iv=(ImageView)findViewById(R.id.user_icon);  
  41. AsyncImageLoader asyncImageLoader = new AsyncImageLoader();  
  42. Drawable cachedImage = asyncImageLoader.loadDrawable(userIcon,iv, new ImageCallback(){  
  43. @Override  
  44. public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl) {  
  45.   
  46. imageView.setImageDrawable(imageDrawable);  
  47. }  
  48. });  
  49. if (cachedImage == null)   
  50. {  
  51. iv.setImageResource(R.drawable.usericon);  
  52. }  
  53. else  
  54. {  
  55. iv.setImageDrawable(cachedImage);  
  56. }  
  57. if(data.has("bmiddle_pic")){  
  58. String picurl=data.getString("bmiddle_pic");  
  59. String picurl2=data.getString("original_pic");  
  60.   
  61. ImageView pic=(ImageView)findViewById(R.id.pic);  
  62. pic.setTag(picurl2);  
  63. pic.setOnClickListener(new OnClickListener() {  
  64. @Override  
  65. public void onClick(View v) {  
  66. Object obj=v.getTag();  
  67. Intent intent = new Intent(ViewActivity.this,ImageActivity.class);  
  68. Bundle b=new Bundle();  
  69. b.putString("url", obj.toString());  
  70. intent.putExtras(b);  
  71. startActivity(intent);  
  72. }  
  73. });  
  74. Drawable cachedImage2 = asyncImageLoader.loadDrawable(picurl,pic, new ImageCallback(){  
  75. @Override  
  76. public void imageLoaded(Drawable imageDrawable,ImageView imageView, String imageUrl) {  
  77. showImg(imageView,imageDrawable);  
  78. }  
  79. });  
  80. if (cachedImage2 == null)   
  81. {  
  82. //pic.setImageResource(R.drawable.usericon);   
  83. }  
  84. else  
  85. {  
  86. showImg(pic,cachedImage2);  
  87. }  
  88. }  
  89. }  
  90. }catch (IllegalStateException e) {  
  91. e.printStackTrace();  
  92. catch (IOException e) {  
  93. e.printStackTrace();  
  94. catch (JSONException e) {  
  95. e.printStackTrace();  
  96. }   
  97. }  
  98. url = "http://api.t.sina.com.cn/statuses/counts.json";  
  99. params=new ArrayList();  
  100. params.add(new BasicNameValuePair("source", auth.consumerKey));   
  101. params.add(new BasicNameValuePair("ids", id));  
  102. response =auth.SignRequest(user.getToken(), user.getTokenSecret(), url, params);  
  103. if (200 == response.getStatusLine().getStatusCode()){  
  104. try {  
  105. InputStream is = response.getEntity().getContent();  
  106. Reader reader = new BufferedReader(new InputStreamReader(is), 4000);  
  107. StringBuilder buffer = new StringBuilder((int) response.getEntity().getContentLength());  
  108. try {  
  109. char[] tmp = new char[1024];  
  110. int l;  
  111. while ((l = reader.read(tmp)) != -1) {  
  112. buffer.append(tmp, 0, l);  
  113. }  
  114. finally {  
  115. reader.close();  
  116. }  
  117. String string = buffer.toString();  
  118. response.getEntity().consumeContent();  
  119. JSONArray data=new JSONArray(string);  
  120. if(data!=null){  
  121. if(data.length()>0){  
  122. JSONObject d=data.getJSONObject(0);  
  123. String comments=d.getString("comments");  
  124. String rt=d.getString("rt");  
  125. Button btn_gz=(Button)findViewById(R.id.btn_gz);  
  126. btn_gz.setText(" 轉發("+rt+")");  
  127. Button btn_pl=(Button)findViewById(R.id.btn_pl);  
  128. btn_pl.setText(" 評論("+comments+")");  
  129. }  
  130. }  
  131. }  
  132. catch (IllegalStateException e) {  
  133. e.printStackTrace();  
  134. catch (IOException e) {  
  135. e.printStackTrace();  
  136. catch (JSONException e) {  
  137. e.printStackTrace();  
  138. }   
  139. }  
  140. }  
 

 

     在上面的方法中對於微博中包含的圖片顯示尺寸進行了特別的處理,如果直接把獲取的圖片顯示在ImageView中,因爲當圖片寬高超過手機屏幕的時候,系統會自動按照手機的屏幕按比例縮放圖片進行顯示,但是我發現一個現象圖片的高雖然是按照比例縮小了,但是圖片佔據的高仍舊是原來圖片的高度照成真實圖片和文字內容之間多了很高的一塊空白,這個現象非常的奇怪,所以我寫了如下方法進行處理:
 

  1. private void showImg(ImageView view,Drawable img){  
  2. int w=img.getIntrinsicWidth();  
  3. int h=img.getIntrinsicHeight();  
  4. Log.e("w", w+"/"+h);  
  5. if(w>300)  
  6. {  
  7. int hh=300*h/w;  
  8. Log.e("hh", hh+"");  
  9. LayoutParams para=view.getLayoutParams();  
  10. para.width=300;  
  11. para.height=hh;  
  12. view.setLayoutParams(para);  
  13. }  
  14. view.setImageDrawable(img);  
  15. }  

本篇到這裏就結束了,請繼續關注下一篇。

 

關於微博服務端API的OAuth認證實現

16.png

6 天前 上傳
下載附件 (18.96 KB)

 

新浪微博跟update相關的api已經掛了很多天了一直沒有恢復正常,返回錯誤:40070 Error limited application access api!,新浪開放平臺的論壇裏n多的人都在等這個恢復,新浪官方也相當的噁心出問題了連個公告都沒有,既不說什麼原因又不說什麼時候能恢復。還是有版主說是api正在升級禮拜1恢復正常今天都禮拜2了還是不行。基於這個原因我的android版的新浪微博客戶端已經停工好幾天了,剛好是跟update相關的一些功能。     客戶端開發不成了,就自己做做服務端程序,提供類似新浪微博rest api服務, api其實說簡單也很簡單了,無法是通過鏈接對外提供json或者xml格式的數據和接收外部提供的數據進去相應的存儲、刪除、更新等操作。過程中碰到的最麻煩的問題就是OAuth認證功能了,在做android版的新浪微博客戶端時候也花了蠻長的時間對OAuth認證進行研究,在客戶端原先是採用oauth-signpost開源項目,後來由於某些原因就放棄了這個開源類庫,自己重新寫了OAuth認證部分的實現, 現在做服務端的OAuth認證,其實有過做客戶端的經驗做服務端也差不多,簡單的說無非是客戶端對參數字符串進行簽名然後把簽名值傳輸到服務端,服務端也對同樣對參數字符串進行簽名,把從客戶端傳過來的簽名值進去比較,簡單的說就這麼個過程,具體實現肯定比這個要複雜多了,不明真相的同學可以google一下OAuth進行深入的學習研究了。      服務端程序用asp.net和C#編寫了而非java,理由很簡單本人對.net更加熟悉。由於想快速的實現效果採用了oauth-dot-net開源項目並沒有全部自己寫。  

  

  一、首先新建名爲Rest Api的ASP.NET Web應用程序,然後添加 oauth-dot-net開源項目相關的幾個dll(Castle.Core.dll、Castle.MicroKernel.dll、Castle.Windsor.dll、CommonServiceLocator.WindsorAdapter.dll、Microsoft.Practices.ServiceLocation.dll、OAuth.Net.Common.dll、OAuth.Net.Components.dll、OAuth.Net.ServiceProvider.dll)。  

   二、在Web.config文件裏添加相應的配置,具體可以參考OAuth.Net.Examples.EchoServiceProvider項目,然後在Global.asax.cs添加如下代碼:

 

  1. public override void Init()  
  2.         {  
  3.             IServiceLocator injector =  
  4.                 new WindsorServiceLocator(  
  5.                     new WindsorContainer(  
  6.                         new XmlInterpreter(  
  7.                             new ConfigResource("oauth.net.components"))));  
  8.   
  9.             ServiceLocator.SetLocatorProvider(() => injector);  
  10.         }  
 

     接下來是比較重要,就是request_token、authorize、access_token的實現,OAuth認證實現的幾個過程,不理解可以看android開發我的新浪微博客戶端-OAuth篇(2.1) ,具體代碼實現很多是參考OAuth.Net.Examples.EchoServiceProvider示例項目。     
三、 首先新建ConsumerStore.cs類,用來存儲Consumer信息,由於測試項目所以存儲在內存中並沒有考慮保存到數據庫,真實項目的時候請把相應的Consumer信息保存到數據庫中。Consumer信息對應新浪微博其實就是應用的App Key和App Secret,當開發者在新浪微博建一個新的應用獲取App Key和App Secret,所以完整的應該還需要一個開發一個提供給第三方開發者申請獲取App Key和App Secret的功能頁面,這裏就不具體實現,直接在代碼裏寫死了一個名爲測試應用的Consumer,App Key:2433927322,App Secret:87f042c9e8183cbde0f005a00db1529f,這個提供給客戶端測試用。 具體代碼如下:

  1. public sealed class ConsumerStore : InMemoryConsumerStore, IConsumerStore  
  2.     {  
  3.         internal static readonly IConsumer FixedConsumer = new OAuthConsumer("2433927322""87f042c9e8183cbde0f005a00db1529f""測試應用", ConsumerStatus.Valid);  
  4.   
  5.         public ConsumerStore()  
  6.         {  
  7.             this.ConsumerDictionary.Add(  
  8.                 ConsumerStore.FixedConsumer.Key,   
  9.                 ConsumerStore.FixedConsumer);  
  10.         }  
  11.   
  12.         public override bool Add(IConsumer consumer)  
  13.         {  
  14.             throw new NotSupportedException("Consumers cannot be added to this store--it is fixed.");  
  15.         }  
  16.   
  17.         public override bool Contains(string consumerKey)  
  18.         {  
  19.             return ConsumerStore.FixedConsumer.Key.Equals(consumerKey);  
  20.         }  
  21.   
  22.         public override bool Update(IConsumer consumer)  
  23.         {  
  24.             throw new NotSupportedException("Consumers cannot be updated in this store--it is fixed.");  
  25.         }  
  26.   
  27.         public override bool Remove(IConsumer consumer)  
  28.         {  
  29.             throw new NotSupportedException("Consumers cannot be removed from this store--it is fixed.");  
  30.         }  
  31.     }   
 

四、接下來就是request_token功能,新建RequestTokenHandler.cs ,這個是OAuth.Net.ServiceProvider.RequestTokenHandler子類,並且是httpHandlers所以需要在Web.config中添加httpHandlers配置,這個用來接收客戶端程序的請求,返回給客戶端程序Request Token和Request Secret用,具體代碼如下:

  1. public sealed class RequestTokenHandler : OAuth.Net.ServiceProvider.RequestTokenHandler  
  2. {   
  3. protected override void IssueRequestToken(HttpContext httpContext, OAuthRequestContext requestContext)  
  4. {  
  5. //產生RequestToken   
  6. IRequestToken token = this.GenerateRequestToken(httpContext, requestContext);  
  7.   
  8. requestContext.RequestToken = token;  
  9. Uri callbackUri;  
  10. if (Uri.TryCreate(requestContext.Parameters.Callback, UriKind.Absolute, out callbackUri))  
  11. {  
  12. if (!ServiceProviderContext.CallbackStore.ContainsCallback(token))  
  13. {  
  14. //保存Callback地址了   
  15. ServiceProviderContext.CallbackStore.AddCallback(token, callbackUri);  
  16. }  
  17. }  
  18. else  
  19. OAuthRequestException.ThrowParametersRejected(new string[] { Constants.CallbackParameter }, "Not a valid Uri.");  
  20.   
  21.   
  22. //把token.Token和token.Secret輸出到客戶端,   
  23. requestContext.ResponseParameters[Constants.TokenParameter] = token.Token;  
  24. requestContext.ResponseParameters[Constants.TokenSecretParameter] = token.Secret;  
  25. }  
  26.   
  27. protected override IRequestToken GenerateRequestToken(HttpContext httpContext, OAuthRequestContext requestContext)  
  28. {  
  29.   
  30. return ServiceProviderContext.TokenGenerator.CreateRequestToken(requestContext.Consumer, requestContext.Parameters);  
  31. }  
  32. }   
 

五、 接着是authorize功能,新建名爲authorize.aspx的頁面,用來給用戶輸入賬號和密碼進行授權的頁面,這個頁面很簡單具體如下圖,在這個頁面中獲取用戶輸入的賬戶和密碼跟數據庫中存儲的用戶賬號和密碼進行驗證,如果驗證通過返回之前客戶端提供的callback地址,並且給這個地址添加一個校驗碼,具體代碼如下:

  1. public partial class authorize : System.Web.UI.Page  
  2. {  
  3. protected void Page_Load(object sender, EventArgs e)  
  4. {  
  5.   
  6. }  
  7.   
  8. protected void Button1_Click(object sender, EventArgs e)  
  9. {  
  10. if (loginName.Text == "test" && password.Text == "123")  
  11. {  
  12. string toke = Request.Params["oauth_token"];  
  13. IRequestToken tk = ServiceProviderContext.TokenStore.GetRequestToken(toke);  
  14. Uri callback = ServiceProviderContext.CallbackStore.GetCalback(tk);  
  15. string oauth_verifier = ServiceProviderContext.VerificationProvider.Generate(tk);  
  16. Response.Redirect(callback.ToString() + "?oauth_verifier=" + oauth_verifier);  
  17. }  
  18.   
  19. }  
  20. }   
 

六、接下來就是access_token功能,新建AccessTokenHandler.cs , 這個是OAuth.Net.ServiceProvider.AccessTokenHandler子類,並且是httpHandlers所以需要在Web.config中添加httpHandlers配置,這個用來接收客戶端程序的請求,返回給客戶端程序Access Token和Access Secret用,具體代碼如下:

  1. public sealed class AccessTokenHandler : OAuth.Net.ServiceProvider.AccessTokenHandler  
  2.     {  
  3.         protected override void IssueAccessToken(HttpContext httpContext, OAuthRequestContext requestContext)  
  4.         {  
  5.             //產生access token   
  6.             IAccessToken accessToken = this.GenerateAccessToken(httpContext, requestContext);  
  7.   
  8.             accessToken.Status = TokenStatus.Authorized;  
  9.   
  10.             // 把accessToken和accessSecret輸出到客戶端,   
  11.             requestContext.ResponseParameters[Constants.TokenParameter] = accessToken.Token;  
  12.             requestContext.ResponseParameters[Constants.TokenSecretParameter] = accessToken.Secret;  
  13.         }  
  14.   
  15.         protected override IAccessToken GenerateAccessToken(HttpContext httpContext,  OAuthRequestContext requestContext)  
  16.         {  
  17.             return ServiceProviderContext.TokenGenerator.CreateAccessToken(requestContext.Consumer, requestContext.RequestToken);  
  18.         }  
  19.     }  
  20.   
  21. public class TokenGenerator : ITokenGenerator  
  22.     {  
  23.         internal static readonly IRequestToken FixedRequestToken = new OAuthRequestToken("requestkey",  
  24.             "requestsecret",  
  25.             ConsumerStore.FixedConsumer,  
  26.             TokenStatus.Authorized,  
  27.             null,  
  28.             ServiceProviderContext.DummyIdentity,  
  29.             new string[] { });  
  30.   
  31.         internal static readonly IAccessToken FixedAccessToken = new OAuthAccessToken(  
  32.             "accesskey",  
  33.             "accesssecret",  
  34.             ConsumerStore.FixedConsumer,  
  35.             TokenStatus.Authorized,  
  36.             TokenGenerator.FixedRequestToken);  
  37.   
  38.         public IRequestToken CreateRequestToken(IConsumer consumer, OAuthParameters parameters)  
  39.         {  
  40.             return TokenGenerator.FixedRequestToken;  
  41.         }  
  42.   
  43.         public IAccessToken CreateAccessToken(IConsumer consumer, IRequestToken requestToken)  
  44.         {  
  45.             return TokenGenerator.FixedAccessToken;  
  46.         }  
  47.     }  
  48.   
  49. public class TokenStore : InMemoryTokenStore, ITokenStore  
  50.     {  
  51.         public TokenStore()  
  52.         {  
  53.             this.RequestTokenDictionary.Add(  
  54.                 TokenGenerator.FixedRequestToken.Token,  
  55.                 TokenGenerator.FixedRequestToken);  
  56.   
  57.             this.AccessTokenDictionary.Add(  
  58.                 TokenGenerator.FixedAccessToken.Token,  
  59.                 TokenGenerator.FixedAccessToken);  
  60.         }  
  61.   
  62.         public override bool Add(IRequestToken token)  
  63.         {  
  64.             throw new NotSupportedException("Tokens cannot be added to the token store--it is fixed.");  
  65.         }  
  66.   
  67.         public override bool Add(IAccessToken token)  
  68.         {  
  69.             throw new NotSupportedException("Tokens cannot be added to the token store--it is fixed.");  
  70.         }  
  71.   
  72.         public override bool Update(IRequestToken token)  
  73.         {  
  74.             throw new NotSupportedException("Tokens cannot be updated in the token store--it is fixed.");  
  75.         }  
  76.   
  77.         public override bool Update(IAccessToken token)  
  78.         {  
  79.             throw new NotSupportedException("Tokens cannot be updated in the token store--it is fixed.");  
  80.         }  
  81.   
  82.         public override bool Remove(IRequestToken token)  
  83.         {  
  84.             throw new NotSupportedException("Tokens cannot be removed from the token store--it is fixed.");  
  85.         }  
  86.   
  87.         public override bool Remove(IAccessToken token)  
  88.         {  
  89.             throw new NotSupportedException("Tokens cannot be removed from the token store--it is fixed.");  
  90.         }  
  91.     }   
 

這樣就完成了一個最最簡單小型的服務端OAuth認證,然後用android客戶端進行測試ok通過。     注意點:     一、android模擬器訪問本地服務地址爲10.0.2.2,比如http://localhost:3423/authorize.aspx在模擬器中用http://10.0.2.2:3423/authorize.aspx     二、OAuth.Net類庫的OAuth.Net.Common項目中的interface ICallbackStore 添加了一個Uri GetCalback(IRequestToken token);並且在具體的實現類InMemoryCallbackStore添加了實習代碼:          public Uri GetCalback(IRequestToken token)        {
            lock (this.callbackStore)
            {
                if (this.callbackStore.ContainsKey(token))
                {
                    return this.callbackStore[token];
                }
                else
                {
                    return null;
                }
            }
        }



 三、爲了能用我前面做的給新浪用的android客戶端,對於類庫源代碼AccessTokenHandler的ParseParameters方法做了如下修改,因爲新浪請求api的時候都會加一個source的參數:            protected virtual void ParseParameters(HttpContext httpContext, OAuthRequestContext requestContext)        {
            .......
            parameters.AllowOnly(
                    Constants.ConsumerKeyParameter,
                    Constants.TokenParameter,
                    Constants.SignatureMethodParameter,
                    Constants.SignatureParameter,
                    Constants.TimestampParameter,
                    Constants.NonceParameter,
                    Constants.VerifierParameter,
                    Constants.VersionParameter, // (optional)
                    Constants.RealmParameter, // (optional)
                    "source");

            ......
        }


android開發我的新浪微博客戶端-大圖瀏覽以及保存篇(7) 

6 天前 上傳
下載附件 (129.72 KB)

 

18.png

6 天前 上傳
下載附件 (73.8 KB)

 

      在閱讀微博的功能篇中,如果微博包含了圖片就會在微博正文下面顯示該張圖片,但是這個圖片只是張縮略圖,這樣就需要提供一個能放大縮小查看這張圖片的功能,當點擊正文中的縮略圖的時候顯示一個簡單的圖片瀏覽器功能,提供圖片的放大、縮小、拖拽操作方便用戶查看圖片,同時也提供保存圖片到手機的功能。本功能的UI比較簡單就不單獨分篇講了,具體的實現效果如上圖。

      新建ImageActivity.java作爲圖片瀏覽Activity,在res/layout下新建image.xml的Layout作爲圖片瀏覽的佈局文件,image.xml佈局代碼很簡單了就不詳細解釋了直接貼代碼:


  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout  
  3.   xmlns:android="http://schemas.android.com/apk/res/android"  
  4.   android:layout_width="wrap_content"  
  5.   android:layout_height="wrap_content"  
  6.   android:orientation="vertical">  
  7.   <LinearLayout  
  8.   android:layout_width="fill_parent"  
  9.   android:layout_height="41px"  
  10.   android:background="@drawable/imagebar_bg">  
  11.     
  12.   <RelativeLayout  
  13.   android:layout_width="fill_parent"  
  14.   android:layout_height="fill_parent"  
  15.   android:layout_weight="2">  
  16.   <Button  
  17.   android:id="@+id/returnBtn"  
  18.   android:layout_width="63px"  
  19.   android:layout_height="29px"  
  20.   android:layout_centerInParent="true"  
  21.   android:text="返回"  
  22.   android:textColor="#ffffff"  
  23.   android:background="@drawable/btn1_bg">  
  24.   </Button>  
  25.   </RelativeLayout>  
  26.     
  27.   <RelativeLayout  
  28.   android:layout_width="fill_parent"  
  29.   android:layout_height="fill_parent"  
  30.   android:layout_weight="1">  
  31.   <TextView  
  32.   android:layout_width="wrap_content"  
  33.   android:layout_height="wrap_content"  
  34.   android:layout_centerInParent="true"  
  35.   android:text="瀏覽圖片"  
  36.   android:textColor="#ffffff">  
  37.   </TextView>  
  38.   </RelativeLayout>  
  39.     
  40.   <RelativeLayout  
  41.   android:layout_width="fill_parent"  
  42.   android:layout_height="fill_parent"  
  43.   android:layout_weight="2">  
  44.   <Button  
  45.   android:id="@+id/downBtn"  
  46.   android:layout_width="60px"  
  47.   android:layout_height="29px"  
  48.   android:layout_centerInParent="true"  
  49.   android:text="下載"  
  50.   android:textColor="#ffffff"  
  51.   android:background="@drawable/btn2_bg">  
  52.   </Button>  
  53.   </RelativeLayout>  
  54.     
  55.   </LinearLayout>  
  56.   <RelativeLayout  
  57.   android:layout_width="fill_parent"  
  58.   android:layout_height="fill_parent">  
  59.   
  60.   <MySinaWeiBo.ui.ImageZoomView  
  61.     xmlns:android="http://schemas.android.com/apk/res/android"   
  62.     android:id="@+id/pic"  
  63.     android:layout_width="fill_parent"   
  64.     android:layout_height="fill_parent">  
  65.   </MySinaWeiBo.ui.ImageZoomView>  
  66.     
  67.   <ZoomControls  
  68.   android:id="@+id/zoomCtrl"  
  69.   android:layout_width="wrap_content"  
  70.   android:layout_height="wrap_content"  
  71.   android:layout_alignParentRight="true"  
  72.   android:layout_alignParentBottom="true">  
  73.   </ZoomControls>  
  74.   </RelativeLayout>  
  75. </LinearLayout>   
 

     上面的代碼中用到了一個自定義控件MySinaWeiBo.ui.ImageZoomView,這個就是整個功能的核心部分,用來實現圖片的放大、縮小、拖拽的一個圖片顯示控件,這個控件非我原創,是參考了Android one finger zoom tutorial 這篇博客寫出來的,所以我在這裏也不貼實現代碼了,有興趣的大家可以直接看看這個文章。      接下要做的就是用這個ImageZoomView來顯示圖片,在閱讀微博內容的頁面中當點擊內容中的縮略圖片的時候會把這個縮略圖對應的原圖的url傳給當前的這個ImageActivity,那麼在ImageActivity的onCreate方法中根據這個url獲取圖片並且設置給ImageZoomView。在onCreate方法中代碼如下:
 

  1. @Override  
  2. public void onCreate(Bundle savedInstanceState) {  
  3. 。。。。。  
  4. Intent i=this.getIntent();  
  5. if(i!=null){  
  6. Bundle b=i.getExtras();  
  7. if(b!=null){  
  8. if(b.containsKey("url")){  
  9. String url = b.getString("url");  
  10. mZoomView=(ImageZoomView)findViewById(R.id.pic);  
  11. Drawable img= AsyncImageLoader.loadImageFromUrl(url);  
  12.   
  13.   
  14. image=drawableToBitmap(img);  
  15. mZoomView.setImage(image);  
  16.   
  17. mZoomState = new ZoomState();  
  18. mZoomView.setZoomState(mZoomState);  
  19. mZoomListener = new SimpleZoomListener();  
  20. mZoomListener.setZoomState(mZoomState);  
  21.   
  22. mZoomView.setOnTouchListener(mZoomListener);  
  23. resetZoomState();  
  24. }  
  25. }  
  26. }  
  27. 。。。。。。  
  28. }   

  1. private void resetZoomState() {  
  2. mZoomState.setPanX(0.5f);  
  3. mZoomState.setPanY(0.5f);  
  4.   
  5. final int mWidth = image.getWidth();  
  6. final int vWidth= mZoomView.getWidth();  
  7. Log.e("iw:",vWidth+"");  
  8. mZoomState.setZoom(1f);  
  9. mZoomState.notifyObservers();  
  10.   
  11. }  
  12.   
  13. public Bitmap drawableToBitmap(Drawable drawable) {  
  14. Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();   
  15. return bitmap;  
  16. }  

  1. ZoomControls zoomCtrl = (ZoomControls) findViewById(R.id.zoomCtrl);  
  2. zoomCtrl.setOnZoomInClickListener(new OnClickListener(){  
  3. @Override  
  4. public void onClick(View view) {  
  5. float z= mZoomState.getZoom()+0.25f;  
  6. mZoomState.setZoom(z);  
  7. mZoomState.notifyObservers();  
  8. }  
  9.   
  10. });  
  11. zoomCtrl.setOnZoomOutClickListener(new OnClickListener(){  
  12.   
  13. @Override  
  14. public void onClick(View v) {  
  15. float z= mZoomState.getZoom()-0.25f;  
  16. mZoomState.setZoom(z);  
  17. mZoomState.notifyObservers();  
  18. }  
  19.   
  20. });   

 

這樣一個簡單的圖片瀏覽器功能就完成了,支持放大縮小並且還能拖拽,基本上達到應用需求。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章