Add:从淘宝服务器获取当前时间

This commit is contained in:
LeGend-wLw 2024-02-05 14:25:18 +08:00
parent 6387f48409
commit d8342e8c6a
1 changed files with 26 additions and 2 deletions

View File

@ -2,6 +2,10 @@ package com.lizongying.mytv
import android.content.res.Resources
import android.util.TypedValue
import com.google.gson.Gson
import com.lizongying.mytv.api.TimeResponse
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.*
@ -10,8 +14,28 @@ object Utils {
return SimpleDateFormat(format, Locale.CHINA).format(Date())
}
fun getDateTimestamp(): Long {
return Date().time / 1000
suspend fun getDateTimestamp(): Long {
return getTimestampFromServer() / 1000
}
/**
* 从服务器获取时间戳
* @return Long 时间戳
*/
private suspend fun getTimestampFromServer(): Long {
return withContext(Dispatchers.IO) {
val client = okhttp3.OkHttpClient.Builder().connectTimeout(500, java.util.concurrent.TimeUnit.MILLISECONDS)
.readTimeout(1, java.util.concurrent.TimeUnit.SECONDS).build()
client.newCall(
okhttp3.Request.Builder().url("https://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp")
.build()
).execute().use { response ->
if (!response.isSuccessful) throw java.io.IOException("Unexpected code $response")
val body = response.body()
val string = body?.toString()
Gson().fromJson(string, TimeResponse::class.java).data.t.toLong()
}
}
}
fun dpToPx(dp: Float): Int {