在之前java开发Android做回调都是使用接口来做的,kotlin后面新增函数作为参数解决啦只限于接口做回调,使用更加方便,上代码: 新增OkhttpFunCallBack类: class OkhttpFunCallBack : Callback{
var mOkHttpCall:((requestBody: RequestBodyContent<T>?)->Unit)?= null
var mOkHttpError:((error: String)->Unit)?= null
private var mTypeToken:TypeToken<RequestBodyContent<T>>? = null
constructor()
constructor( okHttpCall:(requestBody: RequestBodyContent<T>?) -> Unit,
okHttpError:(error: String) -> Unit,
typeToken:TypeToken<RequestBodyContent<T>>){
mOkHttpCall = okHttpCall
mOkHttpError = okHttpError
mTypeToken = typeToken
}
override fun onFailure(call: Call, e: IOException) {
mOkHttpError?.let { it1 -> it1("") }
}
override fun onResponse(call: Call, response: Response) {
val body: String? = response.body?.string();
response.body?.let {
//一定要Dispatchers.Main 不然协程不会切换线程
GlobalScope.launch(Dispatchers.Main) {
body?.let { it1 ->
val content: RequestBodyContent<T>? = JsonUtils.jsonTo2(it1,
mTypeToken)
Log.e("token",content.toString())
mOkHttpCall?.let { it2 -> it2(content) };
}
}
}
}
} 修改OkhttpUtils类:新增加postJsonFunRequest方法 代码: fun postJsonFunRequest(map:HashMap<String,String>,url:String,okhttpCallBack: OkhttpFunCallBack){ if (TextUtils.isEmpty(url)){ return } var builder: FormBody.Builder = FormBody.Builder(); if (map.size > 0){ for (key in map.keys){ key.let { builder.add(it, map[it].toString()) } } }
val formBody:FormBody = builder.build()
val request: Request = Request.Builder().url(url)
.post(formBody)
.build()
val call: Call? = okhttp?.newCall(request)
call?.enqueue(okhttpCallBack)
}
调用方法:(map是参数) val datType:TypeToken<RequestBodyContent> = object : TypeToken<RequestBodyContent>(){}; with(OkhttpUtils){ getInstance().postJsonFunRequest(map,“url”, OkhttpFunCallBack(okHttpCall = { requestBody -> Log.e("","" + requestBody?.result?.name) Toast.makeText(getApplication(),“请求网络数据是:” + requestBody?.result?.name ,Toast.LENGTH_LONG).show() }, okHttpError = {typeToken -> Log.e("",typeToken) },datType)) }
|