React Native - сборка прошла успешно на Android, но приложение вылетало

Когда я создаю (> react-native run-android) с моими зависимостями, сборка выполняется успешно! Однако, когда приложение запускается, оно сразу вылетает ... Как не знаю, как это возможно, ошибки нет, ничего не говорит мне, почему приложение вылетает ...

Уверен, что это из-за зависимостей ...

dependencies {
    implementation project(':react-native-intercom')
    implementation "io.intercom.android:intercom-sdk:3.+"

    implementation project(':react-native-onesignal')
    implementation 'com.google.android.gms:play-services-location:+'

    implementation project(':react-native-linear-gradient')
    implementation project(':react-native-i18n')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.facebook.react:react-native:+"
    implementation project(':tipsi-stripe')
    implementation (project(':react-native-maps')) {
        exclude group: 'com.google.android.gms', module: 'play-services-base'
        exclude group: 'com.google.android.gms', module: 'play-services-maps'
    }
    implementation (project(':react-native-camera')) {
        exclude group: "com.google.android.gms"
        exclude group: "com.android.support", module: 'support-v4'
    }
    implementation "com.android.support:appcompat-v7:23.0.1"
    implementation 'com.google.android.gms:play-services-base:10.0.1'
    implementation 'com.google.android.gms:play-services-maps:10.0.1'
    implementation 'com.google.android.gms:play-services-gcm:10.0.1'
}

Спасибо тебе большое

Этот вопрос слишком общий, вам нужно для начала проверить свои файлы gradle на наличие нескольких экземпляров пакетов.

Pritish Vaidya 10.05.2018 11:38

Не могли бы вы проверить свои журналы всякий раз, когда приложение вылетает?

Ravi 10.05.2018 11:54

О каких журналах вы говорите?

eQuinox 10.05.2018 11:59
6
3
3 794
2

Ответы 2

У меня сейчас такая же ошибка с реакцией 0.59.8 (или даже 60+). Может быть, я смогу пролить свет на это, потому что меня это чертовски раздражает, так как я не могу разрабатывать свое приложение, но сосредоточусь на исправлении ошибок, связанных с фреймворком ... Итак, в качестве объяснения: проект построен успешно. Когда cd в подпапку android, и я выполняю

./gradlew assembleDebug --stacktrace (or similar)

он говорит, что сборка прошла успешно. Если я запускаю react-native run-android, он также успешно строит и пытается загрузить файл на устройство. А потом вылетает без ошибок. Я просто вернулся в свою оболочку, откуда я запускал react-native run-android.

Иногда это исправляется после выполнения npm start и перезагрузки на устройстве, в результате чего javascript создается / транспилируется (или что-то там происходит. Я не знаю).

Есть ли у кого-нибудь такая же проблема?

Кто-нибудь знает, почему это происходит, и может ли это объяснить?

Обновление: adblogcat *: E выдает эту ошибку при попытке подключиться к сборщику метро, ​​который был запущен с npm start (когда он не работает при запуске npm)

unknown:ReactNative: ... 21 more 09-17 10:34:38.851 29275 29275 E unknown:ReactNative: Caused by: android.system.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)

мой package.json:

{
...
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest"
  },
  "dependencies": {
    "lodash": "^4.17.11",
    "moment": "^2.24.0",
    "react": "16.8.3",
    "react-native": "0.59.8",
    "react-native-firebase": "^5.3.1",
    "react-native-gesture-handler": "^1.2.1",
    "react-native-image-picker": "^0.28.1",
    "react-native-table-component": "^1.2.0",
    "react-native-vector-icons": "^6.4.2",
    "react-navigation": "^3.11.0",
    "uuid": "^3.3.2"
  },
  "devDependencies": {
    "@babel/core": "^7.4.4",
    "@babel/runtime": "^7.4.4",
    "babel-jest": "^24.8.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.54.1",
    "react-test-renderer": "16.8.3"
  },
  "jest": {
    "preset": "react-native"
  }
}

мой MainApplication.java

...

import android.app.Application;

import com.facebook.react.ReactApplication;
import io.invertase.firebase.RNFirebasePackage;
import io.invertase.firebase.auth.RNFirebaseAuthPackage;
import io.invertase.firebase.storage.RNFirebaseStoragePackage;
import io.invertase.firebase.database.RNFirebaseDatabasePackage;
import com.swmansion.gesturehandler.react.RNGestureHandlerPackage;
import com.imagepicker.ImagePickerPackage;
import com.facebook.react.ReactNativeHost;
import com.facebook.react.ReactPackage;
import com.facebook.react.shell.MainReactPackage;
import com.facebook.soloader.SoLoader;

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

public class MainApplication extends Application implements ReactApplication {

  private final ReactNativeHost mReactNativeHost = new ReactNativeHost(this) {
    @Override
    public boolean getUseDeveloperSupport() {
      return BuildConfig.DEBUG;
    }

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(new MainReactPackage(), new RNFirebasePackage(), new RNFirebaseAuthPackage(),
          new RNGestureHandlerPackage(), new ImagePickerPackage(), new RNFirebaseStoragePackage(),
          new RNFirebaseDatabasePackage());
    }

    @Override
    protected String getJSMainModuleName() {
      return "index";
    }
  };

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

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

android / build.gradle

// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    ext {
        buildToolsVersion = "28.0.3"
        minSdkVersion = 16
        compileSdkVersion = 28
        targetSdkVersion = 28
        supportLibVersion = "28.0.0"
    }
    repositories {
        google()
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.3.2'
        classpath 'com.google.gms:google-services:4.2.0'
        
        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        mavenLocal()
        google()
        jcenter()
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
    }
}

Android / приложение / build.gradle

apply plugin: "com.android.application"

import com.android.build.OutputFile

/**
 * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets
 * and bundleReleaseJsAndAssets).
 * These basically call `react-native bundle` with the correct arguments during the Android build
 * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the
 * bundle directly from the development server. Below you can see all the possible configurations
 * and their defaults. If you decide to add a configuration block, make sure to add it before the
 * `apply from: "../../node_modules/react-native/react.gradle"` line.
 *
 * project.ext.react = [
 *   // the name of the generated asset file containing your JS bundle
 *   bundleAssetName: "index.android.bundle",
 *
 *   // the entry file for bundle generation
 *   entryFile: "index.android.js",
 *
 *   // whether to bundle JS and assets in debug mode
 *   bundleInDebug: false,
 *
 *   // whether to bundle JS and assets in release mode
 *   bundleInRelease: true,
 *
 *   // whether to bundle JS and assets in another build variant (if configured).
 *   // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants
 *   // The configuration property can be in the following formats
 *   //         'bundleIn${productFlavor}${buildType}'
 *   //         'bundleIn${buildType}'
 *   // bundleInFreeDebug: true,
 *   // bundleInPaidRelease: true,
 *   // bundleInBeta: true,
 *
 *   // whether to disable dev mode in custom build variants (by default only disabled in release)
 *   // for example: to disable dev mode in the staging build type (if configured)
 *   devDisabledInStaging: true,
 *   // The configuration property can be in the following formats
 *   //         'devDisabledIn${productFlavor}${buildType}'
 *   //         'devDisabledIn${buildType}'
 *
 *   // the root of your project, i.e. where "package.json" lives
 *   root: "../../",
 *
 *   // where to put the JS bundle asset in debug mode
 *   jsBundleDirDebug: "$buildDir/intermediates/assets/debug",
 *
 *   // where to put the JS bundle asset in release mode
 *   jsBundleDirRelease: "$buildDir/intermediates/assets/release",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in debug mode
 *   resourcesDirDebug: "$buildDir/intermediates/res/merged/debug",
 *
 *   // where to put drawable resources / React Native assets, e.g. the ones you use via
 *   // require('./image.png')), in release mode
 *   resourcesDirRelease: "$buildDir/intermediates/res/merged/release",
 *
 *   // by default the gradle tasks are skipped if none of the JS files or assets change; this means
 *   // that we don't look at files in android/ or ios/ to determine whether the tasks are up to
 *   // date; if you have any other folders that you want to ignore for performance reasons (gradle
 *   // indexes the entire tree), add them here. Alternatively, if you have JS files in android/
 *   // for example, you might want to remove it from here.
 *   inputExcludes: ["android/**", "ios/**"],
 *
 *   // override which node gets called and with what additional arguments
 *   nodeExecutableAndArgs: ["node"],
 *
 *   // supply additional arguments to the packager
 *   extraPackagerArgs: []
 * ]
 */


project.ext.vectoricons = [
    iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf', 'FontAwesome.ttf' ] // Name of the font files you want to copy
]
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

project.ext.react = [
    entryFile: "index.js"
]

apply from: "../../node_modules/react-native/react.gradle"



/**
 * Set this to true to create two separate APKs instead of one:
 *   - An APK that only works on ARM devices
 *   - An APK that only works on x86 devices
 * The advantage is the size of the APK is reduced by about 4MB.
 * Upload all the APKs to the Play Store and people will download
 * the correct one based on the CPU architecture of their device.
 */
def enableSeparateBuildPerCPUArchitecture = false

/**
 * Run Proguard to shrink the Java bytecode in release builds.
 */
def enableProguardInReleaseBuilds = false

android {
    compileSdkVersion rootProject.ext.compileSdkVersion

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    defaultConfig {
        applicationId "com.bonscanner"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 1
        versionName "1.0"
    }
    splits {
        abi {
            reset()
            enable enableSeparateBuildPerCPUArchitecture
            universalApk false  // If true, also generate a universal APK
            include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
        }
    }
    buildTypes {
        release {
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
    // 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, "arm64-v8a": 3, "x86_64": 4]
            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 {
    implementation project(':react-native-firebase')
    implementation project(':react-native-gesture-handler')
    implementation project(':react-native-image-picker')
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.facebook.react:react-native:+"  // From node_modules
    implementation "com.google.firebase:firebase-core:16.0.9"
    implementation "com.google.firebase:firebase-auth:17.0.0"
    implementation "com.google.firebase:firebase-storage:17.0.0"
    implementation 'com.google.firebase:firebase-database:17.0.0'
    }

// 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'
}

apply plugin: 'com.google.gms.google-services'

gradle.properties содержит:

android.useAndroidX=true android.enableJetifier=true

Для проверки журналов исключений в сгенерированном режиме выпуска apk выполните шаги 1-3. (Шаг 1 можно пропустить, если подписанный apk для режима выпуска уже установлен на устройстве.)

  1. Убедитесь, что команда adb devices отображает ваше устройство, затем установите приложение на устройство / эмулятор, выполнив команду ниже из папки с apk.

    adb -d install -r app-name.apk пример: adb -d install -r learnapp.apk

измените -d на -e, если вы хотите установить на эмулятор.

  1. запустить adb logcat | FINDSTR "Exception" Это будет регистрировать все сообщения об исключениях в cmd.

  2. Теперь запустите приложение, и подробности об исключении будут доступны в cmd.

Исключения могут быть очень незначительными проблемами, например, у меня была console.clear () в одном из хука componentDidMount () моего экрана приложения, а исключение console.clear - undefined вызывало сбой после перехода на этот экран. После выполнения шагов 1-3 я обнаружил исключение, удалил эту строку из кода, снова сгенерировал apk, и после этого приложение работало нормально !!

Другие вопросы по теме