react-native-code-push icon indicating copy to clipboard operation
react-native-code-push copied to clipboard

React Native CodePush Android Release Build not loading JS files

Open kesiena115 opened this issue 9 years ago • 6 comments

Please I need help with this problem I've been struggling with for a few days.

Expected Behavior

When I install the release build of my app with react-native run-android --variant=release, I expect it to download the JS files from codepush servers because I've followed the instructions here and here. I've uploaded the JS files to Staging & Production and confirmed that they're there by running code-push deployment ls <myAppName>-Android -k

Actual Behavior

Although the app displays the first screen, none of the app functionality works. When I check the log files (while installing the release build on the Android emulator), it shows this line:

    [CodePush] Loading JS bundle from "assets://index.android.bundle"

I find it surprising that the release build is trying to load the JS bundle locally instead of checking CodePush remote server.

Environment

  • react-native-code-push version: 5.0.0-beta
  • react-native version: 0.47.1
  • Android version: 6.0
  • Does this reproduce on a debug build or release build: Release build
  • Does this reproduce on a simulator, or only on a physical device: Both

Reproducible Demo

settings.gradle file:

rootProject.name = 'OneText'
include ':react-native-onesignal'
project(':react-native-onesignal').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-onesignal/android')

include ':react-native-image-picker'
project(':react-native-image-picker').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-image-picker/android')

include ':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')

include ':app'

Relevant parts of my build.gradle file:

apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"

def enableSeparateBuildPerCPUArchitecture = false

def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig {
        applicationId "com.onetext"
        minSdkVersion 16
        targetSdkVersion 22
        versionCode 4
        versionName "1.0.1"
        ndk {
            abiFilters "armeabi-v7a", "x86"
        }
         manifestPlaceholders = [onesignal_app_id: "xxx",
                                         onesignal_google_project_number: "xxx"]
    }
    signingConfigs {
        release {
            if (project.hasProperty('MYAPP_RELEASE_STORE_FILE')) {
                storeFile file(MYAPP_RELEASE_STORE_FILE)
                storePassword MYAPP_RELEASE_STORE_PASSWORD
                keyAlias MYAPP_RELEASE_KEY_ALIAS
                keyPassword MYAPP_RELEASE_KEY_PASSWORD
            }
        }
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86"
        }
    }
    buildTypes {
        debug {
            buildConfigField "String", "CODEPUSH_KEY", '""'
        }
        releaseStaging {
            buildConfigField "String", "CODEPUSH_KEY", '"H3ZFJ..."'
        }
        release {
            buildConfigField "String", "CODEPUSH_KEY", '"r0Sx..."'
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
            signingConfig signingConfigs.release
        }
    }
    // applicationVariants are e.g. debug, release
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            // For each separate APK per architecture, set a unique version code as described here:
            // http://tools.android.com/tech-docs/new-build-system/user-guide/apk-splits
            def versionCodes = ["armeabi-v7a":1, "x86":2]
            def abi = output.getFilter(OutputFile.ABI)
            if (abi != null) {  // null for the universal-debug, universal-release variants
                output.versionCodeOverride =
                        versionCodes.get(abi) * 1048576 + defaultConfig.versionCode
            }
        }
    }
}

dependencies {
    compile project(':react-native-onesignal')
    compile project(':react-native-image-picker')
    compile project(':react-native-code-push')
    compile fileTree(dir: "libs", include: ["*.jar"])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
}

// Run this once to be able to run the application with BUCK
// puts all compile dependencies into folder libs for BUCK to use
task copyDownloadableDepsToLibs(type: Copy) {
    from configurations.compile
    into 'libs'
}

MainApplication.java:

package com.onetext;

import android.app.Application;

import com.facebook.react.ReactApplication;
import com.geektime.rnonesignalandroid.ReactNativeOneSignalPackage;
import com.microsoft.codepush.react.CodePush;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;
import com.imagepicker.ImagePickerPackage;

import java.util.Arrays;
import java.util.List;

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {

    @Override
    protected String getJSBundleFile() {
      return CodePush.getJSBundleFile();
    }

    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
          new MainReactPackage(),
            new ReactNativeOneSignalPackage(),
            new CodePush(BuildConfig.CODEPUSH_KEY, MainApplication.this, BuildConfig.DEBUG), // Add/change this line.
            new ImagePickerPackage()
      );
    }
  };

  @Override
  public ReactNativeHost getReactNativeHost() {
    return mReactNativeHost;
  }

  @Override
  public void onCreate() {
    super.onCreate();
    SoLoader.init(this, /* native exopackage */ false);
  }
}

kesiena115 avatar Sep 04 '17 22:09 kesiena115

Hello @kesiena115, I've tried to follow your approach and was unable to reproduce the issue. Let's go over the steps again:

  1. I've created new rn app rninit init issue987 [email protected]
  2. Moved to the app's directory cd issue987
  3. I've installed RNCP npm install --save [email protected]
  4. I've created new app with Staging and Production deployments code-push app add issue987_android android react-native
  5. I've linked libraries as follows: react-native link react-native-code-push
  6. I've generated signing key as it is described here
  7. I've added signing config to the app build.gradle as it is described here
  8. Verified that mine MainApplication.java init code is the same as yours
  9. Configured code-push in index.android.js file as follows:
index.android.js (Click to expand)
import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';

import CodePush from "react-native-code-push";

export default class issue987 extends Component {

  constructor() {
    super();
    this.state = { restartAllowed: true };
  }

  codePushStatusDidChange(syncStatus) {
    switch(syncStatus) {
      case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
        this.setState({ syncMessage: "Checking for update." });
        break;
      case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
        this.setState({ syncMessage: "Downloading package." });
        break;
      case CodePush.SyncStatus.AWAITING_USER_ACTION:
        this.setState({ syncMessage: "Awaiting user action." });
        break;
      case CodePush.SyncStatus.INSTALLING_UPDATE:
        this.setState({ syncMessage: "Installing update." });
        break;
      case CodePush.SyncStatus.UP_TO_DATE:
        this.setState({ syncMessage: "App up to date.", progress: false });
        break;
      case CodePush.SyncStatus.UPDATE_IGNORED:
        this.setState({ syncMessage: "Update cancelled by user.", progress: false });
        break;
      case CodePush.SyncStatus.UPDATE_INSTALLED:
        this.setState({ syncMessage: "Update installed and will be applied on restart.", progress: false });
        break;
      case CodePush.SyncStatus.UNKNOWN_ERROR:
        this.setState({ syncMessage: "An unknown error occurred.", progress: false });
        break;
    }
  }

  /** Update is downloaded silently, and applied on restart (recommended) */
  sync() {
    CodePush.sync(
      {},
      this.codePushStatusDidChange.bind(this),
      null
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <TouchableOpacity onPress={this.sync.bind(this)}>
          <Text style={styles.syncButton}>Press for background sync</Text>
        </TouchableOpacity>
        <Text style={styles.instructions}>
          To get started, edit index.android.js
        </Text>
        <Text style={styles.instructions}>
          Double tap R on your keyboard to reload,{'\n'}
          Shake or press menu button for dev menu 222
        </Text>
        <Text style={styles.messages}>{this.state.syncMessage || ""}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };
issue987 = CodePush(codePushOptions)(issue987);

AppRegistry.registerComponent('issue987', () => issue987);

  1. Verified the app is running well with react-native run-android --variant=release
  2. Produced new code push release for Production deployment with the following command: code-push release-react issue987_android android --deploymentName Production

NOTE that we should explicitly provide deployment name here

  1. Press sync button on my app, verified update is installed

Could you please take a look at this and let me know if your steps are different and you still see an issue.

max-mironov avatar Sep 05 '17 08:09 max-mironov

Thank you so much @max-mironov. I've not been able to figure out what's wrong with my app. But by following your steps, everything works as expected. I might just have to slowly add my app features unto a simple working version like yours until I figure out the problem. My original setup was based on native-starter-kit. I have two quick questions based on some observed differences:

  1. Need for restart: With your example, I had to restart the emulator (so I guess users will have to restart their phones) for the update to be applied. Is this the recommended approach or is there a way to apply updates without restarting the device?

  2. Staging vs production key: By following the prompt in react-native link react-native-code-push, the deployment key ends up in android/app/src/main/res/values/strings.xml (which is different from my initial setup). In this case, how does one configure staging and production keys? Do you simply replace this key if you want to test the release in staging?

kesiena115 avatar Sep 05 '17 16:09 kesiena115

Hey @kesiena115, that's great that you were able to update your app successfully.

Regarding your questions:

  1. In the end it's up to you to decide whether you should use silent updates or specifically prompt user if s/he would like to update the app. Just beware of Store Guideline Compliance when using update dialog with immediate updates for this. From my point of view silent updates using ON_NEXT_RESUME or ON_NEXT_SUSPEND should fit the best for most of the customers.
  2. In general - yes, you can just simply replace the key before uploading the app to AppStrore and that's it. Also you could use MultiDeployment workflow to define custom config settings for each type of the build (that is what was done in your sample). This way correct deployment key would be applied based on build type.

Please let me know if you have more questions.

max-mironov avatar Sep 05 '17 16:09 max-mironov

@kesiena115 - I'm going to close the issue as it seems to be resolved, please feel free to reach us in case of any troubles with code-push.

max-mironov avatar Sep 07 '17 06:09 max-mironov

@kesiena115 Did you end up getting your app working with this? If so, do you know what was wrong? I'm currently facing a similar issue. The update appears to work fine and the app reloads but the bundle does not update (i.e. the UI doesn't change to reflect the changes I made in the new bundle).

Thanks!

joshuapinter avatar Sep 07 '17 17:09 joshuapinter

@joshuapinter yes my issue is resolved. I'll first explain the bug I had before showing some code changes I used for my case.

My bug

It was actually caused by react-navigation. I was using <classObject>.name to specify the name of my screens. That worked as expected in debug mode but not in release mode (still not sure why), hence my buttons were not navigating to the next screen in my release build. I fixed that by using normal string variables as my screen names instead of my previous fancy code.

Code push

I wish the original documentation was well laid out like the steps provided by @max-mironov. When I followed max's instructions to create a new app, I was able to get everything working as expected and the codepush updates work well. Now I need to update my original app because the codepush updating mechanism (based on native-starter-kit) isn't yet working as expected in my app. In order to implement max's suggestions about ON_NEXT_RESUME, I used this code to replace his sync():

/** Update is downloaded after clicking the button and installed on next app resume after moving the app to the background */
  sync() {
    CodePush.sync(
      { installMode: CodePush.InstallMode.ON_NEXT_RESUME },  // Note the lowercase i in installMode:
      this.codePushStatusDidChange.bind(this),
      null
    );
  }

That way, the app downloads updates when I click on the button added by Max in his example, but I'll only see the updates after re-opening the app from the background.

kesiena115 avatar Sep 07 '17 19:09 kesiena115