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

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

#1

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


#2

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.


#3

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!!


#4

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.


#5

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…


#6

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


#7

Checked it and it looks fine to me??


#8

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


#9

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?


#10

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.


#11

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!!)


#12

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?!


#13

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?


#14

Im using mac os so here probably it little easier.


#15

@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


#16

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 ;(


#17

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?


#18

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"
}

#19

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.


#20

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.