как скачать и установить APK файл по намерению? - PullRequest
1 голос
/ 10 октября 2019

Я делаю обновление моего приложения через собственный файловый сервер вместо Google Play-store. Тем не менее, это не работает хорошо. После подтверждения "обновить" файл APK загружен, он не открывается правильно. Пожалуйста, проверьте демонстрацию https://youtu.be/qDSGZ9fQ1Oo

class MainActivity : Activity() {
    private fun checkUpdate(){
        val jsonObjectRequest = JsonObjectRequest(
            Request.Method.GET,
            "https://myserver/release.json",
            null,
            Response.Listener { response ->
                if(response.getInt("version") > versionCode){
                    val builder = AlertDialog.Builder(this, R.style.Theme_AppCompat_Dialog_Alert)
                    builder.setTitle("Update to v" + response.getString("version") + " ?")
                    builder.setMessage(response.getString("note"))

                    builder.setPositiveButton("Yes") { _, _ ->
                        downloadUpdate(response.getString("version"))
                    }

                    builder.setNegativeButton("No") { _, _ ->
                        showUserInteraction()
                    }

                    builder.setCancelable(false)

                    builder.show()
                }else{
                    showUserInteraction()
                }
            },
            Response.ErrorListener{ _ ->
                showUserInteraction()
            }
        )

        requestQueue.add(jsonObjectRequest)
    }

    private fun downloadUpdate(versionCode: String) {
        registerReceiver(onDownloadComplete(), IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE))

        val request = DownloadManager
            .Request(Uri.parse("https://myserver/app-release.apk"))
            .setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE)
            .setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "myapp_v" + versionCode + ".apk")

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

    private class onDownloadComplete: BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val c = downloadManager.query(DownloadManager.Query().setFilterById(downloadId))
            if(c != null){
                c.moveToFirst()
                val fileUri = c.getString(c.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI))
                val mFile = File(Uri.parse(fileUri).path!!)
                val fileName = mFile.absolutePath

                context.unregisterReceiver(this)

                val intent = Intent(Intent.ACTION_VIEW)
                var contentUri: Uri
                if (SDK_VER >= Build.VERSION_CODES.N) {
                    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
                    contentUri = FileProvider.getUriForFile(context, BuildConfig.APPLICATION_ID + ".fileProvider", File(fileName))
                }else{
                    contentUri = Uri.fromFile(File(fileName))
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }

                intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
                startActivity(context, intent, null)
            }
        }
    }
}

Может ли кто-нибудь указать на мою ошибку? Спасибо.

1 Ответ

1 голос
/ 10 октября 2019

Вам необходимо добавить указанные ниже права доступа в файл manifest.xml .

Если приложение использует targetSdkLevel из 26 или вышеи предлагает пользователю установить другие приложения, файл манифеста должен включать разрешение REQUEST_INSTALL_PACKAGES:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />

Ниже приведена ссылка, почему это необходимо

  1. Link1
  2. Ссылка2
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...