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