Update UpdateManager.kt

This commit is contained in:
MNCHL 2023-12-27 14:29:08 +08:00 committed by GitHub
parent 308963d0da
commit ee31ec923c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,101 +1,113 @@
package org.yuzu.yuzu_emu package org.yuzu.yuzu_emu
import android.app.AlertDialog
import android.app.DownloadManager import android.app.DownloadManager
import android.content.* import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri import android.net.Uri
import android.os.Bundle
import android.os.Environment import android.os.Environment
import android.util.Log import android.provider.Settings
import android.widget.Toast import android.widget.Toast
import androidx.appcompat.app.AlertDialog import kotlinx.coroutines.Dispatchers
import androidx.core.content.FileProvider import kotlinx.coroutines.GlobalScope
import androidx.appcompat.app.AppCompatActivity import kotlinx.coroutines.launch
import kotlinx.coroutines.* import org.json.JSONException
import okhttp3.*
import org.json.JSONObject import org.json.JSONObject
import java.io.File import java.io.BufferedReader
import java.io.IOException import java.io.IOException
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
class MainActivity : AppCompatActivity() { class UpdateManager(private val context: Context) {
override fun onCreate(savedInstanceState: Bundle?) { private companion object {
super.onCreate(savedInstanceState) private const val CONFIG_URL = "https://your-server.com/api/config"
setContentView(R.layout.activity_main)
val downloadUrl = "http://mkoc.cn/app/yuzu163.apk"
UpdateManager.checkAndInstallUpdate(this, downloadUrl)
} }
}
object UpdateManager { fun checkForUpdates() {
private val client = OkHttpClient()
fun checkAndInstallUpdate(context: Context, downloadUrl: String) {
GlobalScope.launch(Dispatchers.IO) { GlobalScope.launch(Dispatchers.IO) {
val currentVersionName = context.packageManager try {
.getPackageInfo(context.packageName, 0).versionName val configJson = fetchConfigFromServer(CONFIG_URL)
val latestVersionName = getLatestVersionNameFromServer() if (configJson != null) {
val jsonObject = JSONObject(configJson)
val updateDialogTitle = jsonObject.optString("updateDialogTitle")
val updateDialogMessage = jsonObject.optString("updateDialogMessage")
val versionName = jsonObject.optString("versionName")
val downloadUrl = jsonObject.optString("downloadUrl")
withContext(Dispatchers.Main) { if (isNewVersionAvailable(versionName)) {
if (isNewVersionAvailable(currentVersionName, latestVersionName)) { showUpdateDialog(updateDialogTitle, updateDialogMessage, downloadUrl)
showUpdateDialog(context, downloadUrl) } else {
showUpdateAvailableMessage(context) showNoUpdateAvailableMessage()
}
} else { } else {
showNoUpdateAvailableMessage(context) showErrorToast()
} }
} catch (e: Exception) {
showErrorToast()
} }
} }
} }
private suspend fun getLatestVersionNameFromServer(): String { private fun fetchConfigFromServer(urlString: String): String? {
val request = Request.Builder() var connection: HttpURLConnection? = null
.url("http://mkoc.cn/aip/version.php") var reader: BufferedReader? = null
.build()
return try { return try {
val response: Response = client.newCall(request).execute() val url = URL(urlString)
val responseBody = response.body?.string() connection = url.openConnection() as HttpURLConnection
connection.requestMethod = "GET"
connection.connect()
if (responseBody != null) { if (connection.responseCode == HttpURLConnection.HTTP_OK) {
val jsonObject = JSONObject(responseBody) reader = BufferedReader(InputStreamReader(connection.inputStream))
jsonObject.getString("versionName") val stringBuilder = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
stringBuilder.append(line).append("\n")
}
stringBuilder.toString()
} else { } else {
"" null
} }
} catch (e: IOException) { } finally {
Log.e("UpdateManager", "Error checking for updates: ${e.message}") reader?.close()
"" connection?.disconnect()
} }
} }
private fun isNewVersionAvailable(currentVersion: String, latestVersion: String): Boolean { private fun isNewVersionAvailable(serverVersionName: String): Boolean {
return latestVersion.compareTo(currentVersion) > 0 try {
val currentVersionName = context.packageManager
.getPackageInfo(context.packageName, 0).versionName
return serverVersionName.compareTo(currentVersionName) > 0
} catch (e: PackageManager.NameNotFoundException) {
return false
}
} }
private fun showUpdateDialog(context: Context, downloadUrl: String) { private fun showUpdateDialog(title: String, message: String, downloadUrl: String) {
AlertDialog.Builder(context) AlertDialog.Builder(context)
.setTitle("发现新版本") .setTitle(title)
.setMessage("有新版本可用,是否立即更新?") .setMessage(message)
.setPositiveButton("更新") { dialog, which -> .setPositiveButton("更新") { dialog, which ->
// 开始下载新版本 downloadLatestVersion(downloadUrl)
downloadLatestVersion(context, downloadUrl)
}
.setNegativeButton("稍后") { dialog, which ->
// 稍后处理更新操作
} }
.setNegativeButton("稍后", null)
.show() .show()
} }
private fun showUpdateAvailableMessage(context: Context) { private fun showNoUpdateAvailableMessage() {
Toast.makeText(context, "发现新版本,请及时更新。", Toast.LENGTH_LONG).show()
}
private fun showNoUpdateAvailableMessage(context: Context) {
Toast.makeText(context, "您的应用已经是最新版本。", Toast.LENGTH_SHORT).show() Toast.makeText(context, "您的应用已经是最新版本。", Toast.LENGTH_SHORT).show()
} }
private fun downloadLatestVersion(context: Context, downloadUrl: String) { private fun showErrorToast() {
Toast.makeText(context, "无法获取配置信息", Toast.LENGTH_SHORT).show()
}
private fun downloadLatestVersion(downloadUrl: String) {
val request = DownloadManager.Request(Uri.parse(downloadUrl)) val request = DownloadManager.Request(Uri.parse(downloadUrl))
.setTitle("应用更新") .setTitle("应用更新")
.setDescription("正在下载新版本") .setDescription("正在下载新版本")
@ -107,41 +119,33 @@ object UpdateManager {
val downloadManager = val downloadManager =
context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
downloadManager.enqueue(request)
val onCompleteReceiver = object : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
installLatestVersion(context)
context?.unregisterReceiver(this)
}
}
val intentFilter = IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
context.registerReceiver(onCompleteReceiver, intentFilter)
val downloadId = downloadManager.enqueue(request)
} }
private fun installLatestVersion(context: Context?) { fun installLatestVersion(downloadId: Long) {
val downloadManager = val downloadManager =
context?.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
val query = DownloadManager.Query().apply { val query = DownloadManager.Query().apply {
setFilterByStatus(DownloadManager.STATUS_SUCCESSFUL) setFilterById(downloadId)
} }
val cursor = downloadManager.query(query) val cursor = downloadManager.query(query)
if (cursor.moveToFirst()) { if (cursor.moveToFirst()) {
val apkUri = FileProvider.getUriForFile( val status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS))
context, if (status == DownloadManager.STATUS_SUCCESSFUL) {
context.packageName + ".fileprovider", val uri = Uri.parse(
File(cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))) cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
) )
val intent = Intent(Intent.ACTION_VIEW).apply {
val installIntent = Intent(Intent.ACTION_INSTALL_PACKAGE).apply { setDataAndType(uri, "application/vnd.android.package-archive")
setDataAndType(apkUri, "application/vnd.android.package-archive") addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION) addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
}
context.startActivity(intent)
} else if (status == DownloadManager.STATUS_FAILED) {
showErrorToast()
} }
context.startActivity(installIntent)
} }
} }
} }