Lie*_*yan 234
您可以轻松启动市场链接或安装提示:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("content:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
Run Code Online (Sandbox Code Playgroud)
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.package.name"));
startActivity(goToMarket);
Run Code Online (Sandbox Code Playgroud)
但是,如果没有用户的明确许可,您无法安装.apks ; 除非设备和您的程序已植根.
Hor*_*man 56
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);
Run Code Online (Sandbox Code Playgroud)
我遇到了同样的问题,经过多次尝试,这种方式对我有用.我不知道为什么,但设置数据和类型分别搞砸了我的意图.
Ali*_*Nem 37
提供给该问题的解决方案均适用于targetSdkVersion23及以下的s.但是,对于Android N,即API级别24及更高版本,它们不起作用并且崩溃时出现以下异常:
android.os.FileUriExposedException: file:///storage/emulated/0/... exposed beyond app through Intent.getData()
Run Code Online (Sandbox Code Playgroud)
这是因为从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
Run Code Online (Sandbox Code Playgroud)
为了API 24及以上.
关于这方面的更多细节可以在这里找到,我不打算通过它.
要回答这个问题的targetSdkVersion的24以上,就必须遵循以下步骤:将以下内容添加到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>
Run Code Online (Sandbox Code Playgroud)
2.将以下paths.xml文件添加到src,main中的xml文件夹res:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="pathName"
path="pathValue"/>
</paths>
Run Code Online (Sandbox Code Playgroud)
这pathName是在上面的示例性内容uri示例中示出的并且pathValue是系统上的实际路径.放一个"."是个好主意.(如果您不想添加任何额外的子目录,请在上面的pathValue中使用(不带引号).
编写以下代码以appName.apk在主外部文件系统上安装名称为apk的apk :
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();
Run Code Online (Sandbox Code Playgroud)在外部文件系统上写入您自己的应用程序的私人目录时,也不需要权限.
我在这里编写了一个AutoUpdate库,其中我使用了上述内容.
Alk*_*san 29
好吧,我深入挖掘,并从Android Source找到了PackageInstaller应用程序的来源.
https://github.com/android/platform_packages_apps_packageinstaller
从清单我发现它需要许可:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
Run Code Online (Sandbox Code Playgroud)
确认后会发生实际的安装过程
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);
Run Code Online (Sandbox Code Playgroud)
小智 21
我只是想分享我的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);
Run Code Online (Sandbox Code Playgroud)
小智 10
在 Android Oreo 及以上版本中,我们必须采用不同的方法以编程方式安装 apk。
private void installApkProgramatically() {
try {
File path = activity.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
File file = new File(path, filename);
Uri uri;
if (file.exists()) {
Intent unKnownSourceIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName())));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!activity.getPackageManager().canRequestPackageInstalls()) {
startActivityForResult(unKnownSourceIntent, Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE);
} else {
Uri fileUri = FileProvider.getUriForFile(activity.getBaseContext(), activity.getApplicationContext().getPackageName() + ".provider", 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);
startActivity(intent);
alertDialog.dismiss();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
Intent intent1 = new Intent(Intent.ACTION_INSTALL_PACKAGE);
uri = FileProvider.getUriForFile(activity.getApplicationContext(), BuildConfig.APPLICATION_ID + ".provider", file);
activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_READ_URI_PERMISSION);
activity.grantUriPermission("com.abcd.xyz", uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
intent1.setDataAndType(uri,
"application/*");
intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent1.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent1.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
startActivity(intent1);
} else {
Intent intent = new Intent(Intent.ACTION_VIEW);
uri = Uri.fromFile(file);
intent.setDataAndType(uri,
"application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
} else {
Log.i(TAG, " file " + file.getPath() + " does not exist");
}
} catch (Exception e) {
Log.i(TAG, "" + e.getMessage());
}
}
Run Code Online (Sandbox Code Playgroud)
在Oreo及以上版本中我们需要未知资源安装权限。所以在活动结果中你必须检查结果的权限
@Override
public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE:
switch (resultCode) {
case Activity.RESULT_OK:
installApkProgramatically();
break;
case Activity.RESULT_CANCELED:
//unknown resouce installation cancelled
break;
}
break;
}
}
Run Code Online (Sandbox Code Playgroud)
这可以帮助别人很多!
第一:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
第二:对于android 7及更高版本,您应该在清单中定义一个提供者,如下所示!
<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>
Run Code Online (Sandbox Code Playgroud)
第三:在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>
Run Code Online (Sandbox Code Playgroud)
第四:您应该在清单中添加此权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
Run Code Online (Sandbox Code Playgroud)
允许应用程序请求安装软件包。定位到大于25的API的应用必须拥有此权限才能使用Intent.ACTION_INSTALL_PACKAGE。
请确保提供者的权限相同!
不要忘记请求权限:
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
android.Manifest.permission.READ_EXTERNAL_STORAGE
Run Code Online (Sandbox Code Playgroud)
在 AndroidManifest.xml 中添加提供者和权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
...
<application>
...
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="${applicationId}"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
</application>
Run Code Online (Sandbox Code Playgroud)
创建 XML 文件提供程序 res/xml/provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path
name="external"
path="." />
<external-files-path
name="external_files"
path="." />
<cache-path
name="cache"
path="." />
<external-cache-path
name="external_cache"
path="." />
<files-path
name="files"
path="." />
</paths>
Run Code Online (Sandbox Code Playgroud)
使用以下示例代码:
public class InstallManagerApk extends AppCompatActivity {
static final String NAME_APK_FILE = "some.apk";
public static final int REQUEST_INSTALL = 0;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// required permission:
// android.Manifest.permission.WRITE_EXTERNAL_STORAGE
// android.Manifest.permission.READ_EXTERNAL_STORAGE
installApk();
}
...
/**
* Install APK File
*/
private void installApk() {
try {
File filePath = Environment.getExternalStorageDirectory();// path to file apk
File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);
Uri uri = getApkUri( file.getPath() ); // get Uri for each SDK Android
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( uri );
intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);
if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity
startActivityForResult(intent, REQUEST_INSTALL);
} else {
throw new Exception("don`t start Activity.");
}
} catch ( Exception e ) {
Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
.show();
}
}
/**
* Returns a Uri pointing to the APK to install.
*/
private Uri getApkUri(String path) {
// Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
// Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
// recommended.
boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;
String tempFilename = "tmp.apk";
byte[] buffer = new byte[16384];
int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
try (InputStream is = new FileInputStream(new File(path));
FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {
int n;
while ((n = is.read(buffer)) >= 0) {
fout.write(buffer, 0, n);
}
} catch (IOException e) {
Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
}
if (useFileProvider) {
File toInstall = new File(this.getFilesDir(), tempFilename);
return FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID, toInstall);
} else {
return Uri.fromFile(getFileStreamPath(tempFilename));
}
}
/**
* Listener event on installation APK file
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == REQUEST_INSTALL) {
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
} else if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
}
}
}
...
}
Run Code Online (Sandbox Code Playgroud)
不需要硬编码接收应用程序的另一种解决方案,因此更安全:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( Uri.fromFile(new File(pathToApk)) );
startActivity(intent);
Run Code Online (Sandbox Code Playgroud)
大约两个月前来到这里,据说已经弄清楚了。今天回来了,却一头雾水。据我所知,我的设置没有任何改变,所以显然过去我想出的任何东西对于现在的我来说都不够强大。我终于设法让某些东西再次工作,因此在这里将其记录下来,以供将来的我和其他可能从另一次尝试中受益的人使用。
此尝试代表原始 Android Java Install APK - Session API示例的直接 Xamarin C# 翻译。它可能需要一些额外的工作,但这至少是一个开始。我让它在 Android 9 设备上运行,尽管我有一个针对 Android 11 的项目。
安装ApkSessionApi.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;
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
我特别喜欢这种方法的是,它不需要在清单中进行任何特殊工作 - 不需要广播接收器、文件提供程序等。当然,这将应用程序资产中的某些 APK 作为其来源,而更有用的系统可能会使用一些给定的 APK 路径。我想这会带来一定程度的额外复杂性。此外,在 Android 处理完流之前,我从未遇到过 Xamarin GC 关闭流的任何问题(至少据我所知)。我也没有遇到任何未解析 APK 的问题。我确保使用签名的 APK(部署到设备时由 Visual Studio 生成的 APK 工作得很好),而且我再次没有遇到任何文件访问权限问题,仅仅是因为在此示例中使用了应用程序资产中的 APK 。
这里的其他一些答案提供的一件事是使侧面加载权限授予更加简化的想法。Yabaze Cool 的答案提供了这个功能:
Run Code Online (Sandbox Code Playgroud)Intent unKnownSourceIntent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName()))); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { if (!activity.getPackageManager().canRequestPackageInstalls()) { startActivityForResult(unKnownSourceIntent, Constant.UNKNOWN_RESOURCE_INTENT_REQUEST_CODE); ...
当我测试翻译时,我卸载了启动器演示及其安装的应用程序。没有提供检查来canRequestPackageInstalls使其达到我必须手动按下附加设置按钮才能将我带到与ACTION_MANAGE_UNKNOWN_APP_SOURCES上述意图相同的对话框的位置。因此,添加此逻辑有助于在一定程度上简化用户的安装过程。
| 归档时间: |
|
| 查看次数: |
168659 次 |
| 最近记录: |