自从我将targetSdkVersion
更新为29以来,我遇到了很多麻烦,所以这个麻烦变成了下载-安装-更新我的应用程序。具有新版本的apk已成功下载(因为我是通过手机中的文件浏览器找到的),但我认为安装不正确。该过程完成后,屏幕似乎重新启动,因为它闪烁了,但是该应用程序未更新(我知道,因为在主屏幕上它显示了版本)。我的代码是:
public static boolean openFile(String intentAction) { // in this case it is Intent.ACTION_INSTALL_PACKAGE
try {
File file = new File(Environment.getExternalStorageDirectory().toString() + "/" + "myApp.apk");
if (file.exists()) {
Uri uri;
if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) {
uri = Uri.fromFile(file);
} else {
uri = FileProvider.getUriForFile(appContext, appContext.getPackageName() + ".provider", file);
}
return installPackage(file, uri);
}
} catch (Exception e) {
generateExceptionLog(e);
}
return false;
}
private static boolean installPackage(File file, Uri uri) {
PackageInstaller packageInstaller = appContext.getPackageManager().getPackageInstaller();
PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(PackageInstaller.SessionParams.MODE_FULL_INSTALL);
params.setAppPackageName(file.getAbsolutePath());
try {
int sessionId = packageInstaller.createSession(params);
PackageInstaller.Session session = packageInstaller.openSession(sessionId);
OutputStream packageInSession = session.openWrite("package", 0, -1);
InputStream input;
input = appContext.getContentResolver().openInputStream(uri);
if (input != null) {
generateInfoLog("input.available: " + input.available());
byte[] buffer = new byte[16384];
int n;
while ((n = input.read(buffer)) >= 0) {
packageInSession.write(buffer, 0, n);
}
} else {
generateExceptionLog("INSTALLATION FAILED");
}
packageInSession.close();
input.close();
//Intent intent2 = new Intent(appContext, ActMain.class);
Intent intent2 = new Intent(appContext, LauncherReceiver.class);
intent2.setAction(ACTION_PACKAGE_INSTALED);
//intent.setAction(Intent.PACKAGE);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
appContext,
sessionId,
intent2,
PendingIntent.FLAG_UPDATE_CURRENT);
IntentSender statusReceiver = pendingIntent.getIntentSender();
session.commit(statusReceiver);
} catch (Exception e) {
generateExceptionLog(e);
return false;
}
return true;
}
我的接收器:
public class LauncherReceiver extends BroadcastReceiver {
public static final String ACTION_PACKAGE_INSTALED = "com.gim.androidv2.action.PACKAGE_INSTALED";
@Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, ActMain.class);
intent.setAction(ACTION_PACKAGE_INSTALED);
startIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(startIntent);
}
}
清单:
<receiver android:name=".LauncherReceiver" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.aaa.aaa.action.START"></action>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>