【发布时间】:2018-05-07 15:41:45
【问题描述】:
我在 /storage/emulated/0/Download/app-debug.apk 中有一个 APK 文件。 我想通过 FileProvider 安装这个文件,因为我使用的是 Android N。
当我尝试启动意图时,logcat 没有显示任何错误,但我在手机上收到以下消息:
解析包时出现问题。
我做错了什么?
MainActivity
public class MainActivity extends AppCompatActivity {
Button btnStartIntent;
String strRootPathInternalStorage = Environment.getExternalStorageDirectory().toString(); //-> /storage/emulated/0 //-> /storage/emulated/0/Download/
String strApkToInstall = "app-debug.apk";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*
--> Booooh bad way! <--
StrictMode.VmPolicy.Builder builder = new StrictMode.VmPolicy.Builder();
StrictMode.setVmPolicy(builder.build());
*/
btnStartIntent = (Button)findViewById(R.id.btnStartIntent);
btnStartIntent.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
installApk(MainActivity.this, strRootPathInternalStorage+"/Download/"+strApkToInstall);
}
});
}
public static void installApk(Context context, String apkPath) {
if (context == null || TextUtils.isEmpty(apkPath)) {
return;
}
File file = new File(apkPath);
Intent intent = new Intent(Intent.ACTION_VIEW);
if (Build.VERSION.SDK_INT >= 24) {
//provider authorities
Uri apkUri = FileProvider.getUriForFile(context, "com.spicysoftware.test.provider", file);
//Granting Temporary Permissions to a URI
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
} else {
intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
}
context.startActivity(intent);
}
}
清单
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<provider
android:name="android.support.v4.content.FileProvider"
android:authorities="com.spicysoftware.test.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="@xml/provider_paths"/>
</provider>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
provider_paths.xml
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="Download" path="Download" />
</paths>
【问题讨论】:
-
可能是您尝试安装的 apk 不是为 Android Nougat 制作的。查看 compileSDk、TargetSDK 和 minSDK 了解更多信息
-
感谢您的快速答复。 compileSDK 为 24,TargetSDK 为 24,minSDK24。所以这不应该是问题。
-
尝试使用您设备上的文件资源管理器应用安装。
-
这不是我的问题的解决方案。如果我想使用文件资源管理器应用程序,我不会尝试以编程方式进行。所以我认为唯一可以接受的方法是通过 Strictmode - VmPolicy
标签: android installation apk android-fileprovider