7 Commits
9 changed files with 766 additions and 13 deletions

No files matched your search

+4
View File
@@ -6,3 +6,7 @@ local.properties
!apk/*.apk !apk/*.apk
tools/ tools/
notes.txt notes.txt
keystore.properties
*.jks
*.keystore
*.aab
+10
View File
@@ -5,6 +5,16 @@
--- ---
## v9.3.0(2026-10-08)→ ✨新功能
- ✨ **接入安装统计**:启动时调用 `POST /api/public/installations/check-update` 完成安装登记与在线上报(返回 `install_id`)
- ✨ **接入版本推送**:同一请求同时返回 `update_available / latest_version / download_url / file_size / changelog / min_client_version / is_force`
- ✨ 发现新版本时弹出更新提示(版本号、当前版本、文件大小、更新说明;强制更新额外提示),走系统 `DownloadManager` 下载并在完成后自动拉起安装
- ✨ 每 10 分钟心跳 `POST /api/public/installations/heartbeat`,更新"最后上线"时间
- ✨ 设置页新增「版本更新」区块:显示安装上报结果与 `install_id`,可手动「检查更新」
- 🔧 接入服务端:`https://auth.88531.cn`,请求头 `X-Api-Key`;文档见 `auth.88531.cn/#/docs`
- 🔧 新增权限:`REQUEST_INSTALL_PACKAGES`、`POST_NOTIFICATIONS`
## v9.2.0(2026-10-08)→ ✨新功能 / 🐛修复 ## v9.2.0(2026-10-08)→ ✨新功能 / 🐛修复
- 🐛 从设置页或桌面返回时,直接**重连当前流**(不再依赖 `play()`,避免画面定格) - 🐛 从设置页或桌面返回时,直接**重连当前流**(不再依赖 `play()`,避免画面定格)
- ✨「▶ 继续播放」按钮改为强制重连同一路流,恢复更快更可靠 - ✨「▶ 继续播放」按钮改为强制重连同一路流,恢复更快更可靠
+19
View File
@@ -4,6 +4,7 @@
<p><b>港澳台 55 个频道,装上就能看,遥控器一点就换台</b></p> <p><b>港澳台 55 个频道,装上就能看,遥控器一点就换台</b></p>
<p> <p>
<a href="https://github.com/personal82555/gangao-tv/releases/latest"><img src="https://img.shields.io/badge/下载-APK-1B6EF3?style=for-the-badge" alt="下载"></a> <a href="https://github.com/personal82555/gangao-tv/releases/latest"><img src="https://img.shields.io/badge/下载-APK-1B6EF3?style=for-the-badge" alt="下载"></a>
<a href="https://t.me/+7YVPMu9EOChkYmM1"><img src="https://img.shields.io/badge/Telegram-加入交流群-26A5E4?style=for-the-badge&logo=telegram&logoColor=white" alt="Telegram"></a>
<img src="https://img.shields.io/badge/Android-5.0%2B-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Android 5.0+"> <img src="https://img.shields.io/badge/Android-5.0%2B-3DDC84?style=for-the-badge&logo=android&logoColor=white" alt="Android 5.0+">
<img src="https://img.shields.io/badge/平台-Android%20TV%20%7C%20电视盒子%20%7C%20手机-555?style=for-the-badge" alt="平台"> <img src="https://img.shields.io/badge/平台-Android%20TV%20%7C%20电视盒子%20%7C%20手机-555?style=for-the-badge" alt="平台">
</p> </p>
@@ -57,6 +58,24 @@
- 包名:`com.iptv807.tv` | 支持 Android 5.0 及以上 | 横屏 - 包名:`com.iptv807.tv` | 支持 Android 5.0 及以上 | 横屏
- TV 桌面会自动出现横幅图标(Leanback) - TV 桌面会自动出现横幅图标(Leanback)
## 💬 加入交流群
有问题、有建议、想第一时间拿到新版本,欢迎进群里聊。
**👉 [点此加入 Telegram 交流群](https://t.me/+7YVPMu9EOChkYmM1)**
群里能拿到这些:
| | 好处 |
|---|---|
| 📢 | **新版本第一时间通知** —— 版本推送发布后群内同步提醒,不用天天来盯 GitHub Releases |
| 🔧 | **装不上 / 播不出来直接问** —— 带上电视型号和屏幕上的报错文字,通常几分钟就能定位 |
| 📡 | **频道与线路问题互通** —— 哪个台挂了、哪条线更稳,大家互相同步,修得更快 |
| 💡 | **功能建议真的会被采纳** —— 数字键换台、选中高亮、收藏置顶、开机自启,这些都来自群里的反馈 |
| 🎁 | **内测机会** —— 新版本上线前优先发到群里试用 |
> 进群免费,不发广告;遇到问题先看群公告,多数都能自查解决。
## 💳 会员与激活 ## 💳 会员与激活
- **免费**:未激活也能看,每天 1 小时 - **免费**:未激活也能看,每天 1 小时
+22 -2
View File
@@ -1,8 +1,16 @@
import java.util.Properties
plugins { plugins {
id("com.android.application") id("com.android.application")
id("org.jetbrains.kotlin.android") id("org.jetbrains.kotlin.android")
} }
// release 签名:从仓库根的 keystore.properties 读取(该文件已 .gitignore,缺失时不影响 debug 构建)
val ksProps = Properties().apply {
val f = rootProject.file("keystore.properties")
if (f.exists()) f.inputStream().use { load(it) }
}
android { android {
namespace = "com.iptv807.tv" namespace = "com.iptv807.tv"
compileSdk = 35 compileSdk = 35
@@ -11,13 +19,25 @@ android {
applicationId = "com.iptv807.tv" applicationId = "com.iptv807.tv"
minSdk = 21 minSdk = 21
targetSdk = 35 targetSdk = 35
versionCode = 920 versionCode = 943
versionName = "9.2.0" versionName = "9.4.3"
}
signingConfigs {
if (ksProps.isNotEmpty()) {
create("release") {
storeFile = rootProject.file(ksProps.getProperty("storeFile", ""))
storePassword = ksProps.getProperty("storePassword")
keyAlias = ksProps.getProperty("keyAlias")
keyPassword = ksProps.getProperty("keyPassword")
}
}
} }
buildTypes { buildTypes {
release { release {
isMinifyEnabled = false isMinifyEnabled = false
signingConfig = signingConfigs.findByName("release")
proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro") proguardFiles(getDefaultProguardFile("proguard-android-optimize.txt"), "proguard-rules.pro")
} }
} }
+2
View File
@@ -3,6 +3,8 @@
xmlns:tools="http://schemas.android.com/tools"> xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.software.leanback" android:required="false" /> <uses-feature android:name="android.software.leanback" android:required="false" />
+133
View File
@@ -0,0 +1,133 @@
package com.iptv807.tv
import android.content.Context
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.nio.charset.StandardCharsets
/**
* 安装统计 + 版本推送 客户端(auth.88531.cn)
*
* 接口文档:https://auth.88531.cn/#/docs
* POST /api/public/installations/check-update 安装登记 + 检查更新(启动时调用,一石二鸟)
* POST /api/public/installations/heartbeat 仅更新在线时间(周期心跳)
* Header: X-Api-Key + Content-Type: application/json
* 响应:{ code, message, data }
*
* 文档建议:
* 启动/周期心跳时调用 check-update,同时完成安装登记与在线上报;
* verify / check-update / heartbeat 成功都会更新"最后上线"。
*/
object AuthApi {
private const val BASE = "https://auth.88531.cn"
private const val API_KEY = "ak_563f4768d5d411d381e58bc3f76ba447"
@Volatile var lastError: String = ""
/** 检查更新 + 安装登记 的结果 */
data class UpdateInfo(
val ok: Boolean = false,
val msg: String = "",
val updateAvailable: Boolean = false,
val updateRequired: Boolean = false, // 后台开了强制推送
val currentVersion: String = "",
val latestVersion: String = "",
val downloadUrl: String = "",
val fileSize: Long = 0,
val checksum: String = "",
val changelog: String = "",
val minClientVersion: String = "",
val isForce: Int = 0,
val installId: Long = 0
)
/** 当前应用版本号(用于 client_version 与版本比较) */
fun clientVersion(ctx: Context): String = try {
ctx.packageManager.getPackageInfo(ctx.packageName, 0).versionName ?: "0.0.0"
} catch (e: Exception) { "0.0.0" }
/** 完整下载地址(接口返回的是相对路径) */
fun absDownloadUrl(rel: String): String = when {
rel.isEmpty() -> ""
rel.startsWith("http") -> rel
else -> BASE + if (rel.startsWith("/")) rel else "/$rel"
}
/** 检查更新 + 登记安装(网络请求,必须放后台线程) */
@JvmOverloads
fun checkUpdate(machineId: String, cardKey: String = "", ctx: Context? = null): UpdateInfo {
val body = JSONObject().apply {
put("machine_id", machineId)
put("client_version", if (ctx != null) clientVersion(ctx) else "0.0.0")
put("device_info", "AndroidTV ${android.os.Build.MODEL}")
if (cardKey.isNotEmpty()) put("card_key", cardKey)
}
val r = post("/api/public/installations/check-update", body)
val code = r.optInt("code", 0)
if (code != 200) {
lastError = "code=$code ${r.optString("message")}"
return UpdateInfo(ok = false, msg = lastError)
}
val d = r.optJSONObject("data") ?: JSONObject()
val ver = d.optString("version").ifEmpty { d.optString("latest_version") }
val info = UpdateInfo(
ok = true,
msg = "ok",
updateAvailable = d.optBoolean("update_available", false),
updateRequired = d.optBoolean("update_required", false) || d.optInt("is_force", 0) == 1,
currentVersion = d.optString("current_version"),
latestVersion = ver,
downloadUrl = absDownloadUrl(d.optString("download_url")),
fileSize = d.optLong("file_size", 0),
checksum = d.optString("checksum"),
changelog = d.optString("changelog"),
minClientVersion = d.optString("min_client_version"),
isForce = d.optInt("is_force", 0),
installId = d.optLong("install_id", 0)
)
lastError = "ok install=${info.installId}"
return info
}
/** 心跳:仅更新在线时间(网络请求,必须放后台线程) */
@JvmOverloads
fun heartbeat(machineId: String, cardKey: String = "", ctx: Context? = null): Boolean {
val body = JSONObject().apply {
put("machine_id", machineId)
put("client_version", if (ctx != null) clientVersion(ctx) else "0.0.0")
if (cardKey.isNotEmpty()) put("card_key", cardKey)
}
val r = post("/api/public/installations/heartbeat", body)
val ok = r.optInt("code", 0) == 200
lastError = if (ok) "hb ok" else "hb ${r.optString("message")}"
return ok
}
private fun post(path: String, body: JSONObject): JSONObject {
return try {
val conn = (URL(BASE + path).openConnection() as HttpURLConnection).apply {
requestMethod = "POST"
connectTimeout = 12000
readTimeout = 15000
doOutput = true
setRequestProperty("Content-Type", "application/json")
setRequestProperty("X-Api-Key", API_KEY)
setRequestProperty("Accept", "application/json")
}
conn.outputStream.use { it.write(body.toString().toByteArray(StandardCharsets.UTF_8)) }
val code = conn.responseCode
val stream = if (code in 200..299) conn.inputStream else conn.errorStream
val text = try {
stream?.let { BufferedReader(InputStreamReader(it, StandardCharsets.UTF_8)).readText() } ?: ""
} finally { runCatching { stream?.close(); conn.disconnect() } }
if (text.isEmpty()) JSONObject().put("code", code)
else JSONObject(text)
} catch (e: Exception) {
JSONObject().put("code", 0).put("message", e.javaClass.simpleName + ": " + (e.message ?: "").take(80))
}
}
}
@@ -97,6 +97,52 @@ class MainActivity : Activity() {
private var downT = 0L private var downT = 0L
private var exitHint: TextView? = null private var exitHint: TextView? = null
private var confirmOverlay: View? = null private var confirmOverlay: View? = null
/** 右上角「立即授权」按钮(未授权时显示) */
private var authBtn: TextView? = null
/** 右下角「已授权」小字标识(已授权时显示,未授权隐藏) */
private var authStateText: TextView? = null
/** 首次启动简易教程遮罩 */
private var tutorialOverlay: View? = null
private var tutorialVisible = false
/** 更新弹窗的可聚焦按钮 + 当前焦点索引(遥控器左右切换用) */
private var updBtns: Array<TextView?> = emptyArray()
private var updFocusIdx = 0
private var updForce = false
// 安装统计 + 版本推送
private var updateOverlay: View? = null
private var pendingUpdate: AuthApi.UpdateInfo? = null
private var downloadId = -1L
private val heartbeatTask = object : Runnable {
override fun run() {
Thread {
try {
val card = getSharedPreferences("iptv_license", MODE_PRIVATE).getString("card_key", "") ?: ""
AuthApi.heartbeat(LicenseClient.machineCode(this@MainActivity), card, this@MainActivity)
} catch (e: Exception) { }
}.start()
handler.postDelayed(this, 10 * 60 * 1000L) // 每 10 分钟心跳
}
}
private val downloadReceiver = object : android.content.BroadcastReceiver() {
override fun onReceive(ctx: android.content.Context, intent: android.content.Intent) {
if (intent.action != android.app.DownloadManager.ACTION_DOWNLOAD_COMPLETE) return
val id = intent.getLongExtra(android.app.DownloadManager.EXTRA_DOWNLOAD_ID, -1L)
if (id != downloadId) return
val dm = ctx.getSystemService(android.content.Context.DOWNLOAD_SERVICE) as android.app.DownloadManager
val uri = runCatching { dm.getUriForDownloadedFile(id) }.getOrNull()
if (uri != null) runOnUiThread {
statusText.text = "✓ 新版本下载完成,正在打开安装…"
try {
val i = android.content.Intent(android.content.Intent.ACTION_VIEW)
.setDataAndType(uri, "application/vnd.android.package-archive")
.addFlags(android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION)
startActivity(i)
} catch (e: Exception) {
statusText.text = "已下载到 下载/ 目录,请手动安装"
}
}
}
}
private var confirmVisible = false private var confirmVisible = false
private var confirmCancelBtn: TextView? = null private var confirmCancelBtn: TextView? = null
private var channelAdapter: RowAdapter? = null private var channelAdapter: RowAdapter? = null
@@ -143,18 +189,53 @@ class MainActivity : Activity() {
root.addView(statusText, FrameLayout.LayoutParams( root.addView(statusText, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT)) ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
// 4) 右上:免费时长 + 模式 // 4) 右上:免费时长 + 模式 + 【立即授权】按钮(横排,按钮在倒计时右边)
val rightCol = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL } val rightCol = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL }
trialText = TextView(this).apply { trialText = TextView(this).apply {
textSize = 14f; setTextColor(Color.WHITE) textSize = 14f; setTextColor(Color.WHITE)
setBackgroundColor(0x88000000u.toInt()) setBackgroundColor(0x88000000u.toInt())
setPadding(20, 10, 20, 10) setPadding(20, 10, 20, 10)
} }
rightCol.addView(trialText) rightCol.addView(trialText)
authBtn = TextView(this).apply {
text = "🔑 立即授权"
textSize = 14f
setTextColor(Color.WHITE)
setBackgroundColor(0xFF1B6EF3.toInt())
setPadding(26, 10, 26, 10)
isFocusable = true
isFocusableInTouchMode = true
visibility = View.GONE // 授权成功后隐藏
// 遥控器聚焦高亮:蓝底加白框
val pad = (4 * resources.displayMetrics.density).toInt()
setOnFocusChangeListener { v, has ->
v.setBackgroundColor(if (has) 0xFF3D8BFF.toInt() else 0xFF1B6EF3.toInt())
v.setPadding(26, 10, 26, 10)
if (has) v.alpha = 1f else v.alpha = 0.95f
}
setOnClickListener { openAuthPage() }
}
rightCol.addView(authBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { leftMargin = 8 })
val rcLP = FrameLayout.LayoutParams( val rcLP = FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP or Gravity.END) ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.TOP or Gravity.END)
root.addView(rightCol, rcLP) root.addView(rightCol, rcLP)
// 4b) 右下角:已授权标识(小字,不打扰观看;未授权时隐藏)
authStateText = TextView(this).apply {
text = "✓ 已授权"
textSize = 12f
setTextColor(0xB3FFFFFF.toInt()) // 70% 白,弱化存在感
setBackgroundColor(0x59000000.toInt()) // 35% 黑底,保证在亮画面上也看得清
setPadding(14, 6, 14, 6)
setShadowLayer(3f, 1f, 1f, Color.BLACK)
visibility = View.GONE
}
root.addView(authStateText, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
Gravity.BOTTOM or Gravity.END).apply { setMargins(0, 0, 26, 26) })
// 5) 数字键大字 // 5) 数字键大字
digitText = TextView(this).apply { digitText = TextView(this).apply {
textSize = 56f; setTextColor(Color.WHITE) textSize = 56f; setTextColor(Color.WHITE)
@@ -168,8 +249,9 @@ class MainActivity : Activity() {
// 6) 加载罩 // 6) 加载罩
loadingMask = FrameLayout(this).apply { setBackgroundColor(0xB2000000u.toInt()); visibility = View.GONE } loadingMask = FrameLayout(this).apply { setBackgroundColor(0xB2000000u.toInt()); visibility = View.GONE }
loadingText = TextView(this).apply { loadingText = TextView(this).apply {
textSize = 28f; setTextColor(Color.WHITE); gravity = Gravity.CENTER textSize = 16f; setTextColor(0xE6FFFFFF.toInt()); gravity = Gravity.CENTER
setShadowLayer(6f, 3f, 3f, Color.BLACK) setShadowLayer(4f, 2f, 2f, Color.BLACK)
setPadding(32, 0, 32, 0)
} }
loadingMask.addView(loadingText, FrameLayout.LayoutParams( loadingMask.addView(loadingText, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)) ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
@@ -238,12 +320,15 @@ class MainActivity : Activity() {
// 播放期间保持屏幕常亮 // 播放期间保持屏幕常亮
window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON) window.addFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
checkLicense() checkLicense()
startInstallTracking() // 安装统计 + 检查新版本
if (savedInstanceState == null && channels.isNotEmpty()) { if (savedInstanceState == null && channels.isNotEmpty()) {
val defIdx = channels.indexOfFirst { it.name.contains("TVB翡翠台") }.let { if (it >= 0) it else 0 } val defIdx = channels.indexOfFirst { it.name.contains("TVB翡翠台") }.let { if (it >= 0) it else 0 }
playChannel(defIdx) playChannel(defIdx)
// 启动后预取默认频道的相邻频道(很轻量,1 个一个来) // 启动后预取默认频道的相邻频道(很轻量,1 个一个来)
handler.postDelayed({ schedulePrefetch(channels.getOrNull(defIdx)) }, 2000) handler.postDelayed({ schedulePrefetch(channels.getOrNull(defIdx)) }, 2000)
} }
// 新安装首次打开 → 简易使用教程(可关闭,只弹一次)
maybeShowTutorial()
} }
private fun setMode(m: Int) { mode = m } private fun setMode(m: Int) { mode = m }
@@ -283,17 +368,161 @@ class MainActivity : Activity() {
runOnUiThread { runOnUiThread {
isVip = r.ok isVip = r.ok
prefs.edit().putBoolean("is_vip", r.ok).apply() prefs.edit().putBoolean("is_vip", r.ok).apply()
if (r.ok) { trialText.visibility = View.GONE; trialText.text = "VIP" } else enterFreeMode() if (r.ok) {
trialText.visibility = View.GONE; trialText.text = "VIP"
showAuthButton(false)
showAuthState(true) // 右下角显示「✓ 已授权」
} else enterFreeMode()
} }
}.start() }.start()
} }
private fun enterFreeMode() { private fun enterFreeMode() {
trialText.visibility = View.VISIBLE trialText.visibility = View.VISIBLE
showAuthButton(true)
showAuthState(false) // 免费模式下不显示右下角标识
handler.removeCallbacks(uiTick) handler.removeCallbacks(uiTick)
handler.post(uiTick) handler.post(uiTick)
} }
/** 右下角「✓ 已授权」标识 显示/隐藏 */
private fun showAuthState(show: Boolean) {
runOnUiThread {
val t = authStateText ?: return@runOnUiThread
t.visibility = if (show) View.VISIBLE else View.GONE
t.text = if (show) "✓ 已授权" else ""
}
}
/** 显示/隐藏右上角「立即授权」按钮 */
private fun showAuthButton(show: Boolean) {
runOnUiThread {
val b = authBtn ?: return@runOnUiThread
b.visibility = if (show) View.VISIBLE else View.GONE
if (show) {
// 首次出现时自动聚焦,遥控器按 OK 直接进授权页
b.postDelayed({
if (b.visibility == View.VISIBLE && !isPanelVisible() && tutorialOverlay?.visibility != View.VISIBLE) {
b.requestFocus()
}
}, 600)
} else {
b.clearFocus()
}
}
}
/** 菜单键/其他入口统一打开设置页;带三重诊断,打不开时屏幕上有原因 */
private fun openSettingsPage() {
val intent = Intent(this, SettingsActivity::class.java)
// ① 预检查:系统能否解析到这个 Activity(manifest 没注册会返回 null)
val resolve = try { packageManager.resolveActivity(intent, 0) } catch (e: Exception) { null }
if (resolve == null) {
statusText.text = "⚠ 设置页无法解析:manifest 未注册 SettingsActivity"
android.widget.Toast.makeText(this, "设置页无法解析(manifest 未注册)", android.widget.Toast.LENGTH_LONG).show()
return
}
// ② 启动
val before = try { getSharedPreferences("iptv_main", MODE_PRIVATE).getLong("settings_opened_at", 0L) } catch (e: Exception) { 0L }
try {
startActivity(intent)
} catch (e: Exception) {
statusText.text = "⚠ 打开设置失败: ${e.javaClass.simpleName}: ${e.message}"
android.widget.Toast.makeText(this, "打开设置失败: ${e.message}", android.widget.Toast.LENGTH_LONG).show()
return
}
// ③ 1.4 秒后核对:SettingsActivity.onCreate 有没有真的跑起来
handler.postDelayed({
val after = try { getSharedPreferences("iptv_main", MODE_PRIVATE).getLong("settings_opened_at", 0L) } catch (e: Exception) { 0L }
if (after <= before) {
statusText.text = "⚠ 设置页未响应:onCreate 未执行(启动被拦截或立刻结束)"
android.widget.Toast.makeText(this, "设置页未响应,请把这行字告诉我", android.widget.Toast.LENGTH_LONG).show()
}
}, 1400)
}
/** 打开授权/激活页面(就是设置页:卡密激活 + 购买入口 + 撤销授权) */
private fun openAuthPage() { openSettingsPage() }
/** 首次启动:简易使用教程(可关闭,只弹一次) */
private fun maybeShowTutorial() {
try {
if (getSharedPreferences("iptv_main", MODE_PRIVATE).getBoolean("tutorial_done", false)) return
val mask = FrameLayout(this).apply {
setBackgroundColor(0xE6000000.toInt())
isClickable = true // 挡住底层点击
}
val card = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(0xFF161B26.toInt())
setPadding(64, 48, 64, 56)
}
card.addView(TextView(this).apply {
text = "📺 欢迎使用「港澳台直播」"
textSize = 24f; setTextColor(Color.WHITE); setPadding(0, 0, 0, 6)
})
card.addView(TextView(this).apply {
text = "花 30 秒知道怎么用,功能一个不少"
textSize = 14f; setTextColor(0xFF93A1B8.toInt()); setPadding(0, 0, 0, 26)
})
val steps = listOf(
"1️⃣ 按遥控器 OK 键 → 打开选台面板",
"2️⃣ 上下键选频道(选中行蓝底高亮),左右键切换香港 / 澳门 / 台湾分组",
"3️⃣ 直接按数字键 → 快速跳到对应频道(按 9 就是 9 号台)",
"4️⃣ 菜单键 → 收藏 / 取消收藏当前频道",
"5️⃣ 连滑两次 或 按返回键 → 退出应用(都会先弹确认框)",
"6️⃣ 断线自动重连、10 条线路自动切换,画面卡住点「▶ 继续播放」即可"
)
for (t in steps) {
card.addView(TextView(this).apply {
text = t; textSize = 16f; setTextColor(0xFFE6ECF7.toInt())
setLineSpacing(0f, 1.35f); setPadding(0, 9, 0, 9)
})
}
val okBtn = android.widget.Button(this).apply {
text = "知道了,开始观看"
textSize = 17f
isFocusable = true; isFocusableInTouchMode = true
setBackgroundColor(0xFF1B6EF3.toInt())
setTextColor(Color.WHITE)
setOnClickListener { closeTutorial() }
}
card.addView(okBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { topMargin = 34 })
val scroll = android.widget.ScrollView(this).apply {
setBackgroundColor(Color.TRANSPARENT)
isFillViewport = true
addView(card)
}
mask.addView(scroll, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER
).apply { setMargins(260, 90, 260, 90) })
root.addView(mask, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
tutorialOverlay = mask
tutorialVisible = true
okBtn.post { okBtn.requestFocus() } // 遥控器 OK 直接关闭
} catch (e: Exception) {
// 教程失败不能影响正常播放
tutorialVisible = false
}
}
/** 关闭教程并记住(之后不再显示) */
private fun closeTutorial() {
tutorialVisible = false
try {
getSharedPreferences("iptv_main", MODE_PRIVATE).edit().putBoolean("tutorial_done", true).apply()
} catch (e: Exception) { }
root.removeView(tutorialOverlay)
tutorialOverlay = null
}
private fun onUiTick() { private fun onUiTick() {
if (isVip) return if (isVip) return
// 每秒累计一次免费用量,这样右上角倒计时才会真正走动 // 每秒累计一次免费用量,这样右上角倒计时才会真正走动
@@ -403,8 +632,7 @@ class MainActivity : Activity() {
setItemsCanFocus(false) setItemsCanFocus(false)
onItemClickListener = AdapterView.OnItemClickListener { _, _, pos, _ -> onItemClickListener = AdapterView.OnItemClickListener { _, _, pos, _ ->
if (pos == 0) { if (pos == 0) {
startActivity(Intent(this@MainActivity, SettingsActivity::class.java)) openSettingsPage(); hidePanel(); return@OnItemClickListener
hidePanel(); return@OnItemClickListener
} }
if (pos == 0) return@OnItemClickListener if (pos == 0) return@OnItemClickListener
curGroupPos = pos - 1 curGroupPos = pos - 1
@@ -643,11 +871,55 @@ class MainActivity : Activity() {
} }
override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean { override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
// 首次教程显示时:返回/OK 都可关闭
if (tutorialVisible) {
if (keyCode == KeyEvent.KEYCODE_BACK ||
keyCode == KeyEvent.KEYCODE_DPAD_CENTER ||
keyCode == KeyEvent.KEYCODE_ENTER) {
closeTutorial(); return true
}
return true
}
// ★ 更新弹窗显示时:所有按键都由弹窗接管。
// 否则会落到下面的 showPanel()/exitApp()/换台 —— 遥控器就"选不了"了
if (isUpdateDialogVisible()) {
when (keyCode) {
KeyEvent.KEYCODE_BACK -> { hideUpdateDialog(); return true }
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER,
KeyEvent.KEYCODE_NUMPAD_ENTER, KeyEvent.KEYCODE_SPACE -> {
val btn = updBtns.getOrNull(updFocusIdx)
?.takeIf { it.visibility == View.VISIBLE }
?: updBtns.filterNotNull().firstOrNull { it.visibility == View.VISIBLE }
btn?.performClick()
return true
}
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_UP -> { moveUpdateFocus(-1); return true }
KeyEvent.KEYCODE_DPAD_RIGHT, KeyEvent.KEYCODE_DPAD_DOWN -> { moveUpdateFocus( 1); return true }
else -> return true // 数字键 / 菜单键 等全部吞掉(弹窗期间不能换台、不能进设置)
}
}
// 退出确认框显示时:返回=取消,其余交给按钮焦点系统处理(左右切换,OK 确认) // 退出确认框显示时:返回=取消,其余交给按钮焦点系统处理(左右切换,OK 确认)
if (confirmVisible) { if (confirmVisible) {
if (keyCode == KeyEvent.KEYCODE_BACK) { hideExitConfirm(); return true } if (keyCode == KeyEvent.KEYCODE_BACK) { hideExitConfirm(); return true }
return super.onKeyDown(keyCode, event) return super.onKeyDown(keyCode, event)
} }
// 右上角「立即授权」按钮聚焦时:OK 进授权页,返回取消聚焦,方向键清焦点后继续正常换台
if (authBtn?.visibility == View.VISIBLE && authBtn?.isFocused == true) {
when (keyCode) {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> {
openAuthPage(); return true
}
KeyEvent.KEYCODE_BACK -> { authBtn?.clearFocus(); return true }
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN,
KeyEvent.KEYCODE_DPAD_LEFT, KeyEvent.KEYCODE_DPAD_RIGHT -> {
authBtn?.clearFocus() // 不 return:落到下面正常换台/开面板逻辑
}
}
}
// 「继续播放」按钮可见时,遥控 OK/确认 直接触发 // 「继续播放」按钮可见时,遥控 OK/确认 直接触发
if (resumeBtn?.visibility == View.VISIBLE && if (resumeBtn?.visibility == View.VISIBLE &&
(keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER || (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER ||
@@ -712,7 +984,10 @@ class MainActivity : Activity() {
KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> { KeyEvent.KEYCODE_DPAD_CENTER, KeyEvent.KEYCODE_ENTER, KeyEvent.KEYCODE_NUMPAD_ENTER -> {
if (panelCol == 0) { if (panelCol == 0) {
val np = groupAdapter?.selected ?: 0 val np = groupAdapter?.selected ?: 0
if (np == 0) { startActivity(Intent(this, SettingsActivity::class.java)); hidePanel() } if (np == 0) {
openSettingsPage() // 统一走带诊断的入口
hidePanel()
}
else { curGroupPos = np - 1; updateChannelListOfGroup(curGroupPos); panelCol = 1; refreshPanelHighlight() } else { curGroupPos = np - 1; updateChannelListOfGroup(curGroupPos); panelCol = 1; refreshPanelHighlight() }
} else { } else {
val pos = channelAdapter?.selected ?: -1 val pos = channelAdapter?.selected ?: -1
@@ -725,7 +1000,11 @@ class MainActivity : Activity() {
} }
when (keyCode) { when (keyCode) {
KeyEvent.KEYCODE_MENU -> { autoSwitchLine(); return true } // ★ 修复:返回键必须弹退出确认,绝不直接 finish(原来漏了这个分支,
// 导致 BACK 落到 super.onKeyDown() = 系统默认无提示退出)
KeyEvent.KEYCODE_BACK -> { exitApp(); return true }
// ★ 菜单键 → 打开设置页(原来这里是「换线」,换线已移到设置页里)
KeyEvent.KEYCODE_MENU -> { openSettingsPage(); return true }
KeyEvent.KEYCODE_CHANNEL_UP -> { playChannel((currentChannel - 1 + channels.size) % channels.size); return true } KeyEvent.KEYCODE_CHANNEL_UP -> { playChannel((currentChannel - 1 + channels.size) % channels.size); return true }
KeyEvent.KEYCODE_CHANNEL_DOWN -> { playChannel((currentChannel + 1) % channels.size); return true } KeyEvent.KEYCODE_CHANNEL_DOWN -> { playChannel((currentChannel + 1) % channels.size); return true }
KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> { KeyEvent.KEYCODE_DPAD_UP, KeyEvent.KEYCODE_DPAD_DOWN -> {
@@ -788,6 +1067,180 @@ class MainActivity : Activity() {
} }
private val hideExitHintTask = Runnable { exitHint?.visibility = View.GONE } private val hideExitHintTask = Runnable { exitHint?.visibility = View.GONE }
// ===== 安装统计 & 版本推送 =====
private fun startInstallTracking() {
val prefs = getSharedPreferences("iptv_license", MODE_PRIVATE)
val card = prefs.getString("card_key", "") ?: ""
Thread {
val mid = LicenseClient.machineCode(this@MainActivity)
// check-update 一次请求同时完成:安装登记 + 在线上报 + 查新版本
val info = runCatching {
AuthApi.checkUpdate(mid, card, this@MainActivity)
}.getOrDefault(AuthApi.UpdateInfo(msg = AuthApi.lastError))
runOnUiThread {
if (info.ok) {
val sb = StringBuilder("安装上报 ok #${info.installId} · v${AuthApi.clientVersion(this)}")
if (info.updateAvailable) sb.append(" · 发现新版 v${info.latestVersion}")
statusText.text = sb.toString()
handler.postDelayed({
val c = channels.getOrNull(currentChannel)
if (c != null) statusText.text = "▶ ${c.num} ${c.name}"
}, 8000)
if (info.updateAvailable) {
pendingUpdate = info
showUpdateDialog(info)
}
} else {
statusText.text = "安装上报失败: ${info.msg}"
}
}
}.start()
handler.removeCallbacks(heartbeatTask)
handler.postDelayed(heartbeatTask, 60 * 1000L) // 1 分钟后首次心跳
}
/** 新版本提示(自绘浮层,电视全屏主题下 AlertDialog 不可靠) */
private fun showUpdateDialog(info: AuthApi.UpdateInfo) {
if (updateOverlay == null) {
val mask = FrameLayout(this).apply { setBackgroundColor(0xCC000000u.toInt()) }
val card = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.parseColor("#22262E"))
setPadding(64, 48, 64, 48)
}
card.addView(TextView(this).apply {
text = "发现新版本"; textSize = 24f; setTextColor(Color.WHITE)
gravity = Gravity.CENTER; setPadding(0, 0, 0, 12)
})
card.addView(TextView(this).apply {
tag = "ver"; textSize = 40f; setTextColor(Color.parseColor("#4CAF50"))
gravity = Gravity.CENTER; setPadding(0, 0, 0, 16)
})
card.addView(TextView(this).apply {
tag = "meta"; textSize = 15f; setTextColor(Color.LTGRAY)
gravity = Gravity.CENTER; setLineSpacing(0f, 1.2f); setPadding(0, 0, 0, 24)
})
card.addView(TextView(this).apply {
tag = "chg"; textSize = 15f; setTextColor(Color.WHITE)
setBackgroundColor(Color.parseColor("#1C2028"))
setPadding(24, 20, 24, 20); setLineSpacing(0f, 1.25f)
maxLines = 8; gravity = Gravity.CENTER
})
val row = LinearLayout(this).apply { orientation = LinearLayout.HORIZONTAL; gravity = Gravity.CENTER; setPadding(0, 28, 0, 0) }
fun mkBtn(label: String, focusable: Boolean, onClick: () -> Unit): TextView =
TextView(this).apply {
text = label; textSize = 18f; setTextColor(Color.WHITE); gravity = Gravity.CENTER
setPadding(56, 22, 56, 22); isFocusable = focusable; isFocusableInTouchMode = focusable
if (focusable) background = android.graphics.drawable.StateListDrawable().apply {
addState(intArrayOf(android.R.attr.state_focused),
android.graphics.drawable.ColorDrawable(Color.parseColor("#1B6EF3")))
addState(intArrayOf(), android.graphics.drawable.ColorDrawable(Color.parseColor("#3A4150")))
} else setBackgroundColor(Color.parseColor("#2A2F3A"))
setOnClickListener { onClick() }
}
// ★ 两个按钮都必须可聚焦,否则遥控器永远选不到「立即更新」
val laterBtn = mkBtn("稍后", true) { hideUpdateDialog() }.apply { tag = "later" }
val dlBtn = mkBtn("立即更新", true) {
pendingUpdate?.let { startUpdateDownload(it) }; hideUpdateDialog()
}.apply { tag = "dl" }
row.addView(laterBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { rightMargin = 32 })
row.addView(dlBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
card.addView(row)
mask.addView(card, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, Gravity.CENTER))
root.addView(mask, FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
updateOverlay = mask
}
val ver = updateOverlay!!.findViewWithTag<TextView>("ver")
val meta = updateOverlay!!.findViewWithTag<TextView>("meta")
val chg = updateOverlay!!.findViewWithTag<TextView>("chg")
ver.text = "v" + info.latestVersion
val mb = if (info.fileSize > 0) "%.1f MB".format(info.fileSize / 1024.0 / 1024.0) else ""
val force = info.updateRequired || (info.minClientVersion.isNotEmpty() &&
compareVersion(AuthApi.clientVersion(this), info.minClientVersion) < 0)
meta.text = "当前 v${AuthApi.clientVersion(this)}" + (if (mb.isNotEmpty()) " · $mb" else "") +
(if (force) "\n⚠ 请升级到此版本" else "")
chg.text = info.changelog.ifEmpty { "本次更新包含功能优化与问题修复" }
// ★ 强制更新时不给「稍后」(原代码只写了注释没实现)
val laterB = updateOverlay!!.findViewWithTag<TextView>("later")
val dlB = updateOverlay!!.findViewWithTag<TextView>("dl")
updForce = info.updateRequired || (info.minClientVersion.isNotEmpty() &&
compareVersion(AuthApi.clientVersion(this), info.minClientVersion) < 0)
laterB?.visibility = if (updForce) View.GONE else View.VISIBLE
// 可见的按钮列表(强制更新时只剩「立即更新」)
updBtns = arrayOf(if (updForce) null else laterB, dlB)
updFocusIdx = if (updForce) 1 else 1 // 默认聚焦「立即更新」(主操作)
updateOverlay!!.visibility = View.VISIBLE
// ★ 必须主动聚焦,否则遥控器按 OK 不会命中任何按钮
handler.postDelayed({
if (updateOverlay?.visibility == View.VISIBLE) {
updBtns.getOrNull(updFocusIdx)?.requestFocus()
}
}, 120)
}
private fun hideUpdateDialog() {
updateOverlay?.visibility = View.GONE
// 清掉焦点,避免残留焦点挡住后续按键
updBtns.forEach { it?.clearFocus() }
updFocusIdx = 0
}
/** 更新弹窗内切换按钮焦点(遥控器左右/上下) */
private fun moveUpdateFocus(delta: Int) {
val visible = updBtns.filterNotNull().filter { it.visibility == View.VISIBLE }
if (visible.isEmpty()) return
val cur = updBtns.getOrNull(updFocusIdx)
var i = visible.indexOf(cur)
if (i < 0) i = 0
i = (i + delta + visible.size) % visible.size
val target = visible[i]
updFocusIdx = updBtns.indexOf(target)
target.requestFocus()
}
/** 更新弹窗是否显示 */
private fun isUpdateDialogVisible(): Boolean = updateOverlay?.visibility == View.VISIBLE
/** 比较 "9.10.0" vs "9.3.0" 之类 */
fun compareVersion(a: String, b: String): Int {
val pa = a.split('.').map { it.toIntOrNull() ?: 0 }
val pb = b.split('.').map { it.toIntOrNull() ?: 0 }
for (i in 0 until maxOf(pa.size, pb.size)) {
val x = pa.getOrElse(i) { 0 }; val y = pb.getOrElse(i) { 0 }
if (x != y) return if (x > y) 1 else -1
}
return 0
}
/** 用系统 DownloadManager 下载新版本 APK,完成广播里自动拉起安装 */
private fun startUpdateDownload(info: AuthApi.UpdateInfo) {
if (info.downloadUrl.isEmpty()) {
statusText.text = "暂无下载地址,请到后台发布安装包"
return
}
try {
val dm = getSystemService(android.content.Context.DOWNLOAD_SERVICE) as android.app.DownloadManager
val name = "gangao-tv-${info.latestVersion}.apk"
val req = android.app.DownloadManager.Request(Uri.parse(info.downloadUrl))
.setTitle("港澳台直播 v${info.latestVersion}")
.setDescription("正在下载新版本…")
.setNotificationVisibility(android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED)
.setMimeType("application/vnd.android.package-archive")
.setDestinationInExternalFilesDir(this, android.os.Environment.DIRECTORY_DOWNLOADS, name)
downloadId = dm.enqueue(req)
try { registerReceiver(downloadReceiver, android.content.IntentFilter(android.app.DownloadManager.ACTION_DOWNLOAD_COMPLETE)) } catch (e: Exception) { }
statusText.text = "⬇ 已开始下载 v${info.latestVersion},完成后会自动提示安装"
} catch (e: Exception) {
statusText.text = "下载失败: ${e.message}"
}
}
/** 退出前先弹确认框(自绘,不依赖系统对话框主题) */ /** 退出前先弹确认框(自绘,不依赖系统对话框主题) */
private fun exitApp() { private fun exitApp() {
runOnUiThread { runOnUiThread {
@@ -893,7 +1346,14 @@ class MainActivity : Activity() {
if (nowVip && (card.isNotEmpty() || !isVip)) { if (nowVip && (card.isNotEmpty() || !isVip)) {
isVip = true isVip = true
trialText.visibility = View.GONE trialText.visibility = View.GONE
showAuthButton(false)
showAuthState(true) // 右下角显示「✓ 已授权」
handler.removeCallbacks(uiTick) handler.removeCallbacks(uiTick)
} else if (!nowVip && isVip) {
// ★ 设置页里撤销了授权 → 回到免费模式(倒计时 + 立即授权按钮都恢复)
isVip = false
showAuthState(false) // 右下角标识隐藏
enterFreeMode()
} }
} }
// 从桌面/设置返回:先尝试续播,失败则显示「继续播放」按钮 // 从桌面/设置返回:先尝试续播,失败则显示「继续播放」按钮
@@ -923,6 +1383,14 @@ class MainActivity : Activity() {
playRequested = -1 playRequested = -1
if (idx >= 0) playChannel(idx) if (idx >= 0) playChannel(idx)
} }
// 设置页点「切换线路」→ 回来执行(原菜单键功能,现已移到设置页)
run {
val sp = getSharedPreferences("iptv_main", MODE_PRIVATE)
if (sp.getString("pending_action", "") == "switch_line") {
sp.edit().remove("pending_action").apply()
autoSwitchLine()
}
}
} }
/** 点「继续播放」→ 重新连接当前频道(直播流最稳的恢复方式) */ /** 点「继续播放」→ 重新连接当前频道(直播流最稳的恢复方式) */
@@ -965,6 +1433,7 @@ class MainActivity : Activity() {
handler.removeCallbacksAndMessages(null) handler.removeCallbacksAndMessages(null)
playerView.player = null playerView.player = null
player?.release() player?.release()
runCatching { unregisterReceiver(downloadReceiver) }
super.onDestroy() super.onDestroy()
} }
} }
@@ -26,6 +26,7 @@ import android.widget.TextView
class SettingsActivity : Activity() { class SettingsActivity : Activity() {
private lateinit var statusText: TextView private lateinit var statusText: TextView
private lateinit var statusText2: TextView
/** 焦点高亮背景:获得焦点→蓝色,普通→深灰 */ /** 焦点高亮背景:获得焦点→蓝色,普通→深灰 */
private fun focusBg(normal: Int = 0xFF2A2F3A.toInt(), focused: Int = 0xFF1B6EF3.toInt()) private fun focusBg(normal: Int = 0xFF2A2F3A.toInt(), focused: Int = 0xFF1B6EF3.toInt())
@@ -154,6 +155,25 @@ class SettingsActivity : Activity() {
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 24 }) ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 24 })
// ===== 安装统计 & 版本更新 =====
root.addView(TextView(this).apply {
text = "版本更新"
textSize = 15f; setTextColor(Color.parseColor("#7AA7D9"))
setPadding(0, 8, 0, 8)
})
statusText2 = TextView(this).apply {
textSize = 15f; setLineSpacing(0f, 1.15f)
setTextColor(Color.WHITE); setBackgroundColor(Color.parseColor("#1C2028"))
setPadding(24, 20, 24, 20)
text = "点击右侧按钮检查是否有新版本\n(安装统计会在启动时自动上报)"
}
root.addView(statusText2, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 12 })
val checkBtn = mkAction("检查更新") { doCheckUpdate() }
root.addView(checkBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 40 })
// ===== 卡密激活 ===== // ===== 卡密激活 =====
root.addView(TextView(this).apply { root.addView(TextView(this).apply {
text = "卡密激活" text = "卡密激活"
@@ -183,15 +203,64 @@ class SettingsActivity : Activity() {
root.addView(TextView(this).apply { root.addView(TextView(this).apply {
text = "✓ 已经是会员" text = "✓ 已经是会员"
textSize = 18f; setTextColor(Color.parseColor("#4CAF50")) textSize = 18f; setTextColor(Color.parseColor("#4CAF50"))
gravity = Gravity.CENTER; setPadding(0, 24, 0, 24) gravity = Gravity.CENTER; setPadding(0, 24, 0, 12)
}) })
// ★ 新增:撤销本机授权(换机 / 换卡密前先解绑)
val revokeBtn = mkAction("撤销本机授权(可重新激活 / 换卡密)") { doRevoke() }
root.addView(revokeBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 20 })
} else { } else {
val btn = mkAction("支付成为会员(月/季/年)") { val btn = mkAction("支付成为会员(月/季/年)") {
startActivity(Intent(this@SettingsActivity, ShopActivity::class.java)) startActivity(Intent(this@SettingsActivity, ShopActivity::class.java))
} }
root.addView(btn, LinearLayout.LayoutParams( root.addView(btn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)) ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 20 })
} }
// ===== 其它操作 =====
root.addView(TextView(this).apply {
text = "其它操作"
textSize = 15f; setTextColor(Color.parseColor("#7AA7D9"))
setPadding(0, 8, 0, 8)
})
// 原菜单键的功能(手动换线),现在放在这里
val switchBtn = mkAction("切换线路(当前线路不通时手动换)") {
try {
getSharedPreferences("iptv_main", MODE_PRIVATE).edit()
.putString("pending_action", "switch_line").apply()
} catch (e: Exception) { }
statusText.text = "已请求切换线路,返回主界面后生效"
android.widget.Toast.makeText(this, "返回主界面后自动切换线路", android.widget.Toast.LENGTH_LONG).show()
try { finish() } catch (e: Exception) { }
}
root.addView(switchBtn, LinearLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT).apply { bottomMargin = 20 })
// ★ 诊断标记:证明本页 onCreate 确实跑到了(主界面 1.4 秒后会核对)
try {
getSharedPreferences("iptv_main", MODE_PRIVATE).edit()
.putLong("settings_opened_at", System.currentTimeMillis()).apply()
} catch (e: Exception) { }
}
/** 撤销本机授权:清除本地授权信息 → 恢复免费模式,可重新输入卡密或换机 */
private fun doRevoke() {
try {
getSharedPreferences("iptv_license", MODE_PRIVATE).edit()
.putBoolean("is_vip", false)
.putString("card_key", "")
.putString("vip_expire", "")
.putBoolean("is_permanent", false)
.remove("token")
.apply()
} catch (e: Exception) { }
statusText.text = "✓ 已撤销本机授权\n当前为免费用户(每天 1 小时)\n可在下方重新输入卡密激活"
android.widget.Toast.makeText(this, "已撤销授权,可重新激活", android.widget.Toast.LENGTH_LONG).show()
// 重开本页以刷新界面状态(会员按钮 ↔ 支付按钮)
try {
startActivity(Intent(this@SettingsActivity, SettingsActivity::class.java))
finish()
} catch (e: Exception) { }
} }
/** 输入卡密激活 */ /** 输入卡密激活 */
@@ -224,6 +293,33 @@ class SettingsActivity : Activity() {
}.start() }.start()
} }
/** 检查新版本(安装登记 + 在线上报 会一并完成) */
private fun doCheckUpdate() {
statusText2.text = "正在检查…"
Thread {
val mid = LicenseClient.machineCode(this)
val card = getSharedPreferences("iptv_license", MODE_PRIVATE).getString("card_key", "") ?: ""
val info = AuthApi.checkUpdate(mid, card, this)
runOnUiThread {
if (!info.ok) {
statusText2.text = "检查失败:${info.msg}"
return@runOnUiThread
}
val head = "安装上报成功 #${info.installId}\n当前 v${AuthApi.clientVersion(this@SettingsActivity)}"
statusText2.text = if (info.updateAvailable) {
"$head\n✅ 有新版本:v${info.latestVersion}" +
(if (info.changelog.isNotEmpty()) "\n${info.changelog}" else "")
} else {
"$head\n✅ 已是最新版本"
}
if (info.updateAvailable) {
android.widget.Toast.makeText(this@SettingsActivity,
"发现新版本 v${info.latestVersion},返回主界面下载", android.widget.Toast.LENGTH_LONG).show()
}
}
}.start()
}
private fun isBootReceiverEnabled(): Boolean = private fun isBootReceiverEnabled(): Boolean =
packageManager.getComponentEnabledSetting(ComponentName(this, BootReceiver::class.java)) == packageManager.getComponentEnabledSetting(ComponentName(this, BootReceiver::class.java)) ==
PackageManager.COMPONENT_ENABLED_STATE_ENABLED PackageManager.COMPONENT_ENABLED_STATE_ENABLED