可以从自定义Android应用程序中以编程方式安装动态下载的apk。
当前回答
为这个问题提供的解决方案都适用于23及以下的targetSdkVersion。然而,对于Android N,即API级别24及以上,它们不能工作并崩溃如下异常:
android.os.FileUriExposedException: file:///storage/emulated/0/... exposed beyond app through Intent.getData()
这是因为从Android 24开始,用于寻址下载文件的Uri已经改变。例如,一个名为appName.apk的安装文件存储在应用程序的主要外部文件系统上,包名为com.example.test
file:///storage/emulated/0/Android/data/com.example.test/files/appName.apk
适用于API 23及以下,而类似的
content://com.example.test.authorityStr/pathName/Android/data/com.example.test/files/appName.apk
适用于API 24或以上。
关于这方面的更多细节可以在这里找到,我不打算详细介绍。
要回答24及以上版本的targetSdkVersion的问题,必须遵循以下步骤: 将以下内容添加到AndroidManifest.xml:
<application
android:allowBackup="true"
android:label="@string/app_name">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}.authorityStr"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/paths"/>
</provider>
</application>
2. 将下面的paths.xml文件添加到src, main中的res的xml文件夹中:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="pathName"
path="pathValue"/>
</paths>
pathName是上面示例内容uri示例中显示的,pathValue是系统上的实际路径。 放个"。"是个好主意如果您不想添加任何额外的子目录,则为上面的pathValue(不带引号)。
Write the following code to install the apk with the name appName.apk on the primary external filesystem: File directory = context.getExternalFilesDir(null); File file = new File(directory, fileName); Uri fileUri = Uri.fromFile(file); if (Build.VERSION.SDK_INT >= 24) { fileUri = FileProvider.getUriForFile(context, context.getPackageName(), file); } Intent intent = new Intent(Intent.ACTION_VIEW, fileUri); intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true); intent.setDataAndType(fileUri, "application/vnd.android" + ".package-archive"); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity(intent); activity.finish();
在外部文件系统上写入自己应用程序的私有目录时,也不需要任何权限。
我在这里写了一个AutoUpdate库,我使用了上面的方法。
其他回答
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);
我也遇到过同样的问题,在尝试了几次之后,结果是这样的。我不知道为什么,但是分别设置数据和类型破坏了我的意图。
大概两个月前,我发现了这个问题。今天回来了,一点头绪也没有。据我所知,我的设置没有任何改变,所以很明显,无论过去的我想到什么,对现在的我来说都不够强大。我终于设法让一些东西重新工作了,所以在这里记录它,以便将来的我和其他可能从另一次尝试中受益的人。
这一尝试代表了原始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意图相同的对话框。因此,添加这个逻辑可以帮助在一定程度上简化用户的安装过程。
试试这个
String filePath = cursor.getString(cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME));
String title = filePath.substring( filePath.lastIndexOf('/')+1, filePath.length() );
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // without this flag android returned a intent error!
MainActivity.this.startActivity(intent);
是的,这是可能的。但要做到这一点,你需要在手机上安装未经验证的消息源。例如,slideMe就是这样做的。我认为你能做的最好的事情是检查应用程序是否存在,并向Android市场发送一个意图。你应该使用android市场的url方案。
market://details?id=package.name
我不知道如何启动这个活动但如果你用那种url启动一个活动。它应该打开android市场,给你安装应用程序的选择。
试试这个 -在舱单上填写:
uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions"
编写代码:
File sdCard = Environment.getExternalStorageDirectory();
String fileStr = sdCard.getAbsolutePath() + "/Download";// + "app-release.apk";
File file = new File(fileStr, "app-release.apk");
Intent promptInstall = new Intent(Intent.ACTION_VIEW).setDataAndType(Uri.fromFile(file),
"application/vnd.android.package-archive");
startActivity(promptInstall);
推荐文章
- 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上以编程方式安装应用程序
- 如何膨胀一个视图与布局