最近項目忙完了,開始有一定的時間優化自己的架構,我一直寫代碼都有一種感覺,每次寫完一個項目,然后開始優化,等優化完,再看看自己寫的代碼,就發現我封裝的框架真的有點辣雞,然后又開始寫個基礎的lib進行架構的優化
簡介
關于Android程序的構架,主要有MVC,MVP和MVVM。MVC相對于較為落后,耦合度太高、職責不明確;MVVM其實就是在mvp的基礎上采用DataBind,普及性不如MVP,況且Google官方提供了Sample代碼來展示MVP模式的用法,所以目前大部分項目采用的還是MVP,當然根據項目的情況以及項目的大小來采用合適的結構才是合理的。
Kotlin是由JetBrains創建的基于JVM的編程語言,IntelliJ正是JetBrains的杰作,而Android Studio是基于IntelliJ修改而來的。Kotlin是一門包含很多函數式編程思想的面向對象編程語言。Kotlin生來就是為了彌補Java缺失的現代語言的特性,并極大的簡化了代碼,使得開發者可以編寫盡量少的樣板代碼。所以目前來說kotlin的Android開發者中的普及率越來越大,這應該是一個很大的趨勢。所以學習和使用kotlin是一個Android開發者必備的技能
Retrofit: Retrofit是Square 公司開發的一款正對Android 網絡請求的框架。底層基于OkHttp 實現。
RxJava:RxJava 在 GitHub 主頁上的自我介紹是 "a library for composing asynchronous and event-based programs using observable sequences for the Java VM"(一個在 Java VM 上使用可觀測的序列來組成異步的、基于事件的程序的庫)。這就是 RxJava ,概括得非常精準。總之就是讓異步操作變得非常簡單。
各自的職責:Retrofit 負責請求的數據和請求的結果,使用接口的方式呈現,OkHttp 負責請求的過程,RxJava 負責異步,各種線程之間的切換。
RxJava + Retrofit 已成為當前Android 網絡請求最流行的方式。
MVP具體實現
首先既然采用了MVP,肯定必不可少具M層,V層,P層的基礎接口,封裝一個公共的操作,看一下具體實現
我把頂級的接口分成了兩層,這樣有利于在寫泛型的時候沒那么麻煩
先看下目錄結構
- 頂級接口
第一層
interface ITopView : LifecycleOwner {
fun getCtx(): Context?
fun inited()
fun finish(resultCode: Int = Activity.RESULT_CANCELED)
fun showLoading(@NotNull msg: String)
fun showLoading(@StringRes srtResId: Int)
fun dismissLoading()
fun showToast(@StringRes srtResId: Int)
fun showToast(@NotNull message: String)
}
interface ITopPresenter : LifecycleObserver {
fun attachView(view: ITopView)
@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
fun detachView()
}
interface ITopModel {
fun onDetach()
}
第二層
interface IView<P : ITopPresenter> : ITopView {
var mPresenter: P
override fun inited() {
mPresenter.attachView(this)
}
}
interface IPresenter<V : ITopView, M : IModel> : ITopPresenter {
var mView: V?
var mModel: M?
fun getContext() = mView?.getCtx()
@Suppress("UNCHECKED_CAST")
override fun attachView(view: ITopView) {
mView = view as V
mView?.lifecycle?.addObserver(this)
}
override fun detachView() {
mModel?.onDetach()
mModel = null
mView = null
}
//判斷是否初始化View
private val isViewAttached: Boolean
get() = mView != null
fun checkViewAttached() {
if (!isViewAttached) throw MvpViewNotAttachedException()
}
private class MvpViewNotAttachedException internal constructor() : RuntimeException("Please call IPresenter.attachView(IBaseView) before" + " requesting data to the IPresenter")
}
interface IModel : ITopModel {
val mDisposablePool: CompositeDisposable
fun addDisposable(disposable: Disposable) {
mDisposablePool.add(disposable)
}
override fun onDetach() {
if (!mDisposablePool.isDisposed) {
mDisposablePool.clear()
}
}
}
還有額外的一個列表的V層,主要是對列表界面數據統一處理
interface IListView<P : ITopPresenter> :IView<P>{
val mRecyclerView: RecyclerView?
val mStateView: IStateView?
val mRefreshLayout:SmartRefreshLayout
fun loadMoreFail(isRefresh: Boolean)
}
然后M的基類
open class BaseModelKt {
val mDisposablePool: CompositeDisposable by lazy { CompositeDisposable() }
}
然后P的基類
open class BasePresenterKt<V : ITopView> {
var mView: V? = null
}
-
Activity和Fragment的封裝
首先的MVPActivity的實現
abstract class BaseMvpActivity<V : ITopView, P : ITopPresenter> : BaseActivity(), IView<P> {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
inited()
}
override fun getCtx() = this
override fun showLoading(msg: String) {
progressDialog?.showProgressDialogWithText(msg)
}
override fun finish(resultCode: Int) {
finish()
}
override fun showLoading(srtResId: Int) {
progressDialog?.showProgressDialogWithText(resources.getString(srtResId))
}
override fun dismissLoading() {
progressDialog?.dismissProgressDialog()
}
override fun showToast(message: String) {
showToastBottom(message)
}
override fun showToast(srtResId: Int) {
showToast(resources.getString(srtResId))
}
}
然后MVPFragment的實現
abstract class BaseMvpFragment<V : ITopView, P : ITopPresenter> : BaseFragment(), IView<P> {
override fun getCtx() = context
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
inited()
}
override fun finish(resultCode: Int) {
}
override fun showToast(message: String) {
showToastBottom(message)
}
override fun showToast(srtResId: Int) {
showToast(resources.getString(srtResId))
}
override fun showLoading(msg: String) {
showProgressDialog(msg)
}
override fun showLoading(srtResId: Int) {
showProgressDialog(resources.getString(srtResId))
}
override fun dismissLoading() {
dismissProgressDialog()
}
}
然后封裝一個帶toolBar的MVPTitleActivity,它是MVPActivity的子類
abstract class BaseMvpTitleActivity<V : ITopView, P : ITopPresenter> : BaseMvpActivity<V, P>() {
private var rightMenuTexts: String? = null
private var rightMenuIcons: Int? = null
private var titleTv: TextView? = null
@LayoutRes
protected abstract fun childView(): Int
override fun getContentView() = R.layout.activtiy_base_title
override fun initView() {
val container = this.findViewById<FrameLayout>(R.id.base_container)
container.addView(layoutInflater.inflate(childView(), null))
val toolbar = this.findViewById<Toolbar>(R.id.base_toolbar)
titleTv = this.findViewById(R.id.base_title_tv)
toolbar.title = ""
setSupportActionBar(toolbar)
if (hasBackIcon()) {
toolbar.setNavigationIcon(R.drawable.return_icon)
toolbar.setNavigationOnClickListener { finish() }
}
}
open fun hasBackIcon() = true
override fun onCreateOptionsMenu(menu: Menu): Boolean {
rightMenuIcons?.let {
val item = menu.add(0, 0, 0, "")
item.icon = ContextCompat.getDrawable(this, it)
item.setShowAsAction(Menu.FLAG_ALWAYS_PERFORM_CLOSE)
}
rightMenuTexts?.let {
val item = menu.add(0, 0, 0, "")
item.title = it
item.setShowAsAction(Menu.FLAG_ALWAYS_PERFORM_CLOSE)
}
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
onRightMenuClick(item.itemId)
return false
}
/**
* 設置toolbar右邊的文字
*/
fun setRightMenuTexts(rightMenuText: String) {
this.rightMenuTexts = rightMenuText
}
/**
* 設置toolbar右邊的icon
*/
fun setRightMenuIcons(@DrawableRes rightIconResId: Int) {
this.rightMenuIcons = rightIconResId
}
/**
* 當toolbar右邊的icon,被點擊,數據0,1,2,3
*/
open fun onRightMenuClick(itemId: Int) {
}
/**
* 設置中間的title
*/
protected fun setActivityTitle(@StringRes strResId: Int) {
titleTv?.setText(strResId)
}
protected fun setActivityTitle(text: String) {
titleTv?.text = text
}
/**
* 設置中間title的顏色
*/
fun setActivityTitleColor(@ColorRes colorId: Int) {
titleTv?.setTextColor(resources.getColor(colorId))
}
}
這樣基本的封裝基本就結束了
但是還可以對列表進行封裝,封裝了視圖狀態,下拉刷新
來看看MVPListActivity,MVPListFragment,MvpTitleListAcitivty的封裝
abstract class BaseMvpListActivity<V : ITopView, P : ITopPresenter> : BaseMvpActivity<V, P>(), IListView<P> {
override fun getContentView() = R.layout.layout_list
override val mStateView: IStateView by lazy { list_sv }
override val mRecyclerView: RecyclerView by lazy { list_rv }
override val mRefreshLayout: SmartRefreshLayout by lazy { refreshLayout }
override fun initView() {
//設置列表背景色
list_rv.setBackgroundColor(ContextCompat.getColor(this, setRecyclerViewBgColor))
//重試
list_sv.onRetry = { onRetry() }
//刷新
refreshLayout.setOnRefreshListener { onRefresh() }
//設置下拉刷新是否可用
refreshLayout.isEnabled = setRefreshEnable
}
abstract fun onRefresh()
abstract fun onRetry()
open val setRecyclerViewBgColor = R.color.white
open val setRefreshEnable = true
}
abstract class BaseMvpListFragment<V : ITopView, P : ITopPresenter> : BaseMvpFragment<V, P>(), IListView<P> {
override fun getContentView() = R.layout.layout_list
override val mStateView: IStateView by lazy { list_sv }
override val mRecyclerView: RecyclerView by lazy { list_rv }
override val mRefreshLayout: SmartRefreshLayout by lazy { refreshLayout }
override fun initData() {
//設置背景色
context?.let { list_rv.setBackgroundColor(ContextCompat.getColor(it, setRecyclerViewBgColor)) }
//重試
list_sv.onRetry = { onRetry() }
//刷新
refreshLayout.setOnRefreshListener { onRefresh() }
//設置下拉刷新是否可用
refreshLayout.isEnabled = setRefreshEnable
}
abstract fun onRefresh()
abstract fun onRetry()
open val setRecyclerViewBgColor = R.color.white
open val setRefreshEnable = true
}
abstract class BaseMvpTitleListActivity<V : ITopView, P : ITopPresenter> : BaseMvpTitleActivity<V, P>(), IListView<P> {
override fun childView()= R.layout.layout_list
override val mStateView: IStateView by lazy { list_sv }
override val mRecyclerView: RecyclerView by lazy { list_rv }
override val mRefreshLayout: SmartRefreshLayout by lazy { refreshLayout }
override fun initView() {
super.initView()
//設置背景色
list_rv.setBackgroundColor(ContextCompat.getColor(this, setRecyclerViewBgColor))
//重試
list_sv.onRetry = { onRetry() }
//刷新
refreshLayout.setOnRefreshListener { onRefresh() }
//設置下拉刷新是否可用
refreshLayout.isEnabled = setRefreshEnable
}
abstract fun onRefresh()
abstract fun onRetry()
open val setRecyclerViewBgColor = R.color.white
open val setRefreshEnable = true
}
這樣MVP的大致架構基本已經封裝好了
網絡框架的具體實現
- retrofit的封裝
這個apiService我才用泛型回調,這樣可以根據不同的模塊創建不同的retrofit工廠類,這個也有利用模塊化開發
abstract class RetrofitFactory<T> {
private val time_out: Long = 15//超時時間
var apiService: T
init {
val httpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
val builder = chain.request().newBuilder()
// 添加請求頭header
if (getToken().isNotEmpty()) {
builder.header("userToken", getToken())
}
val build = builder.build()
chain.proceed(build)
}
.addInterceptor(HttpLoggingInterceptor(HttpLoggingInterceptor.Logger { message ->
if (message.contains("{")||message.contains("=")||message.contains("http")
||message.contains("userToken")){
Logger.e("${message}")
}
}).setLevel(HttpLoggingInterceptor.Level.BODY))//設置打印得日志內容
.connectTimeout(time_out, TimeUnit.SECONDS)
.readTimeout(time_out, TimeUnit.SECONDS)
.build()
apiService = Retrofit.Builder()
.baseUrl(URLConstant.BASE_URL)
.addConverterFactory(GsonConverterFactory.create(buildGson())) // 添加Gson轉換器
.addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // 添加Retrofit到RxJava的轉換器
.client(httpClient)
.build()
.create(getApiService())
}
abstract fun getApiService(): Class<T>
abstract fun getToken(): String
private fun buildGson(): Gson {
return GsonBuilder()
.setDateFormat("yyyy-MM-dd HH:mm:ss")
.create()
}
fun getService(): T {
return apiService
}
}
- Rxjava+Retrofit的封裝
這個部分是網絡請求的部分,我是封裝在kotlin的拓展方法里面,這樣就可以使用lambda表達式進行網絡請求,代碼量賊少,用起來賊舒服,一行代碼一個請求
具體使用例子
PersonRetrofit.apiService.getIdentityCode(phone).mySubscribe(view, "正在獲取驗證碼...") {
view.getCodeSuccess()
}
是不是賊簡單,賊方便,這個得感謝我的同學大強哥,這招都是他教我的,把lambda用到極致;
再來看看kotlin的拓展內部實現;
fun <T : BaseBean, P : ITopPresenter> Observable<T>.mSubscribe(
iBaseView: IView<P>? = null
, iModel: IModel? = null
, msg: String = ""
, onSuccess: (T) -> Unit) {
this.compose(SchedulerUtils.ioToMain())
.subscribe(object : Observer<T> {
override fun onComplete() {
iBaseView?.dismissLoading()
}
override fun onSubscribe(d: Disposable) {
iModel?.addDisposable(d)
iBaseView?.showLoading(if (msg.isEmpty()) "請求中..." else msg)
if (!NetworkUtils.isConnected()) {
showToastBottom("連接失敗,請檢查網絡狀況!")
onComplete()
}
}
override fun onNext(t: T) {
if (t.code == CodeStatus.SUCCESS) {
onSuccess.invoke(t)
} else if (t.code == CodeStatus.LOGIN_OUT) {//重新登錄
// val currentActivity = ActivityUtils.currentActivity()
// UserManager.getInstance().clear()
// EMClient.getInstance().logout(true)
// showToastBottom("登錄過期,請重新登錄")
// val intent = Intent(currentActivity, LoginActivity::class.java)
// intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// currentActivity?.startActivity(intent)
} else {
if (!t.msg.isNullOrEmpty()) {
t.msg?.let { showToastBottom(it) }
} else {
showToastBottom("請求失敗")
}
}
}
override fun onError(e: Throwable) {
iBaseView?.dismissLoading()
if (e is SocketTimeoutException || e is ConnectException) {
showToastBottom("連接失敗,請檢查網絡狀況!")
} else if (e is JsonParseException) {
showToastBottom("數據解析失敗")
} else {
showToastBottom("請求失敗")
}
}
})
}
fun <T : BaseBean, P : ITopPresenter> Observable<T>.listSubcribe(
iBaseView: IListView<P>? = null
, iModel: IModel? = null
, isRefresh: Boolean
, isLoadMore: Boolean
, onSuccess: (T) -> Unit) {
this.compose(SchedulerUtils.ioToMain())
.subscribe(object : Observer<T> {
override fun onComplete() {}
override fun onSubscribe(d: Disposable) {
iModel?.addDisposable(d)
if (!isRefresh && !isLoadMore) {
iBaseView?.mStateView?.showLoading()
}
}
override fun onNext(t: T) {
if (t.code == CodeStatus.SUCCESS) {
iBaseView?.mStateView?.showSuccess()
onSuccess.invoke(t)
} else if (t.code == CodeStatus.LOGIN_OUT) {//重新登錄
// UserManager.getInstance().clear()
// showToastBottom("登錄過期,請重新登錄")
// EMClient.getInstance().logout(true)
// val intent = Intent(currentActivity, LoginActivity::class.java)
// intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
// currentActivity.startActivity(intent)
} else {
iBaseView?.mStateView?.showError()
}
}
override fun onError(e: Throwable) {
if (!isLoadMore) {
iBaseView?.mStateView?.showError()
} else {
iBaseView?.loadMoreFail(isRefresh)
}
}
})
}
配合插件使用,快速開發必備
這里我推薦一個我同學的插件,結合這種lib使用賊方便
插件的名字叫MvpAutoCodePlus,github地址 插件地址,,,這個low比名字還是我幫他取的。
具體使用
這樣就生成了,真的很方便
最后我寫了一個demo放在github上面 項目地址
原文地址
歡迎大家掃描關注作者公眾號,長期推送Android技術干貨,感謝大家支持: