至簡微博Android客戶端APP開發以及源碼

前言

至簡微博客戶端APP根據微博開放品臺API獲取微博內容,UI展示
主要功能點:

  • 好友微博列表
  • 公共微博列表
  • 微博詳情
  • 用戶個人信息
  • 微博個人信息
  • 微博評論列表
  • 每日一圖
  • 粉絲列表
  • 關注列表
  • 關注數、粉絲數、微博數、收藏數等

效果圖





源碼下載

如果需要源碼,請聯繫我郵箱 [email protected]

開發環境

  • kotlin
  • Retrofit
  • Rxjava
  • MVP
  • AndroidX
  • Glide

具體實現

一 微博平臺

官網: https://open.weibo.com/wiki/%E9%A6%96%E9%A1%B5
打開微博平臺官網註冊,因爲是開發APP,所以選擇移動應用

這裏開發AndroidAPP,選擇Android SDK下載
這個SDK主要是微博分享、微博授權等功能的具體實現的工具,微博提供了這一個方便的SDK方便開發者開發。

而對於微博API的具體調用,SDK中並沒有什麼幫助,需自己調用,文中開發的APP使用Retrofit + Rxjava來實現。

創建應用完成後如圖:
在這裏插入圖片描述

應用註冊成功後,會生成對應的appkey和appsecret值。另外需要設置的值有授權回調頁。
授權回調頁默認設置爲:https://api.weibo.com/oauth2/default.html

二 集成SDK

AS中構建Android APP工程,集成微博SDK

api 'com.sina.weibo.sdk:core:2.0.3:openDefaultRelease@aar'

三 授權

	private fun launchScope() {
        if (this.isFinishing) {
            return
        }

        val mAccessToken = AccessTokenKeeper.readAccessToken(this);
        if (mAccessToken.isSessionValid) {
            BlogApplication.mAccessToken = mAccessToken
            launchMain()
            return
        }

        getToken()
    }

    private fun getToken() {
        mSsoHandler = SsoHandler(this)
        mSsoHandler.authorize(object : WbAuthListener {
            override fun onSuccess(token: Oauth2AccessToken?) {
                LogUtil.i(token?.toString())
                val isValid = token?.isSessionValid
                if (isValid == true) {
                    BlogApplication.mAccessToken = token
                    AccessTokenKeeper.writeAccessToken(this@LoginActivity, token)
                    launchMain()
                }
            }

            override fun onFailure(p0: WbConnectErrorMessage?) {
                LogUtil.i("err code:" + p0?.errorCode + ", err msg:" + p0?.errorMessage)
                UiUtil.toast(this@LoginActivity, "授權失敗,請重試")
            }

            override fun cancel() {
                LogUtil.i("on cancel.")
                UiUtil.toast(this@LoginActivity, "授權已取消")
            }
        })
    }

    private fun launchMain() {
        val intent = Intent(this, MainActivity::class.java)
        startActivity(intent)
        finish()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        mSsoHandler.authorizeCallBack(requestCode, resultCode, data)
    }

微博授權過程,以上代碼即可實現。

以上授權成功後,AccessTokenKeeper類 會獲取到四個值:

	private static final String KEY_UID = "uid";
    private static final String KEY_ACCESS_TOKEN = "access_token";
    private static final String KEY_EXPIRES_IN = "expires_in";
    private static final String KEY_REFRESH_TOKEN = "refresh_token";

uid、token、expires_in、refresh_token
這四個值其中token和uid尤爲重要,其他不重要。授權過程中需要用戶在登錄頁輸入用戶名和密碼,但是APP是獲取不到這些信息的,這些信息的頁面不受APP控制,由微博登錄頁顯示獲取,然後,微博根據用戶名和密碼返回給APP以上四個值,這樣一來APP與用戶密碼信息隔離,這就是auth2.0認證的大致過程了

四 調用微博API

interface WeiboRequest {

    @GET("https://api.weibo.com/2/statuses/home_timeline.json")
    fun getStatusesHomeTimeLineMore(@Query("since_id") since_id: String, @Query("count") count: Int): Observable<StatusesResponse>

    @GET("https://api.weibo.com/2/statuses/home_timeline.json")
    fun getStatusesHomeTimeLineRefresh(@Query("max_id") max_id: String, @Query("count") count: Int): Observable<StatusesResponse>

    @GET("https://api.weibo.com/2/short_url/share/counts.json")
    fun getShortUrlExpand(@Query("url_short") url_short: String): Observable<ShortUrlResponse>

    // 必須是自己發出的微博
    @GET("https://api.weibo.com/2/statuses/show.json")
    fun getDetailInfo(@Query("id") id: String): Observable<StatusesDetailResponse>

    @GET("https://api.weibo.com/2/comments/show.json")
    fun getComments(@Query("id") id: String, @Query("since_id") since_id: String, @Query("max_id") max_id: String): Observable<CommentsResponse>

    @GET("https://api.weibo.com/2/users/show.json")
    fun getUserInfo(@Query("uid") uid: String, @Query("screen_name") screenName: String): Observable<UserInfoResponse>

    @GET("https://api.weibo.com/2/friendships/friends.json")
    fun getFollowList(@Query("uid") uid: String, @Query("cursor") cursor: Long): Observable<FollowListResponse>

    @GET("https://api.weibo.com/2/friendships/followers.json")
    fun getFollowerList(@Query("uid") uid: String, @Query("cursor") cursor: Long): Observable<FollowListResponse>

    @GET("https://api.weibo.com/2/statuses/public_timeline.json")
    fun getPublicTimeLine(@Query("page") page: Long): Observable<StatusesResponse>
}

以上是APP中用到的微博的一部分API,網絡請求使用Retrofit+Rxjava來實現的

請求關注好友的微博列表,代碼如下:

override fun getStatusesHomeLineLoad() {
        RetrofitClient.instance.create(WeiboRequest::class.java)
            .getStatusesHomeTimeLineMore(sinceId, COUNT)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(object : AbstractObserver<StatusesResponse>() {
                override fun onSuc(t: StatusesResponse) {
                    LogUtil.i("statuses response :${t}")
                    iView?.setStatuses(t.statuses)
                }

                override fun onFail(e: Throwable) {

                }
            })
    }

以上代碼獲取微博列表,返回json信息,微博對象如下:

class Statuses: Serializable {
    var visible: Visible? = null
    var created_at: String? = null
    var id: Long = 0
    var idstr: String? = null
    var mid: String? = null
    var can_edit: Boolean = false
    var version: Int = 0
    var show_additional_indication: Int = 0
    var text: String? = null
    var textLength: Int = 0
    var source_allowclick: Int = 0
    var source_type: Int = 0
    var source: String? = null
    var favorited: Boolean = false
    var truncated: Boolean = false
    var in_reply_to_status_id: String? = null
    var in_reply_to_user_id: String? = null
    var in_reply_to_screen_name: String? = null
    var pic_urls: List<PicUrls>? = null
    var thumbnail_pic: String? = null
    var bmiddle_pic: String? = null
    var original_pic: String? = null
    var geo: Geo? = null
    var is_paid: Boolean = false
    var mblog_vip_type: Int = 0
    var user: User? = null
    var retweeted_status: Statuses? = null
    var annotations: List<Annotations>? = null
    var reposts_count: Int = 0
    var comments_count: Int = 0
    var attitudes_count: Int = 0
    var pending_approval_count: Int = 0
    var isLongText: Boolean = false
    var reward_exhibition_type: Int = 0
    var hide_flag: Int = 0
    var mlevel: Int = 0
    var biz_feature: Long = 0
    var expire_time: Long = 0
    var page_type: Int = 0
    var hasActionTypeCard: Int = 0
    var darwin_tags: List<String>? = null
    var hot_weibo_tags: List<String>? = null
    var text_tag_tips: List<String>? = null
    var mblogtype: Int = 0
    var userType: Int = 0
    var extend_info: ExtendInfo? = null
    var more_info_type: Int = 0
    var cardid: String? = null
    var number_display_strategy: NumberDisplayStrategy? = null
    var positive_recom_flag: Int = 0
    var content_auth: Int = 0
    var gif_ids: String? = null
    var is_show_bulletin: Int = 0
    var comment_manage_info: CommentManageInfo? = null
    var pic_num: Int = 0
}

五 UI展示

獲取微博列表後,UI展示:

具體UI描述:

  • 頭像
  • 名字
  • 微博發佈時間
  • 微博內容
  • 微博圖片
  • 轉發數
  • 評論數
  • 點贊數
  • 轉發微博內容等

個人信息展示:

  • 頭像
  • 名字
  • 用戶描述
  • 省市
  • 註冊時間
  • 收藏數、微博數、關注數、粉絲數
  • 認證原因
  • 博客地址
  • 信用分數

聲明

代碼僅作爲學習之用,嚴禁商業之用。
如有任何問題,不負責任!!


歡迎關注公衆號:技術印象


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