JavaScript 运行 react-native run-android 报错(Error: Command failed: gradlew.bat )解决方法

本文主要介绍android开发,运行react-native run-android报错:Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081 Execution failed for task ':app:checkDebugAarMetadata'.的解决方法。

报错信息:

error Failed to install the app. Make sure you have the Android development environment set up: https://reactnative.dev/docs/environment-setup.
Error: Command failed: gradlew.bat app:installDebug -PreactNativeDevServerPort=8081

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:checkDebugAarMetadata'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.CheckAarMetadataWorkAction
   > The minCompileSdk (30) specified in a
     dependency's AAR metadata (META-INF/com/android/build/gradle/aar-metadata.properties)
     is greater than this module's compileSdkVersion (android-29).
     Dependency: androidx.core:core:1.7.0-alpha01.
     AAR metadata file: C:\Users\gauraab\.gradle\caches\transforms-2\files-2.1\9e02d64f5889006a671d0a7165c73e72\core-1.7.0-alpha01\META-INF\com\android\build\gradle\aar-metadata.properties.

问题原因:

find . -name '*.gradle' -exec grep -H "\.+" {} \;

node_modules/@react-native-community/netinfo/android/build.gradle以下代码段中找到:

def androidXCore = getExtOrInitialValue('androidXCore', null)
  if (supportLibVersion && androidXVersion == null && androidXCore == null) {
    implementation "com.android.support:appcompat-v7:$supportLibVersion"
  } else {
    def defaultAndroidXVersion = "1.+"
    if (androidXCore == null) {
      androidXCore = androidXVersion == null ? defaultAndroidXVersion : androidXVersion
    }
    implementation "androidx.core:core:$androidXCore"
  }
}

所以原因是react-native编译项目时会自动升级依赖SDK 30的androidx.core:core:1.7.0-alpha01

解决方法:

通过 build.gradle 中的 androidXCore 指定 android 核心版本,如下

buildscript {
    ext {
        buildToolsVersion = "29.0.3"
        minSdkVersion = 23
        compileSdkVersion = 29
        targetSdkVersion = 29
        ndkVersion = "20.1.5948944"
        kotlin_version = "1.5.0"
        androidXCore = "1.5.0"
    }

或者

可以通过在 build.gradle 文件中添加以下行来修复它:

configurations.all {   
    resolutionStrategy { force 'androidx.core:core-ktx:1.6.0 }
} 

相关文档https://docs.gradle.org/current/dsl/org.gradle.api.artifacts.ResolutionStrategy.html

推荐阅读
cjavapy编程之路首页