版權聲明:本文爲HaiyuKing原創文章,轉載請註明出處!html
這一篇主要講一下將OkHttpUtils運用到mvp模式中。java
數據請求地址:http://www.wanandroid.com/tools/mockapi/418/versionandroid
一、集成OKHttpUtils開源庫參考《okhttputils【 Android 一個改善的okHttp封裝庫】使用(一)》;git
二、使用mvp模式封裝網絡請求。github
注意事項:json
一、 導入類文件後須要change包名以及從新import R文件路徑api
二、 Values目錄下的文件(strings.xml、dimens.xml、colors.xml等),若是項目中存在,則複製裏面的內容,不要整個覆蓋服務器
參考《okhttputils【 Android 一個改善的okHttp封裝庫】使用(一)》網絡
LoginLogic.java【調用的方法須要傳入tag值,且注意方法命名規則:xxxApi】app
package com.why.project.okhttputilsmvpdemo.logic; import com.why.project.okhttputilsmvpdemo.MyApplication; import com.zhy.http.okhttp.OkHttpUtils; import com.zhy.http.okhttp.callback.StringCallback; /** * Created by HaiyuKing * Used */ public class LoginLogic extends BaseLogic { private static LoginLogic _Instance = null; public static LoginLogic Instance() { if (_Instance == null) _Instance = new LoginLogic(); return _Instance; } private LoginLogic() { this.context = MyApplication.getAppContext();//防止了內存泄漏 } /** * 發現新版本接口 */ public String updateVersionApi(String tag, StringCallback callback) throws Exception { String result = ""; OkHttpUtils .get() .url(getSpcyUrl(ServerApi.UPDATE_VERSION_URL)) .id(100) .tag(tag) .build() .execute(callback); return result; } }
UpdateVersionBean.java【通常項目中都是須要用到的】
package com.why.project.okhttputilsmvpdemo.bean; /** * Created by HaiyuKing * Used 更新APP的實體類 */ public class UpdateVersionBean { private String versionName;//服務器上的版本號,好比3.0 private String forceUpdate;//是否強制更新 private String title;//標題,若是爲空,則默認顯示發現新版本 private String content;//更新內容,若是爲空,則不顯示 private String downloadurl;//下載地址 private String fileSize;//文件大小 public String getVersionName() { return versionName; } public void setVersionName(String versionName) { this.versionName = versionName; } public String getForceUpdate() { return forceUpdate; } public void setForceUpdate(String forceUpdate) { this.forceUpdate = forceUpdate; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getDownloadurl() { return downloadurl; } public void setDownloadurl(String downloadurl) { this.downloadurl = downloadurl; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } }
UpdateVersionModel.java【命名規則:bean類的前綴+Model】【用於封裝網絡請求,而後經過callback回調】
package com.why.project.okhttputilsmvpdemo.model; import android.content.Context; import com.why.project.okhttputilsmvpdemo.MyApplication; import com.why.project.okhttputilsmvpdemo.R; import com.why.project.okhttputilsmvpdemo.bean.UpdateVersionBean; import com.why.project.okhttputilsmvpdemo.logic.LoginLogic; import com.zhy.http.okhttp.callback.StringCallback; import org.json.JSONException; import org.json.JSONObject; import okhttp3.Call; import okhttp3.Request; /** * Created by HaiyuKing * Used 發現新版本的請求類 */ public class UpdateVersionModel { /**獲取新版本的信息*/ public void updateVersionInfo(String tag, final LoadingDataCallBack<UpdateVersionBean> callBack) { final Context mContext = MyApplication.getAppContext(); //執行請求任務 try { LoginLogic.Instance().updateVersionApi(tag,new StringCallback() { @Override public void onBefore(Request request, int id) { callBack.onBefore("");//回調 } @Override public void onAfter(int id) { callBack.onAfter();//回調 } @Override public void onError(Call call, Exception e, int id) { callBack.onError("");//回調 } @Override public void onResponse(String response, int id) { switch (id) { case 100://http try { if (response != null && !"".equals(response)){ JSONObject versionInfoObj = new JSONObject(response); UpdateVersionBean updateVersionBean = new UpdateVersionBean(); updateVersionBean.setVersionName(versionInfoObj.getString("versionName")); updateVersionBean.setForceUpdate(versionInfoObj.getString("forceUpdate")); updateVersionBean.setTitle(versionInfoObj.getString("title")); updateVersionBean.setContent(versionInfoObj.getString("content")); updateVersionBean.setDownloadurl(versionInfoObj.getString("downloadurl")); updateVersionBean.setFileSize(versionInfoObj.getString("fileSize")); callBack.onSuccess(updateVersionBean); }else { //提示失敗 callBack.onFailure("");//回調 } }catch (JSONException e) { callBack.onError(mContext.getResources().getString(R.string.login_json_exception));//回調 }catch (Exception e) { callBack.onError(mContext.getResources().getString(R.string.login_json_exception));//回調 } break; case 101://https break; } } @Override public void inProgress(float progress, long total, int id) { //callBack.onProgress(progress,total,id);//回調 } }); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
LoadingDataCallBack.java【網路請求的回調】
package com.why.project.okhttputilsmvpdemo.model; /** * Used 常規接口請求的回調【請求發現新版本接口】 */ public interface LoadingDataCallBack<T> { /** * 數據請求前的操做 * @ TODO 通常用於顯示加載對話框 */ void onBefore(String msg); /** * 當請求數據結束時,不管請求結果是成功,失敗或是拋出異常都會執行此方法給用戶作處理 * @ TODO 請求結束,通常隱藏加載提示對話框,或者執行下一步操做 */ void onAfter(); /** * 數據請求成功 * @param response 請求到的數據 * @ TODO 請求成功,通常執行下一步的操做(繼續請求接口,或者顯示) */ void onSuccess(T response); /** * 數據請求成功的提示語 * @param msg 提示語 * @ TODO 請求成功,通常用來提示msg */ void onSuccessToast(String msg); /** * 請求失敗 * 使用網絡API接口請求方式時,雖然已經請求成功可是因爲{@code msg}的緣由沒法正常返回數據。 * @ TODO 請求失敗,通常用來提示msg狀態值以及提示語,或者顯示無數據的區域【因此須要跟onError方法區別開來】 */ void onFailure(String msg); /** * 請求數據錯誤,指在請求網絡API接口請求方式時,出現沒法聯網、缺乏權限,內存泄露等緣由致使沒法鏈接到請求數據源。 * @ TODO 請求錯誤,通常隱藏加載提示對話框,提示服務器返回的失敗信息等 */ void onError(String msg); /** * 無網絡時返回 * @ TODO 通常隱藏加載提示對話框,提示當前網絡不可用,或者顯示無網絡的區域【因此須要跟onError方法區別開來】 */ void onNoNetWork(String msg); }
IBaseView.java【提取出來通用的抽象方法】
package com.why.project.okhttputilsmvpdemo.iview; /** * Created by HaiyuKing * Used IView基類接口(含有通用的抽象方法聲明) */ public interface IBaseView { /** 顯示正在加載進度框【通用】*/ void showLoading(String msg); /** 隱藏正在加載進度框【通用】*/ void hideLoading(); /**顯示提示信息【通用】*/ void showToast(String msg); /** 獲取OkHttpUtil用到的tag,通常使用當前類的類名便可。好比:this.getClass().getSimpleName()【通用】*/ String getOkHttpUtilTag(); /** 處理失敗的狀況【應該每個接口對應一個,不過此處省略了】【主要用於第一次請求的時候,顯示提示區域,通常狀況下能夠直接showToast便可】*/ void showFail(String msg); /** * 處理無網絡的狀況【應該每個接口對應一個,不過此處省略了】【主要用於第一次請求的時候,顯示提示區域,通常狀況下能夠直接showToast便可】*/ void showNotNetWork(String msg); }
IUpdateAppView.java【若是跟某個activity或者fragment耦合度很高,那麼能夠命名爲MainActivityView.java(也就是以這個activity或者fragment命名)】【命名規則:I{xxx}View】
package com.why.project.okhttputilsmvpdemo.iview; import com.why.project.okhttputilsmvpdemo.bean.UpdateVersionBean; /** * Created by HaiyuKing * Used 更新APP的view */ public interface IUpdateAppView extends IBaseView{ /** 打開發現新版本對話框*/ void showUpdateDialog(UpdateVersionBean updateVersionBean); }
UpdateAppPresenter.java【若是跟某個activity或者fragment耦合度很高,那麼能夠命名爲MainActivityPresenter.java(也就是以這個activity或者fragment命名)】【命名規則:xxxxPresenter】
package com.why.project.okhttputilsmvpdemo.presenter; import android.text.TextUtils; import com.why.project.okhttputilsmvpdemo.bean.UpdateVersionBean; import com.why.project.okhttputilsmvpdemo.iview.IUpdateAppView; import com.why.project.okhttputilsmvpdemo.model.LoadingDataCallBack; import com.why.project.okhttputilsmvpdemo.model.UpdateVersionModel; /** * Created by HaiyuKing * Used 更新APP的presenter */ public class UpdateAppPresenter { private IUpdateAppView mvpView;//view接口類 private UpdateVersionModel mUpdateVersionModel;//發現新版本接口請求的model類 public UpdateAppPresenter(){ mUpdateVersionModel = new UpdateVersionModel(); } /** * 綁定view,通常在初始化中調用該方法 */ public void attachView(IUpdateAppView view){ mvpView = view; } /** * 斷開view,通常在onDestroy中調用 */ public void detachView() { mvpView = null; } /** * 是否與View創建鏈接 * 每次調用業務請求的時候都要出先調用方法檢查是否與View創建鏈接 */ public boolean isViewAttached(){ return mvpView != null; } /**發現新版本接口數據*/ public void updateVersion() { if (!TextUtils.isEmpty(mvpView.getOkHttpUtilTag())) { mUpdateVersionModel.updateVersionInfo(mvpView.getOkHttpUtilTag(), new LoadingDataCallBack<UpdateVersionBean>() { @Override public void onBefore(String msg) { if (isViewAttached()) { mvpView.showLoading(msg); } } @Override public void onAfter() { if (isViewAttached()) { mvpView.hideLoading(); } } @Override public void onSuccess(UpdateVersionBean response) { if (isViewAttached()) { mvpView.showUpdateDialog(response); } } @Override public void onSuccessToast(String msg) { if (isViewAttached()) { mvpView.showToast(msg); } } @Override public void onFailure(String msg) { if (isViewAttached()) { mvpView.showFail(msg); } } @Override public void onError(String msg) { if (isViewAttached()) { mvpView.showToast(msg); } } @Override public void onNoNetWork(String msg) { } }); } } }
package com.why.project.okhttputilsmvpdemo; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.why.project.okhttputilsmvpdemo.bean.UpdateVersionBean; import com.why.project.okhttputilsmvpdemo.iview.IUpdateAppView; import com.why.project.okhttputilsmvpdemo.presenter.UpdateAppPresenter; import com.why.project.okhttputilsmvpdemo.utils.ToastUtil; import com.why.project.okhttputilsmvpdemo.utils.httputil.HttpUtil; import com.zhy.http.okhttp.OkHttpUtils; public class MainActivity extends AppCompatActivity implements IUpdateAppView{ private static final String TAG = MainActivity.class.getSimpleName(); private UpdateAppPresenter mvpUpdateAppPresenter;//發現新版本 private String okHttpTag = "";//網絡請求用到的tag private Button btn_get; private TextView tv_show; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //presenter綁定view{1} if(mvpUpdateAppPresenter == null){ mvpUpdateAppPresenter = new UpdateAppPresenter(); } //presenter綁定view{2} if(mvpUpdateAppPresenter != null) { mvpUpdateAppPresenter.attachView(this); } initViews(); initData(); initEvents(); } @Override public void onPause() { // TODO Auto-generated method stub super.onPause(); //取消網絡請求,根據tag取消請求 OkHttpUtils.getInstance().cancelTag(okHttpTag); } protected void onDestroy() { //取消網絡請求 Log.w(TAG,"this.getClass().getSimpleName()="+this.getClass().getSimpleName()); OkHttpUtils.getInstance().cancelTag(okHttpTag); super.onDestroy(); //presenter解綁view{3} if(mvpUpdateAppPresenter != null){ mvpUpdateAppPresenter.detachView(); } } private void initViews() { btn_get = (Button) findViewById(R.id.btn_get); tv_show = (TextView) findViewById(R.id.tv_show); } /**初始化數據*/ private void initData() { okHttpTag = this.getClass().getSimpleName(); } private void initEvents() { btn_get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (HttpUtil.isNetworkAvailable(MainActivity.this)) { //執行網絡請求接口 try { mvpUpdateAppPresenter.updateVersion();//請求發現新版本接口 } catch (Exception e) { e.printStackTrace(); } }else{ ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.network_enable)); } } }); } @Override public void showLoading(String msg) { //showProgressDialog("");//顯示進度加載框 } @Override public void hideLoading() { //dismissProgressDialog();//隱藏進度加載框 } @Override public void showToast(String msg) { ToastUtil.showShortToast(msg); } @Override public String getOkHttpUtilTag() { return okHttpTag; } @Override public void showFail(String msg) { ToastUtil.showShortToast(msg); } @Override public void showNotNetWork(String msg) { ToastUtil.showShortToast(msg); } @Override public void showUpdateDialog(UpdateVersionBean updateVersionBean) { String showText = "新版本號:" + updateVersionBean.getVersionName() + "\n是否強制更新:" + updateVersionBean.getForceUpdate() + "\n標題:" + updateVersionBean.getTitle() + "\n內容:" + updateVersionBean.getContent().replace("\\n", "\n") + "\n文件大小:" + updateVersionBean.getFileSize() + "\n下載地址:" + updateVersionBean.getDownloadurl(); tv_show.setText(showText); } }
package com.why.project.okhttputilsmvpdemo; import android.content.Context; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.why.project.okhttputilsmvpdemo.bean.UpdateVersionBean; import com.why.project.okhttputilsmvpdemo.iview.IUpdateAppView; import com.why.project.okhttputilsmvpdemo.presenter.UpdateAppPresenter; import com.why.project.okhttputilsmvpdemo.utils.ToastUtil; import com.why.project.okhttputilsmvpdemo.utils.httputil.HttpUtil; import com.zhy.http.okhttp.OkHttpUtils; /** * Created by HaiyuKing * Used */ public class MainFragment extends Fragment implements IUpdateAppView{ private static final String TAG = MainFragment.class.getSimpleName(); private UpdateAppPresenter mvpUpdateAppPresenter;//發現新版本 private String okHttpTag = "";//網絡請求用到的tag /**View實例*/ private View myView; private Context mContext; private Button btn_get; private TextView tv_show; @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //presenter綁定view{1} if(mvpUpdateAppPresenter == null){ mvpUpdateAppPresenter = new UpdateAppPresenter(); } } //重寫 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { //presenter綁定view【適用presenter調用代碼在onCreateView方法中執行的狀況】{2} /*if(mvpPresenter != null) { mvpPresenter.attachView(this); }*/ myView = inflater.inflate(R.layout.activity_main, container, false); return myView; } @Override public void onActivityCreated(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onActivityCreated(savedInstanceState); //因爲fragment生命週期比較複雜,因此Presenter在onCreateView建立視圖以後再進行綁定,否則會報空指針異常 //presenter綁定view【若是presenter調用的代碼是在onCreateView中執行的話,那麼此處不合適執行綁定的方法】{2"} if(mvpUpdateAppPresenter != null) { mvpUpdateAppPresenter.attachView(this); } mContext = getActivity(); //初始化控件以及設置 initViews(); //初始化數據 initData(); initEvents(); } @Override public void onResume() { super.onResume(); } @Override public void onPause() { super.onPause(); } @Override public void onDestroyView() { //presenter解綁view{3} if(mvpUpdateAppPresenter != null){ mvpUpdateAppPresenter.detachView(); } super.onDestroyView(); } @Override public void onDestroy() { //取消網絡請求 OkHttpUtils.getInstance().cancelTag(okHttpTag); super.onDestroy(); } private void initViews() { btn_get = (Button) myView.findViewById(R.id.btn_get); tv_show = (TextView) myView.findViewById(R.id.tv_show); } /**初始化數據*/ private void initData() { okHttpTag = this.getClass().getSimpleName(); } private void initEvents() { btn_get.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (HttpUtil.isNetworkAvailable(mContext)) { //執行網絡請求接口 try { mvpUpdateAppPresenter.updateVersion();//請求發現新版本接口 } catch (Exception e) { e.printStackTrace(); } }else{ ToastUtil.showShortToast(MyApplication.getAppContext().getResources().getString(R.string.network_enable)); } } }); } @Override public void showLoading(String msg) { //showProgressDialog("");//顯示進度加載框 } @Override public void hideLoading() { //dismissProgressDialog();//隱藏進度加載框 } @Override public void showToast(String msg) { ToastUtil.showShortToast(msg); } @Override public String getOkHttpUtilTag() { return okHttpTag; } @Override public void showFail(String msg) { ToastUtil.showShortToast(msg); } @Override public void showNotNetWork(String msg) { ToastUtil.showShortToast(msg); } @Override public void showUpdateDialog(UpdateVersionBean updateVersionBean) { String showText = "新版本號:" + updateVersionBean.getVersionName() + "\n是否強制更新:" + updateVersionBean.getForceUpdate() + "\n標題:" + updateVersionBean.getTitle() + "\n內容:" + updateVersionBean.getContent().replace("\\n", "\n") + "\n文件大小:" + updateVersionBean.getFileSize() + "\n下載地址:" + updateVersionBean.getDownloadurl(); tv_show.setText(showText); } }
參考《okhttputils【 Android 一個改善的okHttp封裝庫】使用(一)》
暫時空缺