目标
采用AsyncTask,发送单个或多个网络请求(串行),并更新UI.
实现方案
发送单个网络请求方案
- 修改app工程的build.gradle文件
- 在android节点下添加如下信息
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
- 添加依赖
implementation "com.google.code.gson:gson:2.8.5"
- 定义数据类Task.kt
data class Task(val id: Int, var name: String)
- 创建网络工具类NetworkUtils.kt
fun getInfoByUrl(url: URL): String {
var str = ""
runCatching {
val connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.readTimeout = 5000
connection.connectTimeout = 5000
if (connection.responseCode == 200) {
val inputStream = connection.inputStream
str = streamToString(inputStream)
}
}
return str
}
fun streamToString(inputStream: InputStream): String {
val builder = StringBuilder()
val reader = BufferedReader(InputStreamReader(inputStream))
var con: String?
runCatching {
while (reader.readLine().also { con = it } != null) {
builder.append(con)
}
reader.close()
}
return builder.toString()
}
- activity调用
private fun queryData() {
AsyncTask1().execute()
}
internal inner class AsyncTask1 :
AsyncTask<String?, Void?, String>() {
override fun onPreExecute() {
super.onPreExecute()
}
override fun onPostExecute(info: String) {
super.onPostExecute(info)
val (id, name) = Gson().fromJson(info, Task::class.java)
contentTv.text = name
}
override fun doInBackground(vararg params: String?): String {
val url = "https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json"
return getInfoByUrl(URL(url))
}
}
发送两个网络请求方案
- 修改app工程的build.gradle文件,同上
- 定义数据类Task.kt,同上
- 创建网络工具类NetworkUtils.kt,同上
- activity调用
private fun queryData() {
AsyncTask1().execute()
}
internal inner class AsyncTask1 :
AsyncTask<String?, Void?, String>() {
override fun onPreExecute() {
super.onPreExecute()
}
override fun onPostExecute(info: String) {
super.onPostExecute(info)
val (id, name) = Gson().fromJson(info, Task::class.java)
contentTv.text = name
queryData2()
}
override fun doInBackground(vararg params: String?): String {
val url = "https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/raw/master/data.json"
return getInfoByUrl(URL(url))
}
}
private fun queryData2() {
AsyncTask2().execute()
}
internal inner class AsyncTask2 :
AsyncTask<String?, Void?, String>() {
override fun onPreExecute() {
super.onPreExecute()
}
override fun onPostExecute(info: String) {
super.onPostExecute(info)
val (id, name) = Gson().fromJson(info, Task::class.java)
contentTv2.text = name
}
override fun doInBackground(vararg params: String?): String {
val url = "https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/raw/master/data2.json"
return getInfoByUrl(URL(url))
}
}
代码说明:
queryData方法访问第一个网络接口,在获得返回结果后,再通过queryData2访问第二个接口.
完整源代码
https://gitee.com/cxyzy1/AndroidAsyncTaskDemo/tree/master/asyncTaskDemo
网友评论