Skip to content

Commit

Permalink
Fixed the app update crash bug and updated the README file
Browse files Browse the repository at this point in the history
-Removed ActivityResultLauncher related code to simplify the update process
- Optimized the ErrorScreen UI and removed unnecessary code
- Updated the multi-language README file and added descriptions of new features

修复app更新闪退bug,更新README文件
-移除了ActivityResultLauncher的相关代码,简化了更新流程
- 优化了ErrorScreen的UI,移除了不必要的代码
- 更新了多语言README文件,增加了新功能的描述

Signed-off-by: gohj99 <[email protected]>
  • Loading branch information
gohj99 committed Oct 5, 2024
1 parent ef80bb1 commit 742f944
Show file tree
Hide file tree
Showing 6 changed files with 118 additions and 97 deletions.
14 changes: 9 additions & 5 deletions README.ja-JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,16 @@ adb install Telewatch.apk

## 関数

- テキスト、写真、ビデオの表示またはダウンロード
- 写真やビデオを保存する
- 複数アカウント対応
- インターフェースのフォント調整
- 未読/既読インジケーター
- 接続状態インジケーター
- テキスト、画像、ビデオの閲覧またはダウンロード
- 画像やビデオの保存
- テキスト送信
- メッセージ処理の編集
- 削除メッセージの処理
- リューズの回転をサポート
- メッセージ編集処理
- メッセージ削除処理
- クラウンローテーションのサポート

## 最小構成と推奨構成

Expand Down
16 changes: 10 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,12 +39,16 @@ adb install Telewatch.apk

## Functions

- View or download text, pictures, and videos
- Save pictures or videos
- Send text
- Edit message processing
- Delete message processing
- Support crown rotation
- Multi-account support
- Interface font adjustment
- Unread/read indicator
- Connection status indicator
- Viewing or downloading text, images, and videos
- Saving images or videos
- Text messaging
- Message editing
- Message deletion
- Support for rotating the digital crown

## Minimum and recommended requirements

Expand Down
4 changes: 4 additions & 0 deletions README.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ adb install Telewatch.apk

## 功能

- 多账号支持
- 界面字体调节
- 未读/已读指示器
- 连接状态指示器
- 文字、图片、视频查看或下载
- 保存图片或视频
- 文字发送
Expand Down
4 changes: 4 additions & 0 deletions README.zh-TW.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ adb install Telewatch.apk

## 功能

- 多帳號支持
- 介面字體調節
- 未讀/已讀指示器
- 連線狀態指示器
- 文字、圖片、影片檢視或下載
- 儲存圖片或視頻
- 文字發送
Expand Down
173 changes: 91 additions & 82 deletions app/src/main/java/com/gohj99/telewatch/CheckUpdateActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,15 @@ package com.gohj99.telewatch
import android.app.DownloadManager
import android.content.Context
import android.content.Intent
import android.database.Cursor
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
Expand All @@ -38,6 +36,7 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
Expand Down Expand Up @@ -88,8 +87,6 @@ class CheckUpdateActivity : ComponentActivity() {
private const val REQUEST_CODE_UNKNOWN_APP = 1234
}

private lateinit var installApkLauncher: ActivityResultLauncher<Intent>

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)

Expand All @@ -99,31 +96,9 @@ class CheckUpdateActivity : ComponentActivity() {
}
}

// 检查 Android 版本,如果是 Android 10 及以上,注册 ActivityResultLauncher
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
registerInstallApkLauncher()
}

init()
}

private fun registerInstallApkLauncher() {
installApkLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) { result ->
if (result.resultCode == RESULT_OK) {
// 用户已授予安装未知来源应用的权限
installApk(fileName)
} else {
Toast.makeText(
this,
getString(R.string.unknown_apps_install_permission_denied),
Toast.LENGTH_SHORT
).show()
}
}
}

private fun init() {
lifecycleScope.launch(Dispatchers.IO) {
try {
Expand All @@ -149,34 +124,68 @@ class CheckUpdateActivity : ComponentActivity() {
val releaseInfo =
Gson().fromJson(responseData, ReleaseInfo::class.java)

val releaseType =
if (releaseInfo.prerelease) getString(R.string.pre_release) else getString(
R.string.release
)
val tagName = releaseInfo.tagName
val version = tagName.substring(1, 6)

val pInfo = packageManager.getPackageInfo(packageName, 0)
val localVersion = pInfo.versionName
val needsUpdate = compareVersions(version, localVersion)

val publishedAt = releaseInfo.publishedAt
val zonedDateTime = ZonedDateTime.parse(publishedAt)
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedPublishedAt = zonedDateTime.format(formatter)

val armAsset =
releaseInfo.assets.find { it.name.contains("arm.apk") }
val armDownloadUrl = armAsset?.browserDownloadUrl ?: ""

fileName = armDownloadUrl.substringAfterLast('/')

val needsUpdate = compareVersions(
releaseInfo.tagName.substring(1, 6),
packageManager.getPackageInfo(packageName, 0).versionName
)
val updateInfo = """
${getString(R.string.version)}: $version
${getString(R.string.Release_type)}: $releaseType
${getString(R.string.Release_time)}: $formattedPublishedAt
""".trimIndent()

if (needsUpdate) {
setContent {
TelewatchTheme {
var downloadProgress by remember { mutableStateOf(0f) }
var isDownloadComplete by remember {
mutableStateOf(
false
)
}

SplashUpdateView(
contentText = generateUpdateInfo(releaseInfo),
onDownloadClick = { startDownload(armDownloadUrl) },
downloadProgress = 0f,
onInstallClick = { installApk(fileName) },
isDownloadComplete = false
contentText = updateInfo,
onDownloadClick = {
startDownload(armDownloadUrl, { progress ->
downloadProgress = progress
}, {
isDownloadComplete = true
})
},
downloadProgress = downloadProgress,
onInstallClick = {
installApk(fileName)
},
isDownloadComplete = isDownloadComplete
)
}
}
} else {
setContent {
TelewatchTheme {
Box(
modifier = Modifier.fillMaxSize(),
modifier = Modifier
.fillMaxSize()
.fillMaxWidth(),
contentAlignment = Alignment.Center
) {
Text(
Expand Down Expand Up @@ -205,7 +214,11 @@ class CheckUpdateActivity : ComponentActivity() {
}
}

private fun startDownload(url: String) {
private fun startDownload(
url: String,
onProgress: (Float) -> Unit,
onDownloadComplete: () -> Unit
) {
val request = DownloadManager.Request(Uri.parse(url))
.setTitle("Downloading update")
.setDescription("Downloading the latest version of the app")
Expand All @@ -216,24 +229,52 @@ class CheckUpdateActivity : ComponentActivity() {

val downloadManager = getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
downloadId = downloadManager.enqueue(request)

val query = DownloadManager.Query().setFilterById(downloadId)

lifecycleScope.launch(Dispatchers.IO) {
var downloading = true
while (downloading) {
val cursor: Cursor = downloadManager.query(query)
if (cursor.moveToFirst()) {
val statusIndex = cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)
if (statusIndex >= 0) {
val status = cursor.getInt(statusIndex)
if (status == DownloadManager.STATUS_SUCCESSFUL) {
downloading = false
onProgress(1f)
launch(Dispatchers.Main) {
onDownloadComplete()
}
} else if (status == DownloadManager.STATUS_RUNNING) {
val totalIndex =
cursor.getColumnIndex(DownloadManager.COLUMN_TOTAL_SIZE_BYTES)
val downloadedIndex =
cursor.getColumnIndex(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR)
if (totalIndex >= 0 && downloadedIndex >= 0) {
val total = cursor.getLong(totalIndex)
if (total > 0) {
val downloaded = cursor.getLong(downloadedIndex)
val progress = downloaded.toFloat() / total.toFloat()
onProgress(progress)
}
}
}
}
}
cursor.close()
}
}
}

private fun installApk(fileName: String) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!packageManager.canRequestPackageInstalls()) {
// 请求用户授予安装未知来源应用的权限
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:$packageName")
}
installApkLauncher.launch(intent)
} else {
// Android 7.1 及以下版本使用 onActivityResult
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:$packageName")
}
startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP)
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).apply {
data = Uri.parse("package:$packageName")
}
startActivityForResult(intent, REQUEST_CODE_UNKNOWN_APP)
return
}
}
Expand All @@ -255,25 +296,10 @@ class CheckUpdateActivity : ComponentActivity() {
startActivity(intent)
}

@Deprecated("Deprecated in Android 14", ReplaceWith("ActivityResult API"))
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_CODE_UNKNOWN_APP) {
if (resultCode == RESULT_OK) {
installApk(fileName)
} else {
Toast.makeText(
this,
getString(R.string.unknown_apps_install_permission_denied),
Toast.LENGTH_SHORT
).show()
}
}
}

private fun compareVersions(version1: String, version2: String): Boolean {
val parts1 = version1.split(".")
val parts2 = version2.split(".")

for (i in 0..2) {
val num1 = parts1.getOrNull(i)?.toIntOrNull() ?: 0
val num2 = parts2.getOrNull(i)?.toIntOrNull() ?: 0
Expand All @@ -282,23 +308,6 @@ class CheckUpdateActivity : ComponentActivity() {
}
return false
}

private fun generateUpdateInfo(releaseInfo: ReleaseInfo): String {
val releaseType =
if (releaseInfo.prerelease) getString(R.string.pre_release) else getString(R.string.release)
val tagName = releaseInfo.tagName
val version = tagName.substring(1, 6)
val publishedAt = releaseInfo.publishedAt
val zonedDateTime = ZonedDateTime.parse(publishedAt)
val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
val formattedPublishedAt = zonedDateTime.format(formatter)

return """
${getString(R.string.version)}: $version
${getString(R.string.Release_type)}: $releaseType
${getString(R.string.Release_time)}: $formattedPublishedAt
""".trimIndent()
}
}

@Composable
Expand Down
4 changes: 0 additions & 4 deletions app/src/main/java/com/gohj99/telewatch/ui/main/ErrorScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.stringResource
Expand All @@ -31,9 +30,6 @@ import com.gohj99.telewatch.ui.theme.TelewatchTheme
@Composable
fun ErrorScreen(onRetry: () -> Unit, onSetting: () -> Unit = {}, cause: String = "") {
val scrollState = rememberScrollState()
LaunchedEffect(Unit) {
scrollState.scrollTo(80)
}

Column(
modifier = Modifier
Expand Down

0 comments on commit 742f944

Please sign in to comment.