Home > OS >  My app is crashing after I implement In-App-Update from Play Store
My app is crashing after I implement In-App-Update from Play Store

Time:12-17

My app is building successfully but when I open it it closes by itself...

I was able to successfully implement In-App-Review! But Update is failing and crashing my app on start.

I have an error in AppUpdateManager. I reproduced the code from scratch line by line... And the app crashed on its own, after build, when I called the App Update Manager:

private final AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);

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

My MainActivity

package com.baraokeskina;

import com.baraokeskina.ReviewsApp.ReviewsManager;
import com.facebook.react.ReactActivity;
import com.facebook.react.ReactActivityDelegate;
import com.facebook.react.ReactRootView;
import com.google.android.gms.tasks.Task;
import com.google.android.material.snackbar.Snackbar;
import com.google.android.play.core.appupdate.AppUpdateInfo;
import com.google.android.play.core.appupdate.AppUpdateManager;
import com.google.android.play.core.appupdate.AppUpdateManagerFactory;
import com.google.android.play.core.install.InstallStateUpdatedListener;
import com.google.android.play.core.install.model.AppUpdateType;
import com.google.android.play.core.install.model.InstallStatus;
import com.google.android.play.core.install.model.UpdateAvailability;
import com.google.android.play.core.review.ReviewInfo;
import com.google.android.play.core.review.ReviewManager;
import com.google.android.play.core.review.ReviewManagerFactory;
import com.swmansion.reanimated.BuildConfig;

import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;



public class MainActivity extends ReactActivity {

  /**
   * Returns the name of the main component registered from JavaScript. This is used to schedule
   * rendering of the component.
   */
  @Override
  protected String getMainComponentName() {
    return "BaraokeSkina";
  }

  private ReviewInfo reviewInfo;
  private ReviewManager manager;
  private static final int RC_APP_UPDATE = 22;

  private final AppUpdateManager mAppUpdateManager = AppUpdateManagerFactory.create(this);

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(null);
     activateUpdate();
    if (new ReviewsManager().getDaysAppInstaled(this) >= 4) {
      activateReviewInfo();
    }

  }


  void activateUpdate(){
    Task<AppUpdateInfo> appUpdateInfoTask = mAppUpdateManager.getAppUpdateInfo();

    appUpdateInfoTask.addOnSuccessListener(result -> {
      if (result.updateAvailability() == UpdateAvailability.UPDATE_AVAILABLE
              && result.isUpdateTypeAllowed(AppUpdateType.FLEXIBLE)) {
        try {
          mAppUpdateManager.startUpdateFlowForResult(result, AppUpdateType.FLEXIBLE, MainActivity.this, RC_APP_UPDATE);
        } catch (IntentSender.SendIntentException e) {
          System.out.println(e.getMessage());
        }

      }
    });
    mAppUpdateManager.registerListener(installStateUpdatedListener);
  }

  private final InstallStateUpdatedListener installStateUpdatedListener = installState -> {
    if (installState.installStatus() == InstallStatus.DOWNLOADED) {
      showCompleteUpdate();
    }
  };

  @Override
  protected void onStop() {
    super.onStop();
    if (mAppUpdateManager != null) {
      mAppUpdateManager.unregisterListener(installStateUpdatedListener);
    }
  }

  private void showCompleteUpdate() {
    Snackbar snackbar = Snackbar.make(findViewById(android.R.id.content), "Atualização pronta para ser Instalada...",
            Snackbar.LENGTH_INDEFINITE);

    snackbar.setAction("Instalar", view -> mAppUpdateManager.completeUpdate());

    snackbar.show();
  }

  void activateReviewInfo()
  {
    Activity context = this;

    final Handler handler = new Handler(Looper.getMainLooper());
    handler.postDelayed(() -> {
      manager = ReviewManagerFactory.create(context);

      Task<ReviewInfo> request = manager.requestReviewFlow();
      request.addOnCompleteListener(task -> {
        if (task.isSuccessful()) {
          reviewInfo = task.getResult();
          Task<Void> flow = manager.launchReviewFlow(context, reviewInfo);
          flow.addOnCompleteListener(result -> {
          });
        }
      });

      request.addOnFailureListener(e -> System.out.println(e.getMessage()));
    }, 15000);
  }

  @Override
  public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_APP_UPDATE && resultCode != RESULT_OK) {
      Toast.makeText(this, "Cancelado", Toast.LENGTH_SHORT).show();
    }
  }

  /**
   * Returns the instance of the {@link ReactActivityDelegate}. There the RootView is created and
   * you can specify the rendered you wish to use (Fabric or the older renderer).
   */
  @Override
  protected ReactActivityDelegate createReactActivityDelegate() {
    return new MainActivityDelegate(this, getMainComponentName());
  }

  public static class MainActivityDelegate extends ReactActivityDelegate {
    public MainActivityDelegate(ReactActivity activity, String mainComponentName) {
      super(activity, mainComponentName);
    }

    @Override
    protected ReactRootView createRootView() {
      ReactRootView reactRootView = new ReactRootView(getContext());
      // If you opted-in for the New Architecture, we enable the Fabric Renderer.
      reactRootView.setIsFabric(BuildConfig.IS_NEW_ARCHITECTURE_ENABLED);
      return reactRootView;
    }
  }



  @Override
   protected void onDestroy() {
     super.onDestroy();
     reviewInfo = null;
     manager = null;
   }
}


Bild.gradle implementations

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'com.facebook.android:facebook-android-sdk:[4,5)'
    implementation 'com.google.android.material:material:1.1.0'
    //noinspection GradleDynamicVersion
    implementation "com.facebook.react:react-native:0.68.1!!"  // From node_modules

    implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"


    debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.fbjni'
    }

    debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
        exclude group:'com.squareup.okhttp3', module:'okhttp'
    }

    debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") {
        exclude group:'com.facebook.flipper'
    }

    if (enableHermes) {
        def hermesPath = "../../node_modules/hermes-engine/android/";
        debugImplementation files(hermesPath   "hermes-debug.aar")
        releaseImplementation files(hermesPath   "hermes-release.aar")
    } else {
        implementation jscFlavor
    }
    implementation project(':react-native-fbsdk-next')
    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-svg')
    implementation "androidx.multidex:multidex:2.0.1"
    implementation project(':react-native-vector-icons')
    implementation project(':watermelondb')
    implementation project(':watermelondb-jsi')
    implementation 'com.google.android.gms:play-services-tasks:18.0.2'
    implementation project(path: ":@react-native-firebase_analytics")
    implementation project(path: ":@react-native-firebase_inAppMessaging")
    implementation 'com.google.android.play:review:2.0.1'
    implementation 'com.google.android.play:app-update:2.0.1'
    implementation 'com.google.android.play:asset-delivery:2.0.1'
    implementation 'com.google.android.play:feature-delivery:2.0.1'
}   

My Default Config - Build.gradle:


defaultConfig {
        applicationId "com.baraokeskina"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 12
        versionName "1.0.11"
        multiDexEnabled true
        resValue 'string', "CODE_PUSH_APK_BUILD_TIME", String.format("\"%d\"", System.currentTimeMillis())
        buildConfigField "boolean", "IS_NEW_ARCHITECTURE_ENABLED", isNewArchitectureEnabled().toString()
        vectorDrawables.useSupportLibrary = true
        if (isNewArchitectureEnabled()) {
            // We configure the NDK build only if you decide to opt-in for the New Architecture.
            externalNativeBuild {
                ndkBuild {
                    arguments "APP_PLATFORM=android-21",
                        "APP_STL=c  _shared",
                        "NDK_TOOLCHAIN_VERSION=clang",
                        "GENERATED_SRC_DIR=$buildDir/generated/source",
                        "PROJECT_BUILD_DIR=$buildDir",
                        "REACT_ANDROID_DIR=$rootDir/../node_modules/react-native/ReactAndroid",
                        "REACT_ANDROID_BUILD_DIR=$rootDir/../node_modules/react-native/ReactAndroid/build"
                    cFlags "-Wall", "-Werror", "-fexceptions", "-frtti", "-DWITH_INSPECTOR=1"
                    cppFlags "-std=c  17"
                    // Make sure this target name is the same you specify inside the
                    // src/main/jni/Android.mk file for the `LOCAL_MODULE` variable.
                    targets "baraokeskina_appmodules"

                    // Fix for windows limit on number of character in file paths and in command lines
                    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
                        arguments "NDK_OUT=${rootProject.projectDir.getParent()}\\.cxx",
                            "NDK_APP_SHORT_COMMANDS=true"
                    }
                }
            }
            if (!enableSeparateBuildPerCPUArchitecture) {
                ndk {
                    abiFilters (*reactNativeArchitectures())
                }
            }
        }
    }

CodePudding user response:

I Has resolved this question The problem is

AppUpdateManagerFactory.create(this)

Only Can be instancied on one time.

  • Related