可以从自定义Android应用程序中以编程方式安装动态下载的apk。
当前回答
File file = new File(dir, "App.apk");
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
好吧,我深入挖掘,并从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);
大概两个月前,我发现了这个问题。今天回来了,一点头绪也没有。据我所知,我的设置没有任何改变,所以很明显,无论过去的我想到什么,对现在的我来说都不够强大。我终于设法让一些东西重新工作了,所以在这里记录它,以便将来的我和其他可能从另一次尝试中受益的人。
这一尝试代表了原始Android Java安装APK - Session API示例的直接Xamarin c#翻译。它可能需要一些额外的工作,但这至少是一个开始。我让它运行在Android 9设备上,尽管我的项目针对的是Android 11。
InstallApkSessionApi.cs
namespace LauncherDemo.Droid
{
using System;
using System.IO;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.OS;
using Android.Widget;
[Activity(Label = "InstallApkSessionApi", LaunchMode = LaunchMode.SingleTop)]
public class InstallApkSessionApi : Activity
{
private static readonly string PACKAGE_INSTALLED_ACTION =
"com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED";
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
this.SetContentView(Resource.Layout.install_apk_session_api);
// Watch for button clicks.
Button button = this.FindViewById<Button>(Resource.Id.install);
button.Click += this.Button_Click;
}
private void Button_Click(object sender, EventArgs e)
{
PackageInstaller.Session session = null;
try
{
PackageInstaller packageInstaller = this.PackageManager.PackageInstaller;
PackageInstaller.SessionParams @params = new PackageInstaller.SessionParams(
PackageInstallMode.FullInstall);
int sessionId = packageInstaller.CreateSession(@params);
session = packageInstaller.OpenSession(sessionId);
this.AddApkToInstallSession("HelloActivity.apk", session);
// Create an install status receiver.
Context context = this;
Intent intent = new Intent(context, typeof(InstallApkSessionApi));
intent.SetAction(PACKAGE_INSTALLED_ACTION);
PendingIntent pendingIntent = PendingIntent.GetActivity(context, 0, intent, 0);
IntentSender statusReceiver = pendingIntent.IntentSender;
// Commit the session (this will start the installation workflow).
session.Commit(statusReceiver);
}
catch (IOException ex)
{
throw new InvalidOperationException("Couldn't install package", ex);
}
catch
{
if (session != null)
{
session.Abandon();
}
throw;
}
}
private void AddApkToInstallSession(string assetName, PackageInstaller.Session session)
{
// It's recommended to pass the file size to openWrite(). Otherwise installation may fail
// if the disk is almost full.
using Stream packageInSession = session.OpenWrite("package", 0, -1);
using Stream @is = this.Assets.Open(assetName);
byte[] buffer = new byte[16384];
int n;
while ((n = @is.Read(buffer)) > 0)
{
packageInSession.Write(buffer, 0, n);
}
}
// Note: this Activity must run in singleTop launchMode for it to be able to receive the intent
// in onNewIntent().
protected override void OnNewIntent(Intent intent)
{
Bundle extras = intent.Extras;
if (PACKAGE_INSTALLED_ACTION.Equals(intent.Action))
{
PackageInstallStatus status = (PackageInstallStatus)extras.GetInt(PackageInstaller.ExtraStatus);
string message = extras.GetString(PackageInstaller.ExtraStatusMessage);
switch (status)
{
case PackageInstallStatus.PendingUserAction:
// This test app isn't privileged, so the user has to confirm the install.
Intent confirmIntent = (Intent) extras.Get(Intent.ExtraIntent);
this.StartActivity(confirmIntent);
break;
case PackageInstallStatus.Success:
Toast.MakeText(this, "Install succeeded!", ToastLength.Short).Show();
break;
case PackageInstallStatus.Failure:
case PackageInstallStatus.FailureAborted:
case PackageInstallStatus.FailureBlocked:
case PackageInstallStatus.FailureConflict:
case PackageInstallStatus.FailureIncompatible:
case PackageInstallStatus.FailureInvalid:
case PackageInstallStatus.FailureStorage:
Toast.MakeText(this, "Install failed! " + status + ", " + message,
ToastLength.Short).Show();
break;
default:
Toast.MakeText(this, "Unrecognized status received from installer: " + status,
ToastLength.Short).Show();
break;
}
}
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.launcherdemo" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="30" />
<application android:label="LauncherDemo.Android" android:theme="@style/MainTheme" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
</manifest>
What I particularly like about this approach is that it does not require any special work in the manifest - no broadcast receivers, file providers, etc. Granted, this takes as its source some APK in the app's assets, whereas a more useful system will probably use some given APK path. I imagine that will introduce a certain level of additional complexity. In addition, I never ran into any issues here (at least as far as I could tell) with the Xamarin GC closing streams before Android was done with them. Nor did I have any issues with the APK not being parsed. I made sure to use a signed APK (the one generated by Visual Studio when deploying to the device worked just fine), and again I did not run into any file access permission issues simply due to using an APK from the app's assets in this example.
这里的一些其他答案提供的一件事是使侧面加载许可授予更加简化的想法。Yabaze Cool的回答提供了如下特色:
Intent unKnownSourceIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES). setdata (Uri.parse(字符串。格式(“包:% s activity.getPackageName ()))); 如果(Build.VERSION。SDK_INT >= Build.VERSION_CODES.O) { if (!activity.getPackageManager(). canrequestpackageinstaller ()) { startActivityForResult (unKnownSourceIntent Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE); ...
当我测试我的翻译时,我卸载了启动器演示程序和它安装的应用程序。没有向canrequestpackageinstalled提供检查,导致我不得不手动按下一个额外的设置按钮,将我带到与上面的ACTION_MANAGE_UNKNOWN_APP_SOURCES意图相同的对话框。因此,添加这个逻辑可以帮助在一定程度上简化用户的安装过程。
基于@ 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) { }
这可以帮助别人很多!
第一:
private static final String APP_DIR = Environment.getExternalStorageDirectory().getAbsolutePath() + "/MyAppFolderInStorage/";
private void install() {
File file = new File(APP_DIR + fileName);
if (file.exists()) {
Intent intent = new Intent(Intent.ACTION_VIEW);
String type = "application/vnd.android.package-archive";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Uri downloadedApk = FileProvider.getUriForFile(getContext(), "ir.greencode", file);
intent.setDataAndType(downloadedApk, type);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
} else {
intent.setDataAndType(Uri.fromFile(file), type);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
getContext().startActivity(intent);
} else {
Toast.makeText(getContext(), "ّFile not found!", Toast.LENGTH_SHORT).show();
}
}
第二:对于android 7及以上,你应该在manifest中定义一个提供商,如下所示!
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="ir.greencode"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths" />
</provider>
第三:在res/xml文件夹中定义path.xml,如下所示! 我使用这个路径内部存储,如果你想改变它的东西有一些方法!你可以进入这个链接: FileProvider
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="your_folder_name" path="MyAppFolderInStorage/"/>
</paths>
第四:您应该在manifest中添加此权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
允许应用程序请求安装包。针对api大于25的应用程序必须拥有此权限才能使用Intent.ACTION_INSTALL_PACKAGE。 请确保提供者权限相同!
推荐文章
- getDefaultSharedPreferences和getSharedPreferences的区别
- 如何模拟按钮点击使用代码?
- Android Webview给出net::ERR_CACHE_MISS消息
- Parcelable遇到IOException写入序列化对象getactivity()
- 如何在Android中动态更改菜单项文本
- 如何将Base64字符串转换为位图图像,以显示在一个ImageView?
- 新版本的Android模拟器问题-模拟器进程已终止
- 没有与请求版本匹配的NDK版本
- 如何将一个颜色整数转换为十六进制字符串在Android?
- 格式浮动到小数点后n位
- 移除一个onclick监听器
- 如何圆形图像与滑翔图书馆?
- 测试者从哪里下载谷歌Play Android应用?
- Android Studio在创建新项目时卡住了Gradle下载
- 我如何让拨号打开与电话号码显示?