Fix:优化从服务器获取逻辑

This commit is contained in:
LeGend-wLw 2024-02-04 23:49:19 +08:00
parent aa3ba1d41f
commit cd8b37e63c
1 changed files with 63 additions and 38 deletions

View File

@ -1,54 +1,79 @@
package com.lizongying.mytv package com.lizongying.mytv
import android.content.Context import android.content.Context
import com.google.gson.Gson import android.util.Log
import com.google.gson.reflect.TypeToken import kotlinx.coroutines.CoroutineScope
import java.io.File import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import java.io.IOException
object TVList { object TVList {
lateinit var list: Map<String, List<TV>> @Volatile
var list: Map<String, List<TV>>? = null
fun init(context: Context){ get():Map<String, List<TV>>? {
if(::list.isInitialized){ //等待初始化完成
return while (this.list === null) {
} Thread.sleep(10)
synchronized(this){
if(::list.isInitialized){
return
} }
list = setupTV(context) return this.list
} }
}
private fun setupTV(context:Context): Map<String, List<TV>> { /**
val map: MutableMap<String, MutableList<TV>> = mutableMapOf() * 初始化
val appDirectory = Utils.getAppDirectory(context) *
* @param context Context
*/
fun init(context: Context) {
CoroutineScope(Dispatchers.Default).launch {
//获取本地版本号
val localVersion = ChannelUtils.getLocalVersion(context)
//获取服务器版本号
val serverVersion = try {
ChannelUtils.getServerVersion(context)
} catch (e: IOException) {
Log.e("TVList", "无法从服务器获取版本信息", e)
Integer.MIN_VALUE
}
//频道列表
val channelTVMap: MutableMap<String, MutableList<TV>> = mutableMapOf()
//是否从服务器更新
var updateFromServer = false
//获取频道列表
val tvList: List<TV> = if (localVersion < serverVersion) {
//获取服务器地址
val url = ChannelUtils.getServerUrl(context)
//是否从服务器更新
updateFromServer = true
//检查当前目录下是否存在channels.json try {
var file = File(appDirectory, "channels.json") ChannelUtils.getServerChannel(url)
if (!file.exists()) { } catch (e: IOException) {
//不存在则从assets中拷贝 Log.e("TVList", "无法从服务器获取频道信息", e)
file = File(appDirectory, "channels.json") updateFromServer = false
file.createNewFile() ChannelUtils.getLocalChannel(context)
context.assets.open("channels.json").use { input -> }
file.outputStream().use { output -> } else {
input.copyTo(output) //获取本地频道
ChannelUtils.getLocalChannel(context)
}
//按频道分类
for (tv in tvList) {
val key = tv.channel
if (channelTVMap.containsKey(key)) {
val list = channelTVMap[key]!!
list.add(tv)
channelTVMap[key] = list
} else {
channelTVMap[key] = mutableListOf(tv)
} }
} }
} //保存频道列表
list = channelTVMap
//读取channels.json并转换为Map<String,LIst<TV>> //保存版本号
val json = file.readText() if (updateFromServer) {
//防止类型擦除 ChannelUtils.updateLocalChannel(context, serverVersion, tvList)
val type = object : TypeToken<Array<TV>>() {}.type
Gson().fromJson<Array<TV>>(json, type).forEach {
if (map.containsKey(it.channel)) {
map[it.channel]?.add(it)
} else {
map[it.channel] = mutableListOf(it)
} }
} }
return map
} }
} }