Gradle debug Crashes with NullpointerException - Run works fine - java

Gradle crashes with a NullpointerException when trying to debug my app in Android Studio. It works fine just to Run the app. Android Studio 2.3.3.
Here's the gradle stacktrace:
java.lang.NullPointerException
at com.android.tools.idea.run.GradleApplicationIdProvider.getTestPackageName(GradleApplicationIdProvider.java:50)
at com.android.tools.idea.run.AndroidLaunchTasksProvider.getConnectDebuggerTask(AndroidLaunchTasksProvider.java:160)
at com.android.tools.idea.run.LaunchTaskRunner.run(LaunchTaskRunner.java:79)
at com.intellij.openapi.progress.impl.CoreProgressManager$TaskRunnable.run(CoreProgressManager.java:635)
at com.intellij.openapi.progress.impl.CoreProgressManager$3.run(CoreProgressManager.java:170)
at com.intellij.openapi.progress.impl.CoreProgressManager.registerIndicatorAndRun(CoreProgressManager.java:494)
at com.intellij.openapi.progress.impl.CoreProgressManager.executeProcessUnderProgress(CoreProgressManager.java:443)
at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:54)
at com.intellij.openapi.progress.impl.CoreProgressManager.runProcess(CoreProgressManager.java:155)
at com.intellij.openapi.progress.impl.ProgressManagerImpl$1.run(ProgressManagerImpl.java:128)
at com.intellij.openapi.application.impl.ApplicationImpl$2.run(ApplicationImpl.java:307)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
at java.util.concurrent.FutureTask.run(FutureTask.java:266)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Here's my build.gradle inside the app folder. Some more details: This is a project with the Cocos2d-x game engine and I'm trying to get Debug for native code to work. A simple test project does work, but my own project does not.
import java.util.regex.Pattern
import com.android.build.OutputFile
import org.apache.tools.ant.taskdefs.condition.Os
apply plugin: 'com.android.application'
apply plugin: 'io.fabric'
task('increaseVersionCode') << {
println 'Grade: Increasing Version Code...'
def buildFile = file("build.gradle")
def pattern = Pattern.compile("versionCode\\s+(\\d+)")
def manifestText = buildFile.getText()
def matcher = pattern.matcher(manifestText)
matcher.find()
def versionCode = Integer.parseInt(matcher.group(1))
def manifestContent = matcher.replaceAll("versionCode " + ++versionCode)
buildFile.write(manifestContent)
}
preBuild.dependsOn increaseVersionCode
task deleteGraphicsAssets(type: Delete) {
println 'Grade: Deleting unnecessary assets...'
delete "assets/1136p"
delete "assets/2048p"
}
preBuild.dependsOn deleteGraphicsAssets
android {
// Going higher means that we have to request to write to external storage (used for UUID): https://stackoverflow.com/questions/36084959/cant-create-a-directory-on-storage-emulated-0-on-emulator
// But GameAnalytics reqires 24, let's see if it still works this way
compileSdkVersion 22
buildToolsVersion '25.0.3' // should be 25 for newer version
defaultConfig {
applicationId "com.forestringgames.apps.towerduel"
minSdkVersion 15
// Going higher means that we have to request to write to external storage (used for UUID): https://stackoverflow.com/questions/36084959/cant-create-a-directory-on-storage-emulated-0-on-emulator
// But GameAnalytics reqires 24, let's see if it still works this way
targetSdkVersion PROP_TARGET_SDK_VERSION
versionCode 1607
versionName "1.0"
// multiDexEnabled true
externalNativeBuild {
ndkBuild {
if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
// skip the NDK Build step if PROP_NDK_MODE is none
targets 'cocos2dcpp'
arguments 'NDK_TOOLCHAIN_VERSION=4.9'
arguments 'APP_PLATFORM=android-' + PROP_TARGET_SDK_VERSION
def module_paths = [project.file("../../FRGEngine/cocos2d").absolutePath,
project.file("../../FRGEngine/cocos2d/cocos").absolutePath,
project.file("../../FRGEngine/cocos2d/external").absolutePath]
if (Os.isFamily(Os.FAMILY_WINDOWS)) {
// should use '/'
module_paths = module_paths.collect { it.replaceAll('\\\\', '/') }
arguments 'NDK_MODULE_PATH=' + module_paths.join(";")
} else {
arguments 'NDK_MODULE_PATH=' + module_paths.join(':')
}
arguments '-j' + Runtime.runtime.availableProcessors()
abiFilters.addAll(PROP_APP_ABI.split(':').collect { it as String })
}
}
}
}
// only added for android debugging
externalNativeBuild {
ndkBuild {
if (!project.hasProperty("PROP_NDK_MODE") || PROP_NDK_MODE.compareTo('none') != 0) {
// skip the NDK Build step if PROP_NDK_MODE is none
path "jni/Android.mk"
}
}
}
sourceSets.main {
java.srcDir "src"
res.srcDir "res"
jniLibs.srcDir "libs"
manifest.srcFile "AndroidManifest.xml"
assets.srcDir "assets"
}
splits {
abi {
enable true
reset()
include 'armeabi-v7a'
//, 'armeabi', 'armeabi-v7a', 'x86' - what about arm64? Test it with Crashlytics
universalApk false //true
}
// density {
// enable true
// reset()
// include 'mdpi', 'hdpi', 'xhdpi', 'xxhdpi', 'xxxhdpi'
// compatibleScreens 'small', 'normal', 'large', 'xlarge'
//
// }
}
signingConfigs {
release {
if (project.hasProperty("RELEASE_STORE_FILE")) {
storeFile file(RELEASE_STORE_FILE)
storePassword RELEASE_STORE_PASSWORD
keyAlias RELEASE_KEY_ALIAS
keyPassword RELEASE_KEY_PASSWORD
}
}
}
buildTypes {
release {
minifyEnabled false // Warning: is this a good idea?
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
if (project.hasProperty("RELEASE_STORE_FILE")) {
signingConfig signingConfigs.release
}
externalNativeBuild {
ndkBuild {
arguments 'NDK_DEBUG=0'
}
}
}
debug {
// debuggable true
// jniDebuggable true
externalNativeBuild {
ndkBuild {
arguments 'NDK_DEBUG=1'
}
}
}
}
}
crashlytics {
enableNdk = true
androidNdkOut = 'obj'
androidNdkLibsOut = 'libs'
}
repositories {
mavenCentral()
}
dependencies {
// compile 'com.android.support:multidex:1.0.1'
compile fileTree(include: ['*.jar'], dir: 'libs')
compile project(':libcocos2dx')
// compile project(':BaseGameUtils')
// compile 'com.android.support:multidex:1.0.0'
compile 'com.facebook.android:facebook-android-sdk:4.8.0'
// compile 'com.google.android.gms:play-services-auth:9.0.0'
// integration guide (with latest version numbers: https://fabric.io/downloads/gradle)
// Crashlytics KitminifyEnabled
compile('com.crashlytics.sdk.android:crashlytics:2.6.8#aar') {
transitive = true
}
// NDK Kit
compile('com.crashlytics.sdk.android:crashlytics-ndk:1.1.6#aar') {
transitive = true
}
// compile('com.crashlytics.sdk.android:crashlytics:2.7.0-SNAPSHOT#aar') {
// transitive = true;
// }
//
// compile('com.crashlytics.sdk.android:crashlytics-ndk:1.2.0-SNAPSHOT:debug#aar') {
// transitive = true;
// }
compile 'net.bytebuddy:byte-buddy:1.7.3'
compile 'net.bytebuddy:byte-buddy-android:1.7.3'
// compile 'com.google.firebase:firebase-auth:11.0.1'
compile 'com.google.android.gms:play-services-auth:11.0.0'
compile 'com.google.android.gms:play-services-games:11.0.0'
compile 'com.google.firebase:firebase-invites:11.0.0'
compile 'com.google.firebase:firebase-messaging:11.0.0'
compile 'com.anjlab.android.iab.v3:library:1.0.+'
compile files('Frameworks/Fmod/prebuilt/android/fmod.jar')
// // use latest version instead version number: https://github.com/GameAnalytics/GA-SDK-ANDROID
// compile 'com.gameanalytics.sdk:gameanalytics-android:3.5.0'
compile fileTree(include: ['*.jar'], dir: 'Frameworks/Jars')
//
}
apply plugin: 'com.google.gms.google-services'
Here's the project-wide build.gradle file:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
classpath 'com.android.tools.build:gradle:2.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
// The Fabric Gradle plugin uses an open ended version to react
// quickly to Android tooling updates
//classpath 'io.fabric.tools:gradle:1.21.5' // version number: https://twittersdk.artifactoryonline.com/twittersdk/repo/io/fabric/tools/gradle/
classpath 'io.fabric.tools:gradle:1.+'
classpath 'com.google.gms:google-services:3.1.0'
}
}
allprojects {
repositories {
jcenter()
// FABRIC PRIVATE
// maven { url 'https://s3.amazonaws.com/fabric-artifacts-private/internal-snapshots' }
// FABRIC OFFICIAL
maven { url 'https://maven.fabric.io/public' }
// maven { url 'http://maven.gameanalytics.com/release' }
}
}
Edit: I also already tried this in this order:
Rebuild Project
Clean Project
Invalidate caches / Restart
In case you are using Gradle deamon. stop it by ./gradlew --stop and start over the steps from 1 to 3
Finally & destructively close Android Studio completely and delete .gradle directory ( it's hidden ) from the root of directory of your project and then launch Android Studio again.
Close all other Android Studio Instances
Restart OSX

Make sure your NDK path is properly configured on Project Structure (File > Project Structure > SDK Location > Android NDK Location). Click "OK" and try to sync again.

Related

android studio: FAILURE: Build failed with an exception

I am trying to build a flutter app I get so many problems while building it and found a solutions for all of them but now I am stuck since the morning with this one:
> Task :firebase_auth:generateDebugRFile FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':firebase_auth:generateDebugRFile'.
> Could not resolve all files for configuration ':firebase_auth:debugCompileClasspath'.
> Could not find browser-1.0.0.aar (androidx.browser:browser:1.0.0).
Searched in the following locations:
https://dl.google.com/dl/android/maven2/androidx/browser/browser/1.0.0/browser-1.0.0.aar
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
* Get more help at https://help.gradle.org
Deprecated Gradle features were used in this build, making it incompatible with Gradle 7.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/6.7/userguide/command_line_interface.html#sec:command_line_warnings
BUILD FAILED in 37s
my project build.gradle:
buildscript {
ext.kotlin_version = '1.5.31'
repositories {
google()
jcenter()
maven {
url 'http://storage.googleapis.com/r8-releases/raw'
}
}
dependencies {
classpath 'com.android.tools:r8:2.1.75'
classpath 'com.google.gms:google-services:4.3.2'
classpath 'com.android.tools.build:gradle:4.1.0'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
rootProject.buildDir = '../build'
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
project.evaluationDependsOn(':app')
}
task clean(type: Delete) {
delete rootProject.buildDir
}
my app build.gradle:
buildscript {
repositories {
// ...
maven { url 'https://plugins.gradle.org/m2/' } // Gradle Plugin Portal
}
dependencies {
// ...
// OneSignal-Gradle-Plugin
classpath 'gradle.plugin.com.onesignal:onesignal-gradle-plugin:[0.12.6, 0.99.99]'
}
}
apply plugin: 'com.onesignal.androidsdk.onesignal-gradle-plugin'
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
localPropertiesFile.withReader('UTF-8') { reader ->
localProperties.load(reader)
}
}
def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}
def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
flutterVersionCode = '1'
}
def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
flutterVersionName = '1.0'
}
apply plugin: 'com.android.application'
apply plugin: 'com.google.gms.google-services'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"
def keystoreProperties = new Properties()
def keystorePropertiesFile = rootProject.file('key.properties')
if (keystorePropertiesFile.exists()) {
keystoreProperties.load(new FileInputStream(keystorePropertiesFile))
}
android {
compileSdkVersion 30
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
lintOptions {
disable 'InvalidPackage'
checkReleaseBuilds false
}
defaultConfig {
applicationId "com.inspireui.fluxstore"
minSdkVersion 20
targetSdkVersion 30
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
multiDexEnabled true
resConfigs "en"
manifestPlaceholders = [
onesignal_app_id: 'PUT_YOUR_ONESIGNAL_APP_ID_HERE',
// Project number pulled from dashboard, local value is ignored.
onesignal_google_project_number: 'REMOTE'
]
}
signingConfigs {
release {
keyAlias keystoreProperties['keyAlias']
keyPassword keystoreProperties['keyPassword']
storeFile file(keystoreProperties['storeFile'])
storePassword keystoreProperties['storePassword']
}
}
buildTypes {
release {
// Signing with the debug keys for now, so `flutter run --release` works.
signingConfig signingConfigs.release
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
signingConfig signingConfigs.release
}
}
}
flutter {
source '../..'
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test:runner:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
implementation 'com.android.support:multidex:1.0.3'
implementation 'androidx.browser:browser:1.3.0'
// For checking GMS availability.
implementation "com.google.android.gms:play-services-base:17.6.0"
// Fix duplicate exoplayer
implementation 'com.google.android.exoplayer:exoplayer:2.14.1'
}
googleServices { disableVersionCheck = true }
//Fix android-r issue
subprojects {
project.buildDir = "${rootProject.buildDir}/${project.name}"
project.evaluationDependsOn(':app')
afterEvaluate {project ->
if (project.hasProperty("android") && project.property("android").compileSdkVersion.equals("android-R")) {
android {
compileSdkVersion 30
}
}
}
}
gradle.propertis:
org.gradle.jvmargs=-Xmx1536M
android.useAndroidX=true
android.enableJetifier=true
Solutions I tried:
invalidate cache and restart
flutter clean && flutter pub get
gradlew clean && gradlew build
delete the %USER%/.android and %USER%/.gradle and delete every thing related to android studio and reinstalled it
use a VPN ( tried 3 )
but unfortunatly, nothing helped me
for further info: I am building fluxstore app
I still think its a connection issue . is maven google available in your browser with no VPN ?
if no then here is a old solution of mine , on how to configure gradle to use you VPN properly . Because you need to tell gradle to send request over VPN using gradle.properties file .

How to convert all the contents of a .aar package to a .jar package?

I am trying to convert a .aar package to a .jar package according to the title above. I have tried several procedures(including those mentioned here), but all without success. It seems that it is necessary to convert all the contents of the package (including resources, manifest, etc.) to .jar.
The reason for this is that I need to publish .jar files together with my library in an artifactory repository, since .aar gets the following error when referencing it in 'libs /' in the assemble process:
Execution failed for task ':integration-lib:bundleReleaseAar'.
> Direct local .aar file dependencies are not supported when building an AAR. The resulting AAR would be broken because the classes and Android resources from any local .aar file dependencies would not be packaged in the resulting AAR.
Previous versions of the Android Gradle Plugin produce broken AARs in this case too (despite not throwing this error). The following direct local .aar file dependencies of the :integration-lib project caused this error: /Users/thomas/Projetos/mobile-integration-lib/integration-lib/libs/PPCompAndroid-v1.32.aar
I also tried to import it by creating a new module with .jar/.aar file and referencing it in the library gradle, but it is not deployed in the artifactory repository.
My Gradle library:
apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'com.jfrog.artifactory'
apply plugin: 'maven-publish'
def application = new Application()
class Application {
def packageName = 'com.soufan.integration-lib'
def versionMajor = 0
def versionMinor = 0
def versionPatch = 27
def versionName() {
return (versionPatch > 0 ? "${versionMajor}.${versionMinor}.${versionPatch}" : "${versionMajor}.${versionMinor}")
}
def static gitVersion() {
def process = ['/bin/bash', '-c', 'git rev-list HEAD | wc -l | xargs'].execute()
return process.text.toInteger()
}
}
android {
compileSdkVersion 30
buildToolsVersion "30.0.0"
defaultConfig {
minSdkVersion 22
targetSdkVersion 30
versionCode application.gitVersion()
versionName application.versionName()
testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
consumerProguardFiles "consumer-rules.pro"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
publishing {
publications {
aar(MavenPublication) {
groupId application.getPackageName()
version application.versionName()
artifactId project.getName()
artifact("$buildDir/outputs/aar/${project.getName()}-release.aar")
pom.withXml {
def dependenciesNode = asNode().appendNode('dependencies')
configurations.compile.allDependencies.each { dependency ->
if (dependency.group != null) {
def dependencyNode = dependenciesNode.appendNode('dependency')
dependencyNode.appendNode('groupId', dependency.group)
dependencyNode.appendNode('artifactId', dependency.name)
dependencyNode.appendNode('version', dependency.version)
}
}
}
}
}
}
artifactory {
contextUrl = URL_DEPLOY
publish {
repository {
repoKey = DEPLOY_REPO_KEY
username = USER_NAME
password = API_KEY
}
defaults {
publications('aar')
publishArtifacts = true
properties = ['qa.level': 'basic', 'dev.team': 'core']
publishPom = true
}
}
}
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
implementation 'androidx.core:core-ktx:1.3.0'
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
implementation 'com.journeyapps:zxing-android-embedded:3.6.0'
implementation 'com.squareup.okhttp3:okhttp:4.0.1'
// Dependencies
implementation files('libs/NeptuneLiteApi_V2.04.00_20180329.jar')
implementation files('libs/PPCompAndroid-v1.32.aar')
implementation files('libs/libposdigital-1.5.1-4-release.aar')
implementation files('libs/zoop-emv-connect-pax-a920-pos_0.10.jar')
}
My Project Gradle:
buildscript {
ext.kotlin_version = "1.3.72"
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:4.0.1'
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jfrog.buildinfo:build-info-extractor-gradle:4.10.0"
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}

Error while merging dex archives: Program type already present: org.apache.commons.io.Charsets

I'm trying to release APK in react native using ./gradlew bundleRelease I tried
Cleaning gradle
Adding multiDexEnabled true
FAILURE: Build failed with an exception.
What went wrong: Execution failed for task ':app:transformDexArchiveWithDexMergerForRelease'.
com.android.build.api.transform.TransformException: java.lang.RuntimeException: java.lang.RuntimeException:
com.android.builder.dexing.DexArchiveMergerException: Error while
merging dex archives: Program type already present:
org.apache.commons.io.Charsets Learn how to resolve the issue at
https://developer.android.com/studio/build/dependencies#duplicate_classes.
This is my build.gradle
buildscript {
ext {
buildToolsVersion = "28.0.3"
minSdkVersion = 23
compileSdkVersion = 28
targetSdkVersion = 28
supportLibVersion = "28.0.0"
googlePlayServicesVersion = "11+"
}
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.4.2'
classpath 'com.google.gms:google-services:4.3.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
mavenLocal()
jcenter()
maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
url "$rootDir/../node_modules/react-native/android"
}
maven {
// Android JSC is installed from npm
url("$rootDir/../node_modules/jsc-android/dist")
}
}
}
app/build.gradle
apply plugin: "com.android.application"
import com.android.build.OutputFile
project.ext.react = [
entryFile: "index.js",
enableHermes: false
]
apply from: '../../node_modules/react-native-unimodules/gradle.groovy'
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
buildToolsVersion rootProject.ext.buildToolsVersion
defaultConfig {
applicationId "com.package..."
minSdkVersion 23
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode 33
versionName "33.0"
multiDexEnabled true
}
splits {
abi {
reset()
enable enableSeparateBuildPerCPUArchitecture
universalApk false // If true, also generate a universal APK
include "armeabi-v7a", "x86", "arm64-v8a", "x86_64"
}
}
signingConfigs {
release {
if (project.hasProperty('MYAPP_UPLOAD_STORE_FILE')) {
storeFile file(MYAPP_UPLOAD_STORE_FILE)
storePassword MYAPP_UPLOAD_STORE_PASSWORD
keyAlias MYAPP_UPLOAD_KEY_ALIAS
keyPassword MYAPP_UPLOAD_KEY_PASSWORD
}
}
}
buildTypes {
release {
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, "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
}
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
packagingOptions {
pickFirst '**/libjsc.so'
pickFirst 'lib/x86/libc++_shared.so'
pickFirst 'lib/x86_64/libjsc.so'
pickFirst 'lib/arm64-v8a/libjsc.so'
pickFirst 'lib/arm64-v8a/libc++_shared.so'
pickFirst 'lib/x86_64/libc++_shared.so'
pickFirst 'lib/armeabi-v7a/libc++_shared.so'
}
}
def jscFlavor = 'org.webkit:android-jsc:+'
def enableHermes = project.ext.react.get("enableHermes", false);
dependencies {
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.android.gms:play-services-gcm:17.0.0"
implementation "com.google.android.gms:play-services-location:17.0.0"
//Add these lines
implementation "com.google.android.gms:play-services-base:17.3.0"
//implementation "com.google.firebase:firebase-core:15.0.2"
implementation "com.google.firebase:firebase-messaging:20.2.1"
implementation "com.google.firebase:firebase-inappmessaging:19.0.7"
// implementation "com.google.firebase:firebase-inappmessaging-display:19.0.7"
//implementation 'com.android.support:multidex:1.0.3'
//implementation project(':#mauron85_react-native-background-geolocation')
addUnimodulesDependencies()
if (enableHermes) {
def hermesPath = "../../node_modules/hermes-engine/android/";
debugImplementation files(hermesPath + "hermes-debug.aar")
releaseImplementation files(hermesPath + "hermes-release.aar")
} else {
implementation jscFlavor
}
}
// 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 from: file("../../node_modules/#react-native-community/cli-platform-android/native_modules.gradle");
applyNativeModulesAppBuildGradle(project)
apply plugin: 'com.google.gms.google-services'
Still failing but on my emulator and android device its working fine. Does anyone have this problem too? I really appreciate any idea thanks.

How can I package different *.so files for different Build flavors?

I have some pre-build *.so files for different build flavors like arm64-v8a, armeabi-v7a, x86, x86_64, and these files are of android third party library. When I run the project all these *.so files are packaging in apk. But here my question is that how to package different *.SO files in different apks? can you please give build.gradle script for this. any help will be appreciated? Thank you. Sorry for my poor english.
my library.gradle is
apply plugin: 'com.android.library'
import com.android.builder.core.DefaultManifestParser
android {
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
sourceSets {
main {
jni.srcDirs = []
// Prevent gradle from building native code with ndk; we have our own Makefile for it.
jniLibs.srcDirs = ['jni/libs', 'jni/loader/libs', 'private_libs/libs']
// Where generated .so files are placed.
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
// Make per-variant version code
libraryVariants.all { variant ->
def manifestParser = new DefaultManifestParser(android.sourceSets.main.manifest.srcFile)
// get the version code of each flavor
def version = manifestParser.getVersionName()
//Custom APK name
variant.outputs.all { output ->
if (outputFileName != null && outputFileName.endsWith('.aar')) {
outputFileName = "lib-${version}.aar"
}
}
}
}
class BuildNative extends Exec {}
tasks.withType(BuildNative) {
/*
Properties set for Android Studio own shell.
when you run gradlew from cli, OS shell env variables will be used
To be able to build from Android Studio, you have to set ndk.dir & sdk.dir
properties in local.properties in the root folder, like this (for example):
sdk.dir=/home/<username>/SDK/android-sdk-linux
ndk.dir=/home/<username>/SDK/android-ndk-r10b
*/
if (System.getenv('ANDROID_SDK') == null || System.getenv('ANDROID_NDK') == null) {
Properties properties = new Properties()
properties.load(project.rootProject.file('local.properties').newDataInputStream())
environment 'ANDROID_NDK', properties.getProperty('ndk.dir')
environment 'ANDROID_SDK', properties.getProperty('sdk.dir')
}
workingDir '..'
commandLine './compile-libvlc.sh'
}
task buildDebugARMv7(type: BuildNative) {
args('-a', "armeabi-v7a")
}
task buildDebugARM64(type: BuildNative) {
args('-a', "arm64-v8a")
}
task buildDebugx86(type: BuildNative) {
args('-a', "x86")
}
task buildDebugx86_64(type: BuildNative) {
args('-a', "x86_64")
}
task buildDebugMIPS(type: BuildNative) {
args('-a', "mips")
}
task buildDebugMIPS64(type: BuildNative) {
args('-a', "mips64")
}
task generateSources(type: Jar) {
classifier = 'sources'
from android.sourceSets.main.java.srcDirs
}
clean {
// delete 'build', /*'jni/libs',*/ 'jni/obj'
}
dependencies {
api "com.android.support:support-annotations:$rootProject.ext.appCompatVersion"
api "com.android.support:support-v4:$rootProject.ext.appCompatVersion"
}
and my app.gradle is:
apply plugin: 'com.android.application'
android {
packagingOptions {
}
dexOptions {
maxProcessCount 8
javaMaxHeapSize "2g"
preDexLibraries true
keepRuntimeAnnotatedClasses false
}
compileSdkVersion rootProject.ext.compileSdkVersion
buildToolsVersion rootProject.ext.buildToolsVersion
flavorDimensions "target", "abi"
defaultConfig {
applicationId "com.example"
minSdkVersion rootProject.ext.minSdkVersion
targetSdkVersion rootProject.ext.targetSdkVersion
versionCode rootProject.ext.versionCode
versionName rootProject.ext.versionName
vectorDrawables.useSupportLibrary true
multiDexEnabled true
}
signingConfigs {
release {
storeFile file("D:\\Keystore\\aaaaaaaa.jks")
storePassword "aaaaaaa"
keyAlias "avbbaaaaaa"
keyPassword "ababababa"
}
}
buildTypes {
release {
signingConfig null
minifyEnabled true
shrinkResources false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
lintOptions {
checkReleaseBuilds false
// Or, if you prefer, you can continue to check for errors in release builds,
// but continue the build even when errors are found:
abortOnError false
}
dataBinding {
enabled = true
}
productFlavors {
vanilla {
dimension "target"
versionCode = 1
}
chrome {
minSdkVersion 19
dimension "target"
versionCode = 2
}
ARMv7 {
dimension "abi"
versionCode = 4
}
x86 {
dimension "abi"
versionCode = 5
}
MIPS {
dimension "abi"
versionCode = 6
}
ARMv8 {
dimension "abi"
versionCode = 7
}
x86_64 {
dimension "abi"
versionCode = 8
}
MIPS64 {
dimension "abi"
versionCode = 9
}
}
}
Finally I found out how to do this, I got this solution from https://developer.android.com/studio/projects/gradle-external-native-builds. Hope you also get from something here.
android {
...
defaultConfig {
...
// This block is different from the one you use to link Gradle
// to your CMake or ndk-build script.
externalNativeBuild {
// For ndk-build, instead use the ndkBuild block.
cmake {
// Passes optional arguments to CMake.
arguments "-DANDROID_ARM_NEON=TRUE", "-DANDROID_TOOLCHAIN=clang"
// Sets a flag to enable format macro constants for the C compiler.
cFlags "-D__STDC_FORMAT_MACROS"
// Sets optional flags for the C++ compiler.
cppFlags "-fexceptions", "-frtti"
}
}
}
buildTypes {...}
productFlavors {
...
demo {
...
externalNativeBuild {
cmake {
...
// Specifies which native libraries or executables to build and package
// for this product flavor. The following tells Gradle to build only the
// "native-lib-demo" and "my-executible-demo" outputs from the linked
// CMake project. If you don't configure this property, Gradle builds all
// executables and shared object libraries that you define in your CMake
// (or ndk-build) project. However, by default, Gradle packages only the
// shared libraries in your APK.
targets "native-lib-demo",
// You need to specify this executable and its sources in your CMakeLists.txt
// using the add_executable() command. However, building executables from your
// native sources is optional, and building native libraries to package into
// your APK satisfies most project requirements.
"my-executible-demo"
}
}
}
paid {
...
externalNativeBuild {
cmake {
...
targets "native-lib-paid",
"my-executible-paid"
}
}
}
}
// Use this block to link Gradle to your CMake or ndk-build script.
externalNativeBuild {
cmake {...}
// or ndkBuild {...}
}
}
Include prebuilt native libraries
If you want Gradle to package prebuilt native libraries with your APK, modify the default source set configuration to include the directory of your prebuilt .so files, as shown below. Keep in mind, you don't need to do this to include artifacts of CMake build scripts that you link to Gradle.
android {
...
sourceSets {
main {
jniLibs.srcDirs 'imported-lib/src/', 'more-imported-libs/src/'
}
}
}
Specify ABIs
By default, Gradle builds your native library into separate .so files for the ABIs the NDK supports and packages them all into your APK. If you want Gradle to build and package only certain ABI configurations of your native libraries, you can specify them with the ndk.abiFilters flag in your module-level build.gradle file, as shown below:
android {
...
defaultConfig {
...
externalNativeBuild {
cmake {...}
// or ndkBuild {...}
}
// Similar to other properties in the defaultConfig block,
// you can configure the ndk block for each product flavor
// in your build configuration.
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a',
'arm64-v8a'
}
}
buildTypes {...}
externalNativeBuild {...}
}
By adding this script in app.gradle it works like a charm
ndk {
// Specifies the ABI configurations of your native
// libraries Gradle should build and package with your APK.
abiFilters 'x86', 'x86_64', 'armeabi', 'armeabi-v7a','arm64-v8a'
}
Another solution would be to specify the jniLibs.srcDirs based on your flavor requirements, like this:
android {
...
sourceSets {
def flavor = getCurrentFlavor()
if (flavor == ‘device’ || flavor == ‘production’) {
jniLibs.srcDirs = ['libs']//or whatever path you have
}
...
Where getCurrentFlavor() gets your build flavor name. You can find how to do it here:
How to get current flavor in gradle

Project Gradle sync keeps failing. (Gradle DSL method not found)

beginner android developer so not a lot of experience on how the gradle works, I've tried looking at other examples but I still cant get my problem. Basically, I've just downloaded one of the sample projects from google android developer examples, and cant successfully build the project. I keep getting: Gradle sync failed: Gradle DSL method not found: 'compile()'
The app gradle is:
apply plugin: 'com.android.application'
android {
enforceUniquePackageName = false
compileSdkVersion android_compile_version
buildToolsVersion android_version
defaultConfig {
minSdkVersion android_min_sdk_version
targetSdkVersion android_compile_version
versionCode 1
versionName "1.0"
}
lintOptions {
abortOnError false
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
}
}
}
dependencies {
compile "com.android.support:appcompat-v7:${appcompat_library_version}"
compile "com.android.support:support-v4:${support_library_version}"
compile project(':libraries:BaseGameUtils')
compile 'com.google.android.gms:play-services:4.3.23'
}
buildscript {
repositories {
jcenter()
}
}
and as for the project gradle:
// this is the parent build configuration for all the sample projects.
// for more information on gradle build files when used in a multi-project build, see
// http://gradle.org/docs/current/userguide/multi_project_builds.html
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.3.1'
}
}
// allprojects apply to every project
allprojects {
repositories {
jcenter()
}
ext {
android_compile_version = 23
android_version = '23.0.1'
android_min_sdk_version = 9
appcompat_library_version = '23.0.1'
support_library_version = '23.0.1'
gms_library_version = '8.1.0'
}
}

Categories

Resources