Android Studio Setup For Cordova Mac

Android Studio is an official IDE from Google to develop native Android Apps. But people look for alternatives for developing cross-platform apps, IDE to develop lightweight apps and for rapid app development. Yesterday at GoogleIO, Google announced Android Studio, a new development environment for authoring Android applications. This is a great looking new IDE for Android, based off of IntelliJ IDEA, with some new Android-specific tools and features. You can read more about Android Studio on the Google Android Developers blog.

This guide shows how to set up your SDK environment to deploy Cordovaapps for Android devices, and how to optionally use Android-centeredcommand-line tools in your development workflow. You need to installthe Android SDK regardless of whether you want to use theseplatform-centered shell tools or cross-platform Cordova CLI fordevelopment. For a comparison of the two development paths, see theOverview. For details onthe CLI, see Cordova CLI Reference.

Requirements and Support

Cordova for Android requires the Android SDK which can be installedon OS X, Linux or Windows. See the Android SDK'sSystem Requirements.Cordova's latest Android package supports up to Android API Level 28.The supported Android API Levels and Android Versions for the pastfew cordova-android releases can be found in this table:

cordova-android VersionSupported Android API-LevelsEquivalent Android Version
8.X.X19 - 284.4 - 9.0.0
7.X.X19 - 274.4 - 8.1
6.X.X16 - 264.1 - 8.0.0
5.X.X14 - 234.0 - 6.0.1
4.1.X14 - 224.0 - 5.1
4.0.X10 - 222.3.3 - 5.1
3.7.X10 - 212.3.3 - 5.0.2

Please note that the versions listed here are for Cordova's Android package,cordova-android, and not for theCordova CLI. To determine what version of Cordova's Android package is installedin your Cordova project, run the command cordova platform ls in the directorythat holds your project.

As a general rule, Android versions become unsupported by Cordova asthey dip below 5% on Google'sdistribution dashboard.

Installing the Requirements

Java Development Kit (JDK)

Install Java Development Kit (JDK) 8.

When installing on Windows you also need to set JAVA_HOME Environment Variableaccording to your JDK installation path (see Setting Environment Variables)

Gradle

As of Cordova-Android 6.4.0, Gradle is now required to be installed to build Android.

When installing on Windows, you need to add Gradle to your path, (see Setting Environment Variables)

Android SDK

Install Android Studio. Follow the instructions at the linked Android Developer site to get started.Opening Android Studio for the first time will guide you through the process of installing the Android SDK.

Adding SDK Packages

After installing the Android SDK, you must also install the packages forwhatever API levelyou wish to target. It is recommended that you install the highest SDK versionthat your version of cordova-android supports (see Requirements and Support).

Open the Android SDK Manager (Tools > SDK Manager in Android Studio, or sdkmanager on the command line),and make sure the following are installed:

  1. Android Platform SDK for your targeted version of Android
  2. Android SDK build-tools version 19.1.0 or higher
  3. Android Support Repository (found under the 'SDK Tools' tab)

See Android's documentation on Installing SDK Packagesfor more details.

Setting environment variables

Cordova's CLI tools require some environment variables to be set in order tofunction correctly. The CLI will attempt to set these variables for you, butin certain cases you may need to set them manually. The following variablesshould be updated:

  1. Set the JAVA_HOME environment variable to the location of your JDKinstallation
  2. Set the ANDROID_HOME environment variable to the location of your AndroidSDK installation
  3. It is also recommended that you add the Android SDK's tools, tools/bin,and platform-tools directories to your PATH

OS X and Linux

On a Mac or Linux, you can use a text editor to create or modify the~/.bash_profile file. To set an environment variable, add a line that usesexport like so (substitute the path with your local installation):

To update your PATH, add a line resembling the following (substitute the pathswith your local Android SDK installation's location):

Reload your terminal to see this change reflected or run the following command:

Windows

These steps may vary depending on your installed version of Windows. Close andreopen any command prompt windows after making changes to see them reflected.

  1. Click on the Start menu in the lower-left corner of the desktop

  2. In the search bar, search for Environment Variables and select Edit thesystem Environment Variables from the options that appear

  3. In the window that appears, click the Environment Variables button

To create a new environment variable:
  1. Click New... and enter the variable name and value
To set your PATH:
  1. Select the PATH variable and press Edit.

  2. Add entries for the relevant locations to the PATH. For example(substitute the paths with your local Android SDK installation's location):

Project Configuration

Setting up an Emulator

If you wish to run your Cordova app on an Android emulator, you will first needto create an Android Virtual Device (AVD). See the Android documentation formanaging AVDs,configuring the emulator,and setting up hardware acceleration.

Once your AVD is configured correctly, you should be able to deploy your Cordovaapplication to the emulator by running:

Configuring Gradle

As of cordova-android@4.0.0, Cordova for Android projects are built usingGradle. For instructions on building with Ant, referto older versions of the documentation. Please note that Ant builds aredeprecated as of the Android SDK Tools 25.3.0.

Setting Gradle Properties

It is possible to configure the Gradle build by setting the values of certainGradle propertiesthat Cordova exposes. The following properties are available to be set:

PropertyDescription
cdvBuildMultipleApksIf this is set, then multiple APK files will be generated: One per native platform supported by library projects (x86, ARM, etc). This can be important if your project uses large native libraries, which can drastically increase the size of the generated APK. If not set, then a single APK will be generated which can be used on all devices
cdvVersionCodeOverrides the versionCode set in AndroidManifest.xml
cdvReleaseSigningPropertiesFileDefault: release-signing.properties
Path to a .properties file that contains signing information for release builds (see Signing an App)
cdvDebugSigningPropertiesFileDefault: debug-signing.properties
Path to a .properties file that contains signing information for debug builds (see Signing an App). Useful when you need to share a signing key with other developers
cdvMinSdkVersionOverrides the value of minSdkVersion set in AndroidManifest.xml. Useful when creating multiple APKs based on SDK version
cdvBuildToolsVersionOverrides the automatically detected android.buildToolsVersion value
cdvCompileSdkVersionOverrides the automatically detected android.compileSdkVersion value

You can set these properties in one of four ways:

  1. By setting environment variables like so:

  2. By using the --gradleArg flag in your Cordova build or run commands:

  3. By placing a file called gradle.properties in your Android platform folder (<your-project>/platforms/android) and setting the properties in it like so:

  4. By extending build.gradle via a build-extras.gradle fileand setting the property like so:

The latter two options both involve including an extra file in your Androidplatform folder. In general, it is discouraged that you edit the contents ofthis folder because it is easy for those changes to be lost or overwritten.Instead, these two files should be copied from another location into that folderas part of the build command by using the before_buildhook.

Extending build.gradle

If you need to customize build.gradle, rather than edit it directly, youshould create a sibling file named build-extras.gradle. This file will beincluded by the main build.gradle when present. This file must be placed inthe app folder of the Android platform directory (<your-project>/platforms/android/app), so it is recommended that you copy it over via a script attached to the before_buildhook.

Here's an example:

Note that plugins can also include build-extras.gradle files via:

Setting the Version Code

Studio

To change the version codefor your app's generated apk, set the android-versionCode attribute in the widgetelement of your application's config.xml file.If the android-versionCode is not set, the version code will be determinedusing the version attribute. For example, if the version is MAJOR.MINOR.PATCH:

If your application has enabled the cdvBuildMultipleApks Gradle property (seeSetting Gradle Properties), the version code ofyour app will also be multiplied by 10 so that the last digit of the code can beused to indicate the architecture the apk was built for. This multiplicationwill happen regardless of whether the version code is taken from theandroid-versionCode attribute or generated using the version. Be aware thatsome plugins added to your project (including cordova-plugin-crosswalk-webview)may set this Gradle property automatically.

Please Note: When updating the android-versionCode property, it is unwiseto increment the version code taken from built apks. Instead, you shouldincrement the code based off the value in your config.xml file'sandroid-versionCode attribute. This is because the cdvBuildMultipleApksproperty causes the version code to be multiplied by 10 in the built apks andthus using that value will cause your next version code to be 100 times theoriginal, etc.

Signing an App

First, you should read the Android app signing requirements.

Using Flags

To sign an app, you need the following parameters:

ParameterFlagDescription
Keystore--keystorePath to a binary file which can hold a set of keys
Keystore Password--storePasswordPassword to the keystore
Alias--aliasThe id specifying the private key used for signing
Password--passwordPassword for the private key specified
Type of the Keystore--keystoreTypeDefault: auto-detect based on file extension
Either pkcs12 or jks

These parameters can be specified using the command line arguments above tothe Cordova CLIbuild or run commands.

Note: You should use double -- to indicate that these are platform-specific arguments, for example:

cordova run android --release -- --keystore=../my-release-key.keystore --storePassword=password --alias=alias_name --password=password.

Using build.json

Alternatively, you could specify them in a build configuration file (build.json)using the --buildConfig argument to the same commands. Here's a sample of abuild configuration file:

For release signing, passwords can be excluded and the build system will issue aprompt asking for the password.

There is also support to mix and match command line arguments and parameters inbuild.json. Values from the command line arguments will get precedence.This can be useful for specifying passwords on the command line.

Using Gradle

You can also specify signing properties by including a .properties file andpointing to it with the cdvReleaseSigningPropertiesFile andcdvDebugSigningPropertiesFile Gradle properties (see Setting Gradle Properties).The file should look like this:

storePassword and keyPassword are optional, and will be prompted for if omitted.

Debugging

For details on the debugging tools that come packaged with the Android SDK, seeAndroid's developer documentation for debugging.Additionally, Android's developer documentation for debugging web appsprovides an introduction for debugging the portion of your app running in theWebview.

Opening a Project in Android Studio

Cordova for Android projects can be opened in the Android IDE,Android Studio.This can be useful if you wish to use Android Studio's built in Androiddebugging/profiling tools or if you are developing Android plugins. Please notethat when opening your project in Android studio, it is recommended that you doNOT edit your code in the IDE. This will edit the code in the platforms folderof your project (not www), and changes are liable to be overwritten. Instead,edit the www folder and copy over your changes by running cordova build.

Plugin developers wishing to edit their native code in the IDE should use the--link flag when adding their plugin to the project via cordova plugin add.This will link the files so that changes to the plugin files in the platformsfolder are reflected in your plugin's source folder (and vice versa).

To open a Cordova for Android project in Android Studio:

  1. Launch Android Studio.

  2. Select Import Project (Eclipse ADT, Gradle, etc).

  3. Select the Android platform directory in your project (<your-project>/platforms/android).

  4. For the Gradle Sync question you can simply answer Yes.

Once it finishes importing, you should be able to build and run the app directlyfrom Android Studio. See Android Studio Overviewand Building and Running from Android Studiofor more details.

Platform Centered Workflow

cordova-android includes a number of scripts that allow the platform to be usedwithout the full Cordova CLI. This development path may offer you a greaterrange of development options in certain situations than the cross-platformcordova CLI. For example, you need to use shell tools when deploying a customCordova WebView alongside native components. Before using this development path,you must still configure the Android SDK environment as described inRequirements and Support above.

For each of the scripts discussed below, refer to Cordova CLI Referencefor more information on their arguments and usage. Each script has a name thatmatches the corresponding CLI command. For example, cordova-android/bin/createis equivalent to cordova create.

To get started, either download the cordova-android package fromnpm orGithub.

To create a project using this package, run the create script in the binfolder:

The created project will have a folder named cordova inside that containsscripts for the project-specific Cordova commands (e.g. run, build, etc.).Additionally, the project will feature a structure different from that of anormal Cordova project. Notably, /www is moved to /assets/www.

To install plugins in this project, use the Cordova Plugman Utility.

Upgrading

Refer to this article for instructions to upgrade yourcordova-android version.

Lifecycle Guide

Cordova and Android

Native Android apps typically consist of a series of activities that the userinteracts with. Activities can be thought of as the individual screens that makeup an application; different tasks in an app will often have their own activity.Each activity has its own lifecycle that is maintained as the activity entersand leaves the foreground of a user's device.

In contrast, Cordova applications on the Android platform are executed within aWebview that is embedded in a single Android activity. The lifecycle of thisactivity is exposed to your application through the document events that arefired. The events are not guaranteed to line up with Android's lifecycle, butthey can provide guidelines for saving and restoring your state. These eventsroughly map to Android callbacks as follows:

Cordova EventRough Android EquivalentMeaning
devicereadyonCreate()Application is starting (not from background)
pauseonPause()Application is moving to the background
resumeonResume()Application is returning to the foreground

Most other Cordova platforms have a similar concept of lifecycles and shouldfire these same events when similar actions happen on a user's device. However,Android presents some unique challenges that can sometimes show up thanks to thenative Activity lifecycle.

What makes Android different?

In Android, the OS can choose to kill activities in the background in order tofree up resources if the device is low on memory. Unfortunately, when theactivity holding your application is killed, the Webview in which yourapplication lives will be destroyed as well. Any state that your application ismaintaining will be lost in this case. When the user navigates back to yourapplication, the Activity and Webview will be recreated by the OS, but statewill not be automatically restored for your Cordova app. For this reason, it isimperative that your application be aware of the lifecycle events that are firedand maintain whatever state is appropriate to make sure a user's context in yourapp is not lost when they leave the application.

When can this happen?

Install

Your application is susceptible to being destroyed by the OS whenever it leavesthe sight of the user. There are two main situations in which this can occur.The first and most obvious case is when the user presses the home button orswitches to another application.

However, there is a second (and much more subtle) case that certain plugins canintroduce. As noted above, Cordova applications are usually confined to thesingle activity that contains the Webview. However, there are instances in whichother activities may be launched by plugins and temporarily push the Cordovaactivity to the background. These other Activities are typically launched inorder to perform a specific task using a native application installed on thedevice. For example, the Cordova camera pluginlaunches whatever camera activity is natively installed on the device in orderto take a photo. Reusing the installed camera application in this way makes yourapplication feel much more like a native app when the user tries to take aphoto. Unfortunately, when the native Activity pushes your app to the backgroundthere is a chance the OS will kill it.

For a clearer understanding of this second case, let's walk through an exampleusing the camera plugin. Imagine you have an application that requires the userto take a profile photo. The flow of events in the application when everythinggoes as planned will look something like this:

  1. The user is interacting with your app and needs to take a picture
  2. The camera plugin launches the native camera activity
    • The Cordova activity is pushed to the background (pause event is fired)
  3. The user takes a photo
  4. The camera activity finishes
    • The Cordova activity is moved to the foreground (resume event is fired)
  5. The user is returned to your application where they left off

However, this flow of events can be disrupted if a device is low on memory. Ifthe Activity is killed by the OS, the above sequence of events instead plays outas follows:

  1. The user is interacting with your app and needs to take a picture
  2. The camera plugin launches the native camera activity
    • The OS destroys the Cordova activity (pause event is fired)
  3. The user takes a photo
  4. The camera activity finishes
    • The OS recreates the Cordova activity (deviceready and resume events are fired)
  5. The user is confused as to why they are suddenly back at your app's login screen

In this instance, the OS killed the application in the background and theapplication did not maintain its state as part of the lifecycle. When the userreturned to the app, the Webview was recreated and the app appeared to haverestarted from scratch (hence the user's confusion). This sequence of events isequivalent to what happens when the home button is pressed or the user switchesapplications. The key to preventing the above experience is subscribing toevents and properly maintaining state as part of the activity lifecycle.

Respecting the Lifecycle

In the examples above, the javascript events that are fired are noted initalics. These events are your opportunity to save and restore yourapplication's state. You should register callbacks in your application'sbindEvents function that respond to the lifecycle events by saving state. Whatinformation you save and how you save it is left to your discretion, but youshould be sure to save enough information so that you can restore the user toexactly where they left off when they return to your application.

There is one additional factor in the example above that only applies in thesecond-discussed situation (i.e. when a plugin launches an external activity).Not only was the state of the application lost when the user finished taking aphoto, but so was the photo that the user took. Normally, that photo would bedelivered to your application through the callback that was registered with thecamera plugin. However, when the Webview was destroyed that callback was lostforever. Luckily, cordova-android 5.1.0 and above provide a means for gettingthe result of that plugin call when your application resumes.

Mac

Retrieving plugin callback results (cordova-android 5.1.0+)

When the OS destroys the Cordova activity that was pushed into the backgroundby a plugin, any pending callbacks are lost as well. This means that if youpassed a callback to the plugin that launched the new activity (e.g. the cameraplugin), that callback will NOT be fired when the application is recreated.However, starting in cordova-android 5.1.0, the resume event's payload willcontain any pending plugin results from the plugin request that launched theexternal activity made prior to the activity being destroyed.

The payload for the resume event adheres to the following format:

The fields of that payload are defined as follows:

  • pluginServiceName: The name of the plugin returning the result (e.g. 'Camera'). This can be found in the <name> tag of a plugin's plugin.xml file
  • pluginStatus: The status of the plugin call (see below)
  • result: Whatever the result of the plugin call is

The possible values for pluginStatus in the pendingResult field include the following:

  • 'OK' - The plugin call was successful
  • 'No Result' - The plugin call ended with no result
  • 'Error' - The plugin call resulted in some general error
  • Other miscellaneous errors
    • 'Class not found'
    • 'Illegal access'
    • 'Instantiation error'
    • 'Malformed url'
    • 'IO error'
    • 'Invalid action'
    • 'JSON error'

Please note that it is up to the plugin to decide what is contained in theresult field and the meaning of the pluginStatus that is returned. Referencethe API of the plugin you are using to see what you should expect those fieldsto contain and how to use their values.

Example

Below is a brief example application that uses the resume and pause eventsto manage state. It uses the Apache camera plugin as an example of how toretrieve the results of a plugin call from the resume event payload. Theportion of the code dealing with the resume's event.pendingResult objectrequires cordova-android 5.1.0+

The corresponding html:

Testing the Activity Lifecycle

Android provides a developer setting for testing Activity destruction on lowmemory. Enable the 'Don't keep activities' setting in the Developer Options menuon your device or emulator to simulate low memory scenarios. You should alwaysdo some amount of testing with this setting enabled to make sure that yourapplication is properly maintaining state.

Document your code

Every project on GitHub comes with a version-controlled wiki to give your documentation the high level of care it deserves. It’s easy to create well-maintained, Markdown or rich text documentation alongside your code.

Sign up for free See pricing for teams and enterprises
  • Install Procedure

ORDER MATTERS

Please follow the installation order as it appears.

  • If you encounter issues when editing your path variables, please see this stack overflow post for some good advise as how to prevent this issue.

Android Studio Download For Mac

  1. Download JDK- Java SE Development Kit - Windows x64 - (latest edition) and Install using default options
    1. Add a system variable JAVA_HOME and point it to the directory containing the contents of the JDK (example C:Program FilesJavajdk1.7.0_51)
    2. Add ;%JAVA_HOME%bin; to the Path system variable.
    3. If you have a Proxy Server, note proxy server settings and:
      1. Start --> Type Java Control Panel
      2. General Tab --> Click Network Settings...
      3. Choose the appropriate settings, 'use browser settings' may work for you.
    4. Validate Java Install:
      1. From a command prompt enter the following
      2. You should see something like :
  2. Download Apache Ant and extract to a directory on your computer. (example C:utilant)
    1. Add a system variable ANT_HOME and point it to the directory containing the contents of the ANT directory
    2. Add ;%ANT_HOME%bin; to the Path system variable.
    3. Validate Ant Install:
      1. From a command prompt enter the following
      2. You should see something like :
      3. Troubleshooting: Unable to locate tools.jar (check to see if JAVA_HOME is set properly)
  3. Download Android Studio and Install using default settings.
    1. If you have a Proxy Server, note proxy server settings and open Android Studio:
      1. File --> Settings --> (IDE Settings Section) --> HTTP Proxy
      2. Make the appropriate selection for your environment.
    2. Add a system variable ANDROID_HOME and point it to the directory containing the android sdk that's installed with Android Studio (example: C:UsersjdoeAppDataLocalAndroidandroid-studiosdk)
    3. Add the following to your Path system variable:
      1. ;%ANDROID_HOME%platform-tools;%ANDROID_HOME%tools;
  4. Download Node and Install (if you already have it installed, download and install again to update it)
    1. Clear your NPM cache (this may save some headaches):
    2. If behind a firewall, configure node to speak to the firewall by issuing the following commands:
    3. Validate Node Install:
      1. From a command prompt enter the following
      2. You should see something like :
    4. Update Node & Global Packages
      1. Update Node:
      2. Update Global Packages:
  5. Install Cordova
  6. Install Plugman
    1. If behind a firewall, configure plugman to speak to the firewall by issuing the following commands:

Download Visual Studio Setup For Windows

Create a New Android Project

  1. In a command prompt, Navigate to a folder that will hold the project (example: C:MobileApps)
  2. Create a new project:
  3. Navigate to the new project folder:
  4. Add the Android Platform:

Setup Android Emulator

  1. Bring up android config:
  2. In the packages tree, in the open Android x.x.x (APIxx) ...
    1. Select Intel x86 Atom System Image
  3. In the packages tree, in Extras..
    1. Select Intel x86 Emulator Accelerator (HAXM)
  4. Click the Install Packages button
  5. Agree to any dialogs that come up.
  6. While still in the android config, note the SDK Path, open windows explorer and navigate to that directory.
  7. Navigate to extrasintelHardware_Accelerated_Execution_Manager and run IntelHaxm.exe
  8. While still in the android config, choose tools->manage avds, switch to Device Definitions, select one, Click Create AVD, be sure to choose Intel Atom(x86) for CPU/ABI and in emulation options enable Use Host GPU, choose ok and close out..

Don't Open the project in Android Studio!

  1. When pulling from source control, make sure all files are not read only and run clean.bat in platformsandroidcordova and delete any local.properties files in any directories..this may help relieve headaches!!!

Debugging Android Apps

  1. Choose to debug using an emulator or on a device attached to the computer:
    1. Start and deploy to the android emulator:
    2. Debug using attached android device:
  2. See cordova android debug output:
  3. You can use Google Chrome Development tools to remotely inspect and debug javascript running on the device (KitKat +) or in the emulator. This is just wonderful!
    1. Update the java code to enable remote debugging
    2. Start the ADB server:
    3. Open a new chrome window, enter the following url into the addres bar:
Ignore the following:

Full Studio Setup For Sale

  1. I'm feeling lazy, this page has most of the steps. Just start with the 'Welcome to Android Studio' screen shot and look at the screenshots, just choose the defaults if there's a mismatch, and you'll be good to go.

Studio Setup For Youtube

Clone this wiki locally