編輯:關於 Android 開發
這幾年 Android 的網路層幾乎被這三個東西承包了:Retrofit 負責把 HTTP 介面描述成 Java 介面,RxJava 負責把非同步流程串成一條鏈,MVP 負責把 UI 與商業邏輯切乾淨。下面把整個組裝過程走一遍。
版本請依實際專案需求調整,這裡記錄的是當時的組合:

這裡有兩個容易被忽略的細節。第一是 Gson 的 serializeNulls():預設 Gson 會把 null 欄位整個省略,呼叫這個方法之後 null 也會被輸出,後端如果依賴欄位存在,這個設定能省下不少溝通成本。
第二是攔截器的分工。addInterceptor 屬於應用層攔截器,適合放公共參數、Header、應用日誌;addNetworkInterceptor 屬於網路層攔截器,比較接近真實的 socket 連線,適合做重試、重寫請求。兩者都註冊同一個 HttpLoggingInterceptor 就會看到重複的日誌,這點要留意。

Retrofit 最迷人的地方就在這裡:你不需要寫任何實作,只要宣告一條介面方法,參數綁上 @Field,回傳型別寫成 Observable<T>,剩下的它全包了。

順帶一提,POST 表單送出時 @FormUrlEncoded 不能漏,漏了會直接收到後端的 415 或參數全空。
每個 API 集合包一個 Service 類別,用 double-check 或 synchronized 保住單例,避免重複建立 Retrofit 物件。

MVP 裡的 P 是整篇文章的核心。它把「參數檢查 → 切到 IO 執行緒 → 轉換資料 → 切回主執行緒 → 更新 View」這一整串流程寫成一條可讀性極高的鏈:
subscribeOn(Schedulers.io()):決定「誰去執行」,也就是請求在哪條執行緒跑。observeOn(AndroidSchedulers.mainThread()):決定「誰來接收」,後續的 onNext 會回到主執行緒,才能安全更新 UI。map():把外層的 UsersEntity 剝成內層的 UserEntity,View 層不必知道後端的包裝結構。這正是 RxJava 的價值所在:過去要處理巢狀回呼(callback hell),現在只是一條線性表達式。
import android.util.Log; import rx.Observer; import rx.Subscription; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; public class LoginPresenter implements ILoginPresenter { public Subscription login(final String username,final String pwd, final CallBack callBack) { if (username == null || pwd == null || username.equals("") || pwd.equals("")){ callBack.Error(STATUS.NULL_ERROR); return null; } //觀察者Subscription Subscription s = LoginSingleService.getLoginSingleton()//事件源,被觀察者Observable .login("21341234",username,pwd) .subscribeOn(Schedulers.io())//指定觀察者運行的線程 .map(entity -> entity.getData()) .observeOn(AndroidSchedulers.mainThread())//指定訂閱者運行的線程 .subscribe(new Observer<UserEntity>() {//訂閱subscriber @Override public void onCompleted() { Log.e("onNext","onCompleted"); callBack.End(); } @Override public void onError(Throwable e) { Log.e("onNext","onError "+e.getMessage()); callBack.Error(STATUS.ERROR); } @Override public void onNext(UserEntity entity) { STATUS status; if (entity != null) { status = STATUS.SUCCESS; Log.e("onNext","hello "+entity.getName()); App.getInstance().setUserEntity(entity); App.getInstance().setPerson(entity,pwd); } else status = STATUS.ERROR; callBack.Success(status); } }); return s; } }
注意 login 的回傳值是 Subscription,這個設計是刻意留的伏筆,下一節就會用到。
RxJava 最容易釀成災難的一點是記憶體洩漏。請求還在跑、畫面已經被關掉,回呼回來時持有著一個死掉的 Activity。解法是用 CompositeSubscription 把所有訂閱集中管理,在 onDestroy 時一次全部 unsubscribe。
import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import rx.Subscription; import rx.subscriptions.CompositeSubscription; /** * Created by LiuZhen on 2016/5/11. */ public abstract class BaseActivity extends AppCompatActivity { private final static String TAG = "BaseActivity"; private CompositeSubscription mCompositeSubscription; protected Context context; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(getLayoutId()); this.context = BaseActivity.this; } public CompositeSubscription getCompositeSubscription() { if (this.mCompositeSubscription == null) { this.mCompositeSubscription = new CompositeSubscription(); } return this.mCompositeSubscription; } /**使CompositeSubscription持有訂閱**/ public void addSubscription(Subscription s) { if (this.mCompositeSubscription == null) { this.mCompositeSubscription = new CompositeSubscription(); } this.mCompositeSubscription.add(s); } @Override protected void onDestroy() { super.onDestroy(); if (this.mCompositeSubscription != null) { this.mCompositeSubscription.unsubscribe();//取消所有的訂閱 } } protected abstract int getLayoutId(); }
把 getLayoutId() 宣告成抽象方法是很漂亮的一手:子類別只要回答「我用哪個布局」,setContentView 就不用每頁重寫一次。
import android.os.Bundle; import android.widget.TextView; import org.greenrobot.eventbus.EventBus; import org.greenrobot.eventbus.Subscribe; import org.greenrobot.eventbus.ThreadMode; public class MainActivity extends BaseActivity { private TextView username; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); username = (TextView) findViewById(R.id.username); username.setText(App.getInstance().getPerson().getName()+" hello"); } @Override protected int getLayoutId() { return R.layout.activity_main; } @Subscribe(threadMode = ThreadMode.MAIN) public void onEvent() { Toasts.showShort("刷新UI",context); } @Override protected void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
這裡用 EventBus 打通跨元件的通知,登入成功後只要有地方 post 一個事件,訂閱端就會收到。register 與 unregister 必須成對出現,否則 Activity 被回收後仍留在 EventBus 的訂閱清單裡,一樣是洩漏。
整套架構拆下來其實就是三句話:Retrofit 把網路變成介面呼叫,RxJava 把非同步變成一條鏈,MVP 把 UI 與邏輯切成兩層。三者缺一,程式碼就會開始互相污染。真正落地時還要補上統一的錯誤處理(例如用 onErrorResumeNext 把例外轉成統一結果物件)與 loading 狀態管理,那又是另一篇文章的篇幅了。
自訂 View 實作圓形 Progress:attrs 屬性、onDraw 與 onMeasure
本文從零打造一個自訂控制項:外圈一個圓框,內部一個扇形隨時間增長,最終形成一個圓環進度條。這個練習幾乎涵蓋了自訂 View 的所有關鍵環節。 效果預覽 設計思路 整體分
Android應用開發教程之七:應用程式的除錯與調試技巧
除錯是每一個程式設計師必備的基本功。本文將以 Eclipse 為例,系統性地講解 Android 應用的調試流程,從設定斷點、單步執行、檢視變量,到真機調試與 Log 日
Android HTTP 緩存機制與 HttpResponseCache 實作
Android HTTP 緩存機制與 HttpResponseCache 實作HTTP 緩存能減少重複下載、降低網路延遲,並減輕伺服器負擔。在 Android 中,若能正
別再被騙了:getExternalStorageDirectory並非你想像中的SD卡
別再被騙了:getExternalStorageDirectory並非你想像中的SD卡 前情提要:我的測試機是華為榮耀6,裝過一張16G的內存卡。 由於面試需要,我的演示