Как обновить приложения с помощью обновления в приложении на android 10 - PullRequest
1 голос
/ 13 февраля 2020

Я пытаюсь обновить программу, используя обновление в приложении на android, и все шаги обновления успешно завершены на устройствах android с android версией, кроме версии 10Q. В этой версии android отображается диалоговое окно обновления, и обновление программного обеспечения завершается успешно, но индикатор выполнения и страница, показывающая, что обновление успешно выполнено, не отображаются, и программа закрывается. Я гуглил часами и не нашел никакого решения. Что не так с моим кодом? Любая помощь приветствуется.

Создание и установка получателя статуса

final String PACKAGE_INSTALLED_ACTION =
                    "com.example.android.apis.content.SESSION_API_PACKAGE_INSTALLED";
Intent intent = new Intent(ctx, InstallReceiver.class);
intent.setAction(PACKAGE_INSTALLED_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 3439,intent, PendingIntent.FLAG_UPDATE_CURRENT);
session.commit(pendingIntent.getIntentSender());
session.close();

Часть получателя

public final class InstallReceiver extends BroadcastReceiver {
public void onReceive(Context context,  Intent intent) {
    int status = intent.getIntExtra("android.content.pm.extra.STATUS", -1);
    if (status == -1) {
        Intent activityIntent = intent.getParcelableExtra(Intent.EXTRA_INTENT);
        activityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(activityIntent);
    } else if (status == 0) {
        (new ToneGenerator(5, 100)).startTone(25);
    } else {
        String msg = intent.getStringExtra("android.content.pm.extra.STATUS_MESSAGE");
        Log.e("AppInstaller", "received " + status + " and " + msg);
    }

}

1 Ответ

0 голосов
/ 13 февраля 2020

Чтобы выполнить обновление в приложении, вы должны следовать документам:

https://developer.android.com/guide/playcore/in-app-updates

Проверьте, доступно ли обновление:

// Creates instance of the manager.
val appUpdateManager = AppUpdateManagerFactory.create(context)

// Returns an intent object that you use to check for an update.
val appUpdateInfoTask = appUpdateManager.appUpdateInfo

// Checks that the platform will allow the specified type of update.
appUpdateInfoTask.addOnSuccessListener { appUpdateInfo ->
    if (appUpdateInfo.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
        // For a flexible update, use AppUpdateType.FLEXIBLE
        && appUpdateInfo.isUpdateTypeAllowed(AppUpdateType.IMMEDIATE)
    ) {
        // Request the update.
    }
}

Запустить обновление

appUpdateManager.startUpdateFlowForResult(
    // Pass the intent that is returned by 'getAppUpdateInfo()'.
    appUpdateInfo,
    // Or 'AppUpdateType.FLEXIBLE' for flexible updates.
    AppUpdateType.IMMEDIATE,
    // The current activity making the update request.
    this,
    // Include a request code to later monitor this update request.
    MY_REQUEST_CODE)

Список результатов обновления:

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent) {
    if (requestCode == MY_REQUEST_CODE) {
        if (resultCode != RESULT_OK) {
            log("Update flow failed! Result code: $resultCode")
            // If the update is cancelled or fails,
            // you can request to start the update again.
        }
    }
}

Я не уверен, что делает ваш код, но он не следует этому примеру.

Я подумал, что ваша проблема может быть в проверке на наличие зависших обновлений, поэтому вы должны попробовать это:

// Checks that the update is not stalled during 'onResume()'.
// However, you should execute this check at all app entry points.
override fun onResume() {
    super.onResume()

    appUpdateManager
        .appUpdateInfo
        .addOnSuccessListener { appUpdateInfo ->
            ...
            // If the update is downloaded but not installed,
            // notify the user to complete the update.
            if (appUpdateInfo.installStatus() == InstallStatus.DOWNLOADED) {
                popupSnackbarForCompleteUpdate()
            }
        }
}
...