Cocos2d-x 3.17 Android Studio - Step By Step Help Requested

I have always used XCode on the Mac for developing Cocos2d-x in C++

I would like to do so on Windows using Android Studio

The instructions I am following from the documentation is either incomplete, refers to old versions or assumes too much knowledge (or maybe all three :wink: - so I just get stuck !

Can someone point me at instructions to create a new empty cocos game then open and execute it in Android Studio?

ā€“ The issue is essentially I donā€™t know Studio - opening the proj.android folder opens what I assume is my project and I see this
image
which if I expand it shows

Do you see the same error with a new ā€œemptyā€ project? Just create a new project and test it. If this also failed, we need to check you Android SDK/NDK configuration.

The example I am using is with a new cocos2d-x project.
If I create a new project in Android studio (fileā€¦newā€¦ new project) then guess agt a few of the options 9like including C++ support) it starts downloading gradle-4.6-all.zip
Then I see

Failed to find Build Tools revision 28.0.2
Install Build Tools 28.0.2 and sync project

I Click on the link to install build tools.

That seems to download jar files(a lot of jar files!)
It then pops up to say

Failed to find Build Tools revision 28.0.2
Install Build Tools 28.0.2 and sync project
So I click on thatā€¦

When that is finished I see

platform-tools package is not installed.
Install the platform-tools SDK package

so click on that link, which starts downloading stuff, but the message just stays thereā€¦

At this point I notice the ā€˜runā€™ button is enabled in teh IDE so click it - it runs and starts an emulator and seems to run the application.

Woo, as they say, hoo!

so open my proj.android again form my cocos project

And see the below

ANY SUGGESTIONS RECEIVED GRATEFULLY!!

So, the ā€œnewā€ project is running, what is great. I would now suggest to compare the two build.gradle (within proj.android and proj.android\app), the local.properties and gradle.propertiea files. They seems to be different.

Thanks for the help with this!
OK, so in my cocos project and Android new project the structure is completely differentā€¦
New APP
image

Cocos App

So I donā€™t really get what to compare!

Each has several build.gradle files
The one in MyApplication/build.gradle is identical to the one in proj.android/build.gradle and Gradle Scripts/build.gradle

The ones in the /app folders are completely differentā€¦

in MyApplication/app/build.gradle
apply plugin: ā€˜com.android.applicationā€™

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.max.myapplication"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cppFlags ""
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:28.0.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}

And in proj./android/app/build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion PROP_COMPILE_SDK_VERSION.toInteger()
    buildToolsVersion PROP_BUILD_TOOLS_VERSION

    defaultConfig {
        applicationId "cocostest"
        minSdkVersion PROP_MIN_SDK_VERSION
        targetSdkVersion PROP_TARGET_SDK_VERSION
        versionCode 1
        versionName "1.0"

        externalNativeBuild {
            if (PROP_BUILD_TYPE == 'ndk-build') {
                ndkBuild {
                    targets 'MyGame'
                    arguments 'NDK_TOOLCHAIN_VERSION=clang'
                    arguments '-j' + Runtime.runtime.availableProcessors()
                }
            }
            else if (PROP_BUILD_TYPE == 'cmake') {
                cmake {
                    targets 'MyGame'
                    arguments "-DCMAKE_FIND_ROOT_PATH=", "-DANDROID_STL=c++_static", "-DANDROID_TOOLCHAIN=clang", "-DANDROID_ARM_NEON=TRUE", \
                              "-DUSE_CHIPMUNK=TRUE", "-DUSE_BULLET=TRUE"
                    cppFlags "-frtti -fexceptions"
                    // prebuilt root must be defined as a directory which you have right to access or create if you use prebuilt
                    // set "-DGEN_COCOS_PREBUILT=ON" and "-DUSE_COCOS_PREBUILT=OFF" to generate prebuilt,  this way build cocos2d-x libs
                    // set "-DGEN_COCOS_PREBUILT=OFF" and "-DUSE_COCOS_PREBUILT=ON" to use prebuilt, this way not build cocos2d-x libs
                    //arguments "-DCOCOS_PREBUILT_ROOT=/Users/laptop/cocos-prebuilt"
                    //arguments "-DGEN_COCOS_PREBUILT=OFF", "-DUSE_COCOS_PREBUILT=OFF"
                }
            }
        }

        ndk {
            abiFilters = []
            abiFilters.addAll(PROP_APP_ABI.split(':').collect{it as String})
        }
    }

    sourceSets.main {
        java.srcDir "src"
        res.srcDir "res"
        manifest.srcFile "AndroidManifest.xml"
        assets.srcDir "../../Resources"
    }

    externalNativeBuild {
        if (PROP_BUILD_TYPE == 'ndk-build') {
            ndkBuild {
                path "jni/Android.mk"
            }
        }
        else if (PROP_BUILD_TYPE == 'cmake') {
            cmake {
                path "../../CMakeLists.txt"
            }
        }
    }

    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 {
            debuggable false
            jniDebuggable false
            renderscriptDebuggable false
            minifyEnabled true
            shrinkResources true
            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
            renderscriptDebuggable true
            externalNativeBuild {
                ndkBuild {
                    arguments 'NDK_DEBUG=1'
                }
            }
        }
    }
}

android.applicationVariants.all { variant ->
    // delete previous files first
    delete "${buildDir}/intermediates/assets/${variant.dirName}"

    variant.mergeAssets.doLast {
        copy {
            from "${buildDir}/../../../Resources"
            into "${buildDir}/intermediates/assets/${variant.dirName}"
            exclude "**/*.gz"
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation project(':libcocos2dx')
}

Any suggestions?

Thanks again for taking the time to lookā€¦

From log it seems it donā€™t see NDK or u using wrong version of it.

File->Project Structure in Android Studio and put path to NDK

Checked it and it looks fine to me??

mmm which NDK version got downloaded there? For me ussualy allowing androii studio to download NDK ending with compile errors - best option download it manually and then point it there.

Also which Java version u have installed? As I know there is issue with 1.9 - should be 1.8

Not sure but could be also local windows variable for NDK not set

Thanks for helpingā€¦

I donā€™t know how to tell which version of NDK I have, how to tell which version of Java I have (I donā€™t recall installing java)
I donā€™t appear to have an NDK environment variable set at allā€¦

Hmmm - have I missed something in setting up Android Studio? Or cocos?

In cocos when u run ./setup.py it should ask for path and set local variables

I would say u have issue with NDk version - download NDK 16 -> unzip and then point android studio to use it - I think it will fix your issue.

Yep, it asks for a path, but I donā€™t know what path to put in - there seems to be nowhere that tells me that requisite piece of information!

Surely ndk is downloaded with Android Studio? (although I canā€™t find it anywhere on my system!!)

I checked and Android Studio has installed ndk 18.0.5002713
But I donā€™t see how to change that anywhere even if I download 16?!

I found how t6o change it, downloaded 16, changed and it rebuilt - but no difference
I also ran setup.py in cocos folder and set the environm,ent variables to point to 16 - still no difference.

Honestly, is it really this hard to set up an Android dev environment for Cocos? SURELY there are some step-by-step instructions somewhere - Iā€™m more than happy to nuke my machine and start againā€¦

Or does nobody us it?

Im using mac os so here probably it little easier.

@Maxxx Which version of Android Studio are you running? If you donā€™t have Android Studio 3.1.4 installed, then download that specific version and install it. It can be installed along side newer versions, so you can have different versions on your computer at the same time.

Here are some screenshots of a working project on Windows with Android Studio 3.1.4:

Android SDK location settings in my project:
image

Using Gradle 4.4 and Android Plugin version 3.1.4

Gradle.properties file contents:

Try to replicate these settings, and see if the project compiles. As mars3142 suggested, please use a new empty project to do this so you can make sure it all works first before trying it on a proper project.

To create a new empty project, please follow the instructions here:
http://www.cocos2d-x.org/docs/cocos2d-x/en/installation/CMake-Guide.html

Thank you all for your help. I am giving up at this point, as I canā€™t find an old download of Android Studio and, frankly, if it is this much of a problem setting up I feel it sinā€™t worth the effort.
Sorry if I sound bitter, but as cocos is meant to be multi platform, finding it takes more than three days to set up a dev environment, is a little hard to take!
Looks like my game will be IOS only ;(

While thinking about it I thought I might try using Visual studio - at least Iā€™m familiar with that.
Then I read the instructionsā€¦
http://www.cocos2d-x.org/docs/cocos2d-x/en/installation/Android-VisualStudio.html
" Cocos2d-x V3.15 or less is the last supported version."
" Make sure that you are using Cocos2d-x v3.12 ."
" * Add any source files and resources that are required to build your project. Change any necessary build settings required by your project.

  • Build and troubleshoot any integration needs."

I know itā€™s deprecated anyway, but really?

Hey @Maxxx I can understand your frustration, we had to go through similar problems.
So we made one txt file with set of rules/steps which need to follow whenever we create new project.
Currently we are using 3.16 C++ and Android-studio version 3.1.4.
Make sure you have android-ndk-r16b downloaded as zip, extract somewhere.
Inside AndroidStudio => Tools => SDK Manager => SDK platforms => Download API 27
Inside AndroidStudio => Tools => SDK Manager => SDK Tools => Upgrade Build-Tools & Platform-Tools

Now below is steps which we follow. Make sure you sync whenever you make any changes.
Try first with helloworld project, let me know if you still face any problems.

1) Add in env variables ANDROID_NDK_HOME

2) gradle.properties =>  make compile version which is installed in your machine
PROP_COMPILE_SDK_VERSION=27
PROP_MIN_SDK_VERSION=15
PROP_TARGET_SDK_VERSION=27
PROP_APP_PLATFORM=19
PROP_APP_ABI=armeabi

3) External build files : Android.mk
please add all your cpp files

4) Also add NDK in Android-studio, go to "File" menu, than "Project Structure->SDK Location" and set the Android NDK Location 

5) If asking for upgrade to latest gradle version, then press 'Remind me tomorrow'
It should be 2.3.3, may be latest will not work.

6) If asking for 'Instant Run' then press 'Proceed without Instant Run'
If you want to disable this (After that it want ask you again for this project), then goto
File -> Settings -> Build, Execution, Deployment -> Instant Run and uncheck Enable Instant Run.

7) If any Lint error comes, then open build.gradle (Module: Gamename), After `sourceSets.main` add this
lintOptions {
	checkReleaseBuilds false
	abortOnError false
}

8) gradle.properties =>  if used v7a than update below line
    PROP_APP_ABI=armeabi:armeabi-v7a
	
9) multidex error: at build.gradle file after versionName add
	i)	// Enable multiDex support.
	        multiDexEnabled true
        ii)  
		dependencies {
			compile 'com.android.support:multidex:1.0.0'
		}
	iii)	in java file:
		import android.support.multidex.MultiDex;
		
		@Override
		protected void attachBaseContext(Context base) {
			super.attachBaseContext(base);
			MultiDex.install(this);
		}
	iv)	manifest
		<application ... android:name="android.support.multidex.MultiDexApplication">
		
10) at run time HeapDumpOnOutOfMemoryError(add 4 line in gradle.properties)

	org.gradle.daemon=true
	org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8
	org.gradle.parallel=true
	org.gradle.configureondemand=true
	
	Notes: if more than one .jar file in cocos/platform/android/java/libs at that time gives error like
	cause: duplicate entry: android/support/annotation/IntegerRes.class
       			to solved
       	remove one android support file

11) Android Studio\jre\bin\java.exe'' finished with non-zero exit value 3
If this error is coming then add below lines into build.gradle before sourceSets.main

dexOptions {
    javaMaxHeapSize "4g"
}

The only reason I mentioned version 3.1.4 of Android Studio is because I was using it, alongside a beta version of 3.2. I just updated to the full release of Android Studio 3.2, upgraded gradle to 3.6, and compiled and built the APK, and it ran fine. There were no issues at all.

There was no special setup to get it working. The only other thing I changed is the PROP_BUILD_TOOLS_VERSION from 27.0.3 to 28.0.2, in the gradle.properties file.

For the time being nothing is stopping you from using Visual Studio 2017 to do all development, which I have found is a LOT lot quicker than using Android Studio. Once your game is working, then worry about loading the project up in Android Studio, and by that time you may have figured out why your specific setup is causing you problems.

1 Like

You misunderstood the big bold text up the top, and all the bits of text your quoted are out of context. Hereā€™s the paragraph in case anyone else reads this:

" Deprecated Document. Cocos2d-x V3.15 or less is the last supported version."

The documentation relating to the previous method of loading projects in Visual Studio is deprecated, not Cocos2d-x Visual Studio support.

The new method is using CMake, as I linked earlier, to create the Visual Studio project. Here it is again:
http://www.cocos2d-x.org/docs/cocos2d-x/en/installation/CMake-Guide.html

Do not use the other site you linked, because once again, itā€™s out-dated and doesnā€™t reflect the current method of creating projects.