代码拉取完成,页面将自动刷新
Android通用库,对常用组件和框架进行封装,用以提升开发效率. 支持:网络接口日志打印、文件上传、下载进度监听、断点下载等功能。
network library 采用Retrofit+OkHttp+Kotlin的形式进行封装,主要目的是对于kotlin协程访问网络接口的支持。
implementation 'cn.hitcoder.android:network:1.0.0'
maven { url 'https://jitpack.io' }
implementation 'com.gitee.hitcoder:network:0.0.1'
interface NetworkInterface {
/**
* 用户登录接口
*/
@Headers("Content-Type: application/json", "Accept: application/json")
@POST("basic/user/login")
fun login(@Body route: RequestBody?): Call<NetResponse<UserBasicInfo?>>
/**
* 上传文件
*/
@Multipart
@POST("/upload")
fun upload(@Part file: List<MultipartBody.Part>?): Call<String>
}
val net = NetWorkApi.Builder
.setBaseUrl(YOUR_BASL_URL)
.setErrorHandler {
when (it) {
//匹配不同的服务器返回值类型
is NetResponse<*> -> {
if (!TextUtils.equals(it.status.code, "1")) {
throw ServerException(-1, "网络接口调用失败")
}
}
}
}
.setCallAdapterFactory() //设置CallAdapterFactory
.setConverterFactory() //设置ConverterFactory
.addInterceptor() //设置Interceptor
.setDebug(true) //打印接口访问日志
.setTimeout(30) //设置超时时间
.build()
//定义扩展函数,执行框架内封装的同步执行扩展函数,传入自定义errorHandler
fun <T> Call<T>.exe() = executeEx(net.appErrorHandler)
//定义扩展函数,执行框架内封装的异步执行扩展函数,传入自定义errorHandler
fun <T> Call<T>.enQ(callback: (code: Int, message: String, data: T?) -> Unit) =
enqueueEx(callback, net.appErrorHandler)
/**
* 封装请求参数
*/
fun <T> requestBody(params: T): RequestBody {
val netRequest = NetRequest("03815d7a-ee06-48de-8893-c6c4aa0cc835", "", "", "", params)
val jsonString = Gson().toJson(netRequest)
return jsonString.toJsonRequestBody()
}
访问普通网络接口
val loginRequest = LoginRequest("yangqinhe", "1234567", "android")
//同步执行
launch(Dispatchers.IO) {
val loginData =
net.getService(NetworkInterface::class.java)
.login(requestBody(loginRequest))
.exe()
withContext(Dispatchers.Main) {
textView.text = loginData.toString()
Log.e("TAG", loginData.toString())
}
}
//异步执行
val enQ = net.getService(NetworkInterface::class.java)
.login(requestBody(loginRequest))
.enQ { code, message, data ->
textView.text = "code: $code message: $message data: $data"
Log.e("YQH", "code: $code message: $message data: $data")
}
//取消
enQ.cancel()
文件上传
launch(Dispatchers.IO) {
val file = File(getExternalFilesDir(null)?.absolutePath, "1.jpg")
val file2 = File(getExternalFilesDir(null)?.absolutePath, "2.jpg")
Log.e("TAG", "totalLength : ${file.length() + file2.length()}")
val executeExa =
net.getRequestProgressService(NetworkInterface::class.java)
{ read, total, done ->
textView.text = Thread.currentThread().name + " 进度: " + read * 100 / total
Log.e(
"TAG",
Thread.currentThread().name + " 进度: " + read * 100 / total
)
}
.upload(
RequestBodyBuilder()
.addParam("a", "你好")
.addFile(FileInfo("file", "1.jpg", file))
.addFile(FileInfo("file2", "2.jpg", file2))
.buildMultipartBody().parts
).exe()
Log.e("TAG", executeExa.toString())
}
文件下载,由于retrofit下载文件时,如果指定了Range,则会把文件下载到内存中,大文件容易造成oom,因此,文件下载功能是自己封装的AsyncTask,内部实现了断点下载、以及文件下载模式:COVER(覆盖原文件)、RENAME(文件名称冲突时,重命名)、IF_EXIT(如果下载路径有文件,则直接返回下载成功)
net.downloadFile("http://app.2345.cn/appsoft/81595.apk",
getExternalFilesDir(null)?.absolutePath + "/kuake.apk",
object : FileDownload {
override fun cover(): Cover {
return Cover.RENAME
}
override fun downloadStart() {
Log.e("TAG", "开始下载")
textView.text = "开始下载"
}
override fun downloadInProgress(writeBytes: Long, totalLength: Long) {
textView.text =
Thread.currentThread().name + " 进度: " + writeBytes * 100 / totalLength
Log.e(
"TAG",
Thread.currentThread().name + " 进度: " + writeBytes * 100 / totalLength
)
}
override fun downloadSuccess(filePath: String) {
Log.e("TAG", "下载完成:$filePath")
textView.text = "下载完成:$filePath"
}
override fun downloadFail(errorMessage: String) {
textView.text = "下载失败:$errorMessage"
Log.e("TAG", "下载失败:$errorMessage")
}
override fun downloadCancel() {
textView.text = "取消下载"
}
}).tag("aaa")
//取消下载文件
net.canDownloadByTag("aaa")
具体内容可见代码。
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。