自从我更新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>