Commit e30804f8 authored by 赵鹏翔's avatar 赵鹏翔

封装网络框架,添加网络异常回调基础处理,原界面请求重新整理

parent 874a9bc8
...@@ -11,7 +11,7 @@ import com.miya.fastcashier.BuildConfig; ...@@ -11,7 +11,7 @@ import com.miya.fastcashier.BuildConfig;
import com.miya.fastcashier.R; import com.miya.fastcashier.R;
import com.miya.fastcashier.beans.SelfCashierAccountInfo; import com.miya.fastcashier.beans.SelfCashierAccountInfo;
import com.miya.fastcashier.databinding.DialogSystemParameterBinding; import com.miya.fastcashier.databinding.DialogSystemParameterBinding;
import com.miya.fastcashier.net.ApiService; import com.miya.fastcashier.net.ApiRequest;
import com.miya.fastcashier.service.AccountService; import com.miya.fastcashier.service.AccountService;
import com.miya.fastcashier.utils.BaseFunctionKt; import com.miya.fastcashier.utils.BaseFunctionKt;
import com.miya.print.PrinterManager; import com.miya.print.PrinterManager;
...@@ -44,7 +44,7 @@ public class SystemParameterDialog extends Dialog { ...@@ -44,7 +44,7 @@ public class SystemParameterDialog extends Dialog {
setInfo(viewBinding.tvCashier, accountInfo.getShopInfo().getOperatorId()); setInfo(viewBinding.tvCashier, accountInfo.getShopInfo().getOperatorId());
setInfo(viewBinding.tvVersionType, "fastCashier_" + BuildConfig.appType); setInfo(viewBinding.tvVersionType, "fastCashier_" + BuildConfig.appType);
setInfo(viewBinding.tvEquipment, "sunmi_v2pro"); setInfo(viewBinding.tvEquipment, "sunmi_v2pro");
setInfo(viewBinding.tvServerUrl, ApiService.Companion.getBaseUrl()); setInfo(viewBinding.tvServerUrl, ApiRequest.Companion.getBaseUrl());
setInfo(viewBinding.tvWifiName, BaseFunctionKt.getWifyName(getContext())); setInfo(viewBinding.tvWifiName, BaseFunctionKt.getWifyName(getContext()));
setInfo(viewBinding.tvNetIp, BaseFunctionKt.getNetIp(getContext()) == null ? "未知" : BaseFunctionKt.getNetIp(getContext())); setInfo(viewBinding.tvNetIp, BaseFunctionKt.getNetIp(getContext()) == null ? "未知" : BaseFunctionKt.getNetIp(getContext()));
setInfo(viewBinding.tvPrintType, PrinterManager.getInstance().getPrinter() == null ? setInfo(viewBinding.tvPrintType, PrinterManager.getInstance().getPrinter() == null ?
......
package com.miya.fastcashier.net
import android.util.Log
import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.LoginRequest;
import com.miya.fastcashier.net.BaseResult
import com.miya.fastcashier.net.MiyaHttpLoggingInterceptor
import com.miya.fastcashier.utils.manage.AccountPasswordManageKit
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body
import retrofit2.http.POST
class ApiRequest private constructor() {
companion object {
private const val BASE_URL = "https://hhms.miyapay.com/"
private var apiService: ApiService? = null
private var sInstance: ApiRequest? = null
@Synchronized
fun getInstance(): ApiRequest {
if (null == sInstance) {
sInstance = ApiRequest()
}
return sInstance!!
}
private fun getApiService(): ApiService {
if (null == apiService) {
val httpLoggingInterceptor =
MiyaHttpLoggingInterceptor {
Log.e("####", it)
}.apply { level = MiyaHttpLoggingInterceptor.Level.BODY }
val client = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
apiService = retrofit.create(ApiService::class.java)
}
return apiService!!
}
fun getBaseUrl(): String {
return BASE_URL
}
}
fun login(
loginRequest: LoginRequest,
commonCallback: CommonCallback<SelfCashierAccountInfo>
) {
getApiService().login(loginRequest).enqueue(commonCallback)
}
}
\ No newline at end of file
package com.miya.fastcashier.net package com.miya.fastcashier.net
import android.util.Log import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.beans.LoginRequest; import retrofit2.Call
import com.miya.fastcashier.net.BaseResult
import com.miya.fastcashier.net.MiyaHttpLoggingInterceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import retrofit2.http.Body import retrofit2.http.Body
import retrofit2.http.POST import retrofit2.http.POST
...@@ -18,39 +12,9 @@ interface ApiService { ...@@ -18,39 +12,9 @@ interface ApiService {
companion object { companion object {
const val LOGIN: String = "verify/auth/token" const val LOGIN: String = "verify/auth/token"
private const val BASE_URL = "https://hhms.miyapay.com/"
private var service: ApiService? = null
fun getApi(): ApiService {
if (null == service) {
val httpLoggingInterceptor =
MiyaHttpLoggingInterceptor {
Log.e("####", it)
}.apply { level = MiyaHttpLoggingInterceptor.Level.BODY }
val client = OkHttpClient.Builder()
.addInterceptor(httpLoggingInterceptor)
.build()
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.client(client)
.addConverterFactory(GsonConverterFactory.create())
.build()
service = retrofit.create(ApiService::class.java)
}
return service!!
}
fun getBaseUrl(): String {
return BASE_URL
}
} }
@POST(LOGIN) @POST(LOGIN)
suspend fun login(@Body loginRequestCall: LoginRequest): BaseResult<SelfCashierAccountInfo> fun login(@Body loginRequestCall: LoginRequest): Call<BaseResult<SelfCashierAccountInfo>>
} }
\ No newline at end of file
package com.miya.fastcashier.net package com.miya.fastcashier.net
import java.io.Serializable
data class BaseResult<T>(val code: String, val msg: String, val data: T)
\ No newline at end of file data class BaseResult<T>(val code: String, val msg: String, val data: T) : Serializable {
fun isSuccess(): Boolean {
return code.equals("200")
}
fun getError(): String {
return msg
}
}
\ No newline at end of file
package com.miya.fastcashier.net;
import android.util.Log;
import com.miya.fastcashier.BaseApplication;
import com.miya.fastcashier.R;
import com.miya.fastcashier.utils.BaseFunctionKt;
import java.net.SocketTimeoutException;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* 类描述:通用请求返回
* 创建人:zpxiang
* 创建时间:
* 修改人:
* 修改时间:
*/
public abstract class CommonCallback<T> implements Callback<BaseResult<T>> {
private static final String RESPONSE_MSG_UNKNOW = "未知异常";
private static final String CALLBACK_SUCCEED_CODE = "200";
interface ErrorType {
int ERROR_TYPE_CUSTOM = 0;
int ERROR_TYPE_HTTP = 1;
int ERROR_TYPE_EXCEPTION = 2;
}
interface ResponseCode {
String RESPONSE_CODE_FAILED = String.valueOf(-1); // 返回数据失败
String RESPONSE_CODE_NETWORK_DISCONNECT = String.valueOf(-2); // 无网络
String RESPONSE_CODE_NETWORK_TIMEOUT = String.valueOf(-3); // 超时
}
@Override
public void onResponse(Call<BaseResult<T>> call, Response<BaseResult<T>> response) {
if (response.isSuccessful() && response.body() != null) {
String responseCode = response.body().getCode(); // 业务自定义Code
if (CALLBACK_SUCCEED_CODE.equals(responseCode)) {
onSuccess(response.body().getData());
} else {
onFailure(ErrorType.ERROR_TYPE_CUSTOM,
responseCode,
response.body().getError());
}
} else if (response.errorBody() != null) {
onFailure(ErrorType.ERROR_TYPE_HTTP,
String.valueOf(response.code()),
response.errorBody().toString());
} else {
onFailure(ErrorType.ERROR_TYPE_HTTP,
ResponseCode.RESPONSE_CODE_FAILED,
RESPONSE_MSG_UNKNOW); // 理论上不会存在此种情况
}
}
@Override
public void onFailure(Call<BaseResult<T>> call, Throwable t) {
String temp = t.getMessage();
Log.e("#### HttpLog", "请求失败:" + temp);
String errorMessage;
if (!BaseFunctionKt.isNetworkConnected(BaseApplication.Companion.getApplication())) {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_network_error);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_NETWORK_DISCONNECT, errorMessage);
return;
}
if (t instanceof SocketTimeoutException) {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_network_timeout);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_NETWORK_TIMEOUT, errorMessage);
} else {
errorMessage = BaseApplication.Companion.getApplication().getString(R.string.common_prompt_data_error);
onFailure(ErrorType.ERROR_TYPE_EXCEPTION, ResponseCode.RESPONSE_CODE_FAILED, errorMessage);
}
}
public abstract void onSuccess(T data);
public abstract void onFailure(int errorType, String errorCode, String errorMessage);
}
...@@ -102,3 +102,20 @@ fun getVersion(context: Context): String? { ...@@ -102,3 +102,20 @@ fun getVersion(context: Context): String? {
} }
return version return version
} }
/**
* 判断是否有网络连接
* @param context
*/
fun isNetworkConnected(context: Context?): Boolean {
if (context != null) {
val mConnectivityManager = context
.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
val mNetworkInfo = mConnectivityManager.activeNetworkInfo
if (mNetworkInfo != null) {
return mNetworkInfo.isAvailable
}
}
return false
}
...@@ -8,8 +8,8 @@ import com.miya.fastcashier.R ...@@ -8,8 +8,8 @@ import com.miya.fastcashier.R
import com.miya.fastcashier.beans.LoginFormState import com.miya.fastcashier.beans.LoginFormState
import com.miya.fastcashier.beans.LoginRequest import com.miya.fastcashier.beans.LoginRequest
import com.miya.fastcashier.beans.SelfCashierAccountInfo import com.miya.fastcashier.beans.SelfCashierAccountInfo
import com.miya.fastcashier.net.ApiService import com.miya.fastcashier.net.ApiRequest
import com.miya.fastcashier.net.BaseResult import com.miya.fastcashier.net.CommonCallback
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
...@@ -19,27 +19,26 @@ class LoginViewModel : ViewModel() { ...@@ -19,27 +19,26 @@ class LoginViewModel : ViewModel() {
val _loginForm = MutableLiveData<LoginFormState>() val _loginForm = MutableLiveData<LoginFormState>()
val loginFormState: LiveData<LoginFormState> = _loginForm val loginFormState: LiveData<LoginFormState> = _loginForm
fun login(userName: String, passWord: String) { fun login(userName: String, passWord: String) {
viewModelScope.launch(Dispatchers.IO) { viewModelScope.launch(Dispatchers.IO) {
try {
val result = Result.success(
errorHandle(ApiService.getApi().login(LoginRequest(userName, passWord, "")))
)
loginLiveData.postValue(result) ApiRequest.getInstance().login(LoginRequest(userName, passWord, ""),
} catch (e: Exception) { object : CommonCallback<SelfCashierAccountInfo>(){
loginLiveData.postValue(Result.failure(e)) override fun onSuccess(data: SelfCashierAccountInfo) {
} loginLiveData.postValue(Result.success(data))
} }
override fun onFailure(
errorType: Int,
errorCode: String,
errorMessage: String
) {
loginLiveData.postValue(Result.failure(RuntimeException(errorMessage)))
} }
//TODO 待优化 })
private fun <T> errorHandle(result: BaseResult<T>): T {
if (result.code != "200") {
throw RuntimeException(result.msg)
} }
return result.data;
} }
fun loginDataChanged(username: String, password: String) { fun loginDataChanged(username: String, password: String) {
......
<resources> <resources>
<string name="app_name">匡威收银宝</string> <string name="app_name">匡威收银宝</string>
<string name="common_prompt_network_error">网络异常,请检查后再试</string>
<string name="common_prompt_network_timeout">请求超时,请重试</string>
<string name="common_prompt_data_error">加载失败,请重新加载</string>
<string name="title_activity_login">LoginActivity</string> <string name="title_activity_login">LoginActivity</string>
<string name="prompt_email">Email</string> <string name="prompt_email">Email</string>
<string name="prompt_password">Password</string> <string name="prompt_password">Password</string>
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment