在我的应用程序清单中,我已声明使用权限:
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Run Code Online (Sandbox Code Playgroud)
在我的代码中,我检查我的应用程序是否可以从未知来源安装:
public void reinstallApp(Activity activity, String pathname, int request_code)
{
if (activity.getPackageManager().canRequestPackageInstalls())
{
try
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(pathname)), "application/vnd.android.package-archive");
activity.startActivityForResult(intent, request_code);
}
catch (Exception e)
{
LogUtilities.show(this, e);
}
}
else
{
activity.startActivity(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", activity.getPackageName()))));
}
}
Run Code Online (Sandbox Code Playgroud)
但是"activity.getPackageManager().canRequestPackageInstalls()"总是返回"false",即使我在选择活动中检查来自unknow源的allow install.
有什么问题?
小智 13
你首先要求许可.为此,您需要调用来自未知来源的安装权限.我通过重新安排您的代码得到了答案.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
if (!getPackageManager().canRequestPackageInstalls()) {
startActivityForResult(new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES).setData(Uri.parse(String.format("package:%s", getPackageName()))), 1234);
} else {
callInstallProcess();
}
} else {
callInstallProcess();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码将在你的onCreate()中.您可以验证结果.
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1234 && resultCode == Activity.RESULT_OK) {
if (getPackageManager().canRequestPackageInstalls()) {
callInstallProcess();
}
} else {
//give the error
}
}
Run Code Online (Sandbox Code Playgroud)
您在callInstallProcess()中进行安装的位置;
try
{
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.fromFile(new File(pathname)), "application/vnd.android.package-archive");
activity.startActivityForResult(intent, request_code);
}
catch (Exception e)
{
LogUtilities.show(this, e);
}
Run Code Online (Sandbox Code Playgroud)
不要忘记在AndroidManifest.xml中授予权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Run Code Online (Sandbox Code Playgroud)
如此处所述,为了getPackageManager().canRequestPackageInstalls()正常工作,您必须声明此权限
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
Run Code Online (Sandbox Code Playgroud)
在您的 AndroidManifest.xml 中,正如您已经所做的那样,并且 - 最有可能是问题的原因 -在您的 build.gradle 或 AndroidManifest.xml 中声明targetSdkVersion为 26 或更高(换句话说,您的应用程序必须针对 Android Oreo 或多于)。
false否则,即使用户授予了权限,此方法也将始终返回。