可以从自定义Android应用程序中以编程方式安装动态下载的apk。
当前回答
基于@ uroovic podkrinik的回答。
通过APK安装应用程序对于不同版本的android可能有所不同(API级别21-30):
private var uri: Uri? = null
private var manager: DownloadManager? = null
private var file: File? = null
private var request: DownloadManager.Request? = null
private val REQUEST_WRITE_PERMISSION = 786
private val REQUEST_INSTALL_PACKAGE = 1234
private var receiver: BroadcastReceiver? = null
private var installIntent: Intent? = null
...
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val externalStorageDir = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
context?.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)
} else {
@Suppress("DEPRECATION")
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
}
val destination = "$externalStorageDir/Application.apk"
uri = Uri.parse("file://$destination")
file = File(destination)
file?.let { if (it.exists()) it.delete() }
request = DownloadManager.Request(Uri.parse("https://path_to_file/application.apk"))
request?.let {
it.setDescription("Update App")
it.setTitle("Application")
it.setDestinationUri(uri)
}
manager = context?.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
// for level android api >= 23 needs permission to write to external storage
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(context!!, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// here you can display the loading diagram
registerReceiver()
} else {
// request for permission to write to external storage
requestPermissions(
arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
REQUEST_WRITE_PERMISSION
)
}
} else {
// here you can display the loading diagram
registerReceiver()
}
}
创建并注册接收者:
private val onDownloadComplete = object : BroadcastReceiver() {
// install app when apk is loaded
override fun onReceive(ctxt: Context, intent: Intent) {
val mimeType = "application/vnd.android.package-archive"
receiver = this
try {
installIntent = Intent(Intent.ACTION_VIEW)
installIntent?.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
// for android api >= 24 requires FileProvider
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
installIntent?.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
val fileProviderURI = FileProvider.getUriForFile(
context!!,
context!!.applicationContext.packageName + ".provider",
file!!)
installIntent?.setDataAndType(fileProviderURI, mimeType)
// for android api >= 26 requires permission to install from APK in settings
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (context!!.applicationContext.packageManager.canRequestPackageInstalls()) {
installFromAPK()
} else goToSecuritySettings()
} else installFromAPK()
} else {
// for android api < 24 used file:// instead content://
// (no need to use FileProvider)
installIntent?.setDataAndType(uri, mimeType)
installFromAPK()
}
} catch (e: Exception) {
// view error message
}
}
}
private fun registerReceiver() {
manager!!.enqueue(request)
context?.registerReceiver(
onDownloadComplete,
IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE)
)
}
private fun installFromAPK() {
try {
startActivity(installIntent)
context?.unregisterReceiver(receiver)
activity?.finish()
} catch (e: Exception) {
// view error message
}
}
// go to settings for get permission install from APK
private fun goToSecuritySettings() {
val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(
Uri.parse(String.format(
"package:%s",
context!!.applicationContext.packageName
))
)
try {
startActivityForResult(intent, REQUEST_INSTALL_PACKAGE)
} catch (e: Exception) {
// view error message
}
}
拦截权限请求WRITE_EXTERNAL_STORAGE的结果:
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_WRITE_PERMISSION
&& grantResults.isNotEmpty()
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
try {
// here you can display the loading diagram
registerReceiver()
} catch (e: Exception) {
// view error message
}
}
}
在安全设置中拦截用户选择的结果:
@RequiresApi(api = Build.VERSION_CODES.O)
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (requestCode == REQUEST_INSTALL_PACKAGE
&& resultCode == AppCompatActivity.RESULT_OK) {
if (context!!.applicationContext.packageManager.canRequestPackageInstalls()) {
installFromAPK()
}
} else {
// view error message
}
}
添加到您的清单:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
<application...>
...
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths" />
</provider>
...
</application>
将provider_paths.xml文件添加到res/xml:
<?xml version="1.0" encoding="utf-8"?>
<paths>
<external-path name="external_files" path="."/>
</paths>
对于android API级别= 30,从安全设置返回不工作, 所以使用浏览器安装:
try {
val intent = Intent(Intent.ACTION_VIEW)
intent.data = Uri.parse("https://path_to_file/application.apk")
startActivity(intent)
activity?.finish()
} catch (e: ActivityNotFoundException) { }
其他回答
好吧,我深入挖掘,并从Android源代码中找到了PackageInstaller应用程序的源代码。
https://github.com/android/platform_packages_apps_packageinstaller
从manifest中我发现它需要许可:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
而实际安装过程发生在确认之后
Intent newIntent = new Intent();
newIntent.putExtra(PackageUtil.INTENT_ATTR_APPLICATION_INFO, mPkgInfo.applicationInfo);
newIntent.setData(mPackageURI);
newIntent.setClass(this, InstallAppProgress.class);
String installerPackageName = getIntent().getStringExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME);
if (installerPackageName != null) {
newIntent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, installerPackageName);
}
startActivity(newIntent);
您可以轻松启动市场链接或安装提示:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
源
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);
源
但是,没有用户的明确许可,你不能安装。apks;除非设备和您的程序已经扎根。
另一种解决方案不需要硬编码接收应用程序,因此更安全:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( Uri.fromFile(new File(pathToApk)) );
startActivity(intent);
我只是想分享一个事实,我的apk文件保存到我的应用程序“数据”目录,我需要更改apk文件的权限,使其成为世界可读的,以便允许它以这种方式安装,否则系统会抛出“解析错误:解析包存在问题”;所以使用@Horaceman的解决方案,使:
File file = new File(dir, "App.apk");
file.setReadable(true, false);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
startActivity(intent);
UpdateNode provides an API for Android to install APK packages from inside another App. You can just define your Update online and integrate the API into your App - that's it. Currently the API is in Beta state, but you can already do some tests yourself. Beside that, UpdateNode offers also displaying messages though the system - pretty useful if you want to tell something important to your users. I am part of the client dev team and am using at least the message functionality for my own Android App.
这里介绍了如何集成API
推荐文章
- Visual Studio代码- URI的目标不存在" package:flutter/material.dart "
- Tab在平板设备上不采用全宽度[使用android.support.design.widget.TabLayout]
- 我们应该用RecyclerView来代替ListView吗?
- App-release-unsigned.apk没有签名
- 如何在对话框中创建编辑文本框
- 在viewpager中获取当前Fragment实例
- 如何右对齐小部件在水平线性布局安卓?
- 如何创建EditText与十字(x)按钮在它的结束?
- 电话:用于文本输入的数字键盘
- 如何设置不透明度(Alpha)的视图在Android
- Flutter:升级游戏商店的版本代码
- Android构建脚本库:jcenter VS mavencentral
- Android -包名称约定
- 在Android上以编程方式安装应用程序
- 如何膨胀一个视图与布局