From d8342e8c6a4119931a3831e4a306698f8049a557 Mon Sep 17 00:00:00 2001 From: LeGend-wLw <874644990@qq.com> Date: Mon, 5 Feb 2024 14:25:18 +0800 Subject: [PATCH] =?UTF-8?q?Add:=E4=BB=8E=E6=B7=98=E5=AE=9D=E6=9C=8D?= =?UTF-8?q?=E5=8A=A1=E5=99=A8=E8=8E=B7=E5=8F=96=E5=BD=93=E5=89=8D=E6=97=B6?= =?UTF-8?q?=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../main/java/com/lizongying/mytv/Utils.kt | 28 +++++++++++++++++-- 1 file changed, 26 insertions(+), 2 deletions(-) diff --git a/app/src/main/java/com/lizongying/mytv/Utils.kt b/app/src/main/java/com/lizongying/mytv/Utils.kt index d1c53a0..206a407 100644 --- a/app/src/main/java/com/lizongying/mytv/Utils.kt +++ b/app/src/main/java/com/lizongying/mytv/Utils.kt @@ -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 {