在Android上以编程方式安装应用程序
我很想知道是否可以通过编程方式从自定义Android应用程序安装动态下载的apk。是的,这是可能的。但是,你需要手机安装未经验证的来源。例如,slideMe就是这样做的。我认为你能做的最好的事情是检查应用程序是否存在,并向Android市场发送意向。你应该使用android Market的url方案在Android上以编程方式安装应用程序,android,apk,Android,Apk,我很想知道是否可以通过编程方式从自定义Android应用程序安装动态下载的apk。是的,这是可能的。但是,你需要手机安装未经验证的来源。例如,slideMe就是这样做的。我认为你能做的最好的事情是检查应用程序是否存在,并向Android市场发送意向。你应该使用android Market的url方案 market://details?id=package.name 我不知道如何开始活动,但如果你用那种url开始活动。它将打开android market,让您可以选择安装应用程序。您可以轻松启动
market://details?id=package.name
我不知道如何开始活动,但如果你用那种url开始活动。它将打开android market,让您可以选择安装应用程序。您可以轻松启动market链接或安装提示:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
但是,未经用户明确许可,您无法安装.apks;除非设备和你的程序是根目录的。好吧,我深入挖掘,从Android源代码中找到了PackageInstaller应用程序的源代码 从清单中,我发现它需要许可:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<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>
我也有同样的问题,经过几次尝试后,我的结果是这样的。我不知道为什么,但分别设置数据和类型会破坏我的意图 只是一个扩展,如果有人需要一个库,那么可能会有所帮助。感谢为Android提供了一个API,用于从另一个应用程序内部安装APK软件包。
你可以在线定义你的更新,并将API集成到你的应用程序中——就是这样。
目前API处于测试状态,但您已经可以自己进行一些测试了。
除此之外,UpdateNode还提供了通过系统显示消息的功能——如果您想告诉用户一些重要的信息,这非常有用。
我是客户端开发团队的一员,并且至少在为我自己的Android应用程序使用消息功能
值得注意的是,如果您使用
下载管理器开始下载,请确保将其保存到外部位置,例如setdestinationnexternalfilesdir(c,null,“).apk”代码>。包存档类型的意图似乎不喜欢下载到内部位置时使用的内容:
方案,但喜欢文件:
。(尝试将内部路径包装到文件对象中,然后获取路径也不起作用,即使它会导致文件:
url,因为应用程序不会解析apk;看起来它必须是外部路径。)
例如:
int uriIndex = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
String downloadedPackageUriString = cursor.getString(uriIndex);
File mFile = new File(Uri.parse(downloadedPackageUriString).getPath());
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.fromFile(mFile), "application/vnd.android.package-archive")
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
appContext.startActivity(promptInstall);
我只想告诉大家,我的apk文件已保存到我的应用程序“Data”目录中,我需要将apk文件的权限更改为世界可读,以便以这种方式安装,否则系统会抛出“Parse error:解析包时出现问题”;因此,使用@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);
另一种解决方案不需要硬编码接收应用程序,因此更安全:
Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
intent.setData( Uri.fromFile(new File(pathToApk)) );
startActivity(intent);
试试这个
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);
试试这个
-在舱单上写入:
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);
针对此问题提供的解决方案均适用于23岁及以下的targetSdkVersion
s。但是,对于Android N,即API级别24及更高版本,它们不工作且崩溃,但以下情况除外:
android.os.FileUriExposedException: file:///storage/emulated/0/... exposed beyond app through Intent.getData()
这是因为从Android 24开始,用于寻址下载文件的Uri
发生了变化。例如,使用包名com.example.test
存储在应用程序的主外部文件系统上的名为appName.apk
的安装文件如下
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>
路径名
如上述示例性内容uri示例所示,而路径值
是系统上的实际路径。
如果不想添加任何额外的子目录,最好在上面的pathValue中加上“.”(不带引号)
编写以下代码,在主外部文件系统上安装名为appName.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();
在外部文件系统上写入自己应用程序的私有目录时,也不需要任何权限
我已经编写了一个自动更新库,其中使用了上述内容。首先将以下行添加到AndroidManifest.xml中:
<uses-permission android:name="android.permission.INSTALL_PACKAGES"
tools:ignore="ProtectedPermissions" />
这可以帮助别人很多
第一名:
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及以上版本,您应该在清单中定义一个提供者,如下所示
<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>
Third:在res/xml文件夹中定义path.xml,如下所示!
我正在使用这个路径作为内部存储,如果您想将其更改为其他内容,有几种方法!您可以转到以下链接:
Forth:您应该在清单中添加此权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
允许应用程序请求安装软件包。针对大于25的API的应用程序必须持有此权限才能使用Intent.ACTION\u INSTALL\u软件包
请确保提供商权限相同!
不要忘记请求权限:
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
android.Manifest.permission.READ_EXTERNAL_STORAGE
在AndroidManifest.xml中添加提供程序和权限:
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<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>
在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());
}
}
在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;
}
}
正如我所看到的,这个解决方案最接近事实:)。但这不适合我的情况。我需要动态加载器,取决于当前的用户环境,并走向市场-不是一个好的解决方案。
android.Manifest.permission.WRITE_EXTERNAL_STORAGE
android.Manifest.permission.READ_EXTERNAL_STORAGE
<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>
<?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>
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();
}
}
}
...
}
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());
}
}
@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;
}
}