Using Android Studio Beta with Cordova PhoneGap


Article updated here 11/2016: https://iphonedevlog.wordpress.com/2016/11/21/using-android-studio-with-cordova-projects/

I installed Android Studio Beta to see how it currently stacks up against Eclipse. It’s apparent that Android Development Tools for Eclipse is going the way of the dodo and will no longer be updated as vigorously. It’s my impression that Android Studio Beta (AS) is Google’s new SDK to replace Eclipse. We’ll need to learn it sooner or later, so why not now? Here are my notes as I set up the environment and discover the path to creating an apk. These steps track the install and setup of Android Studio down to outputting a signed apk for Google Play upload. 

THIS IS BETA SOFTWARE. Steps you see in this article may not be relevant in later versions.

This article assumes that you will use the default Cordova Android HelloCordova project for the Android platform. It assumes you are already familiar with uploading apps to Google Play (if not, read here for a fuller account of app creation, and add the extra steps as necessary, such as debugging, icons and splash screens: https://iphonedevlog.wordpress.com/2014/06/20/using-cordova-3-5-cli-on-mac-os-x-mavericks-to-build-android-apps/).

AS has instructions for migrating an Eclipse project to AS here: https://developer.android.com/sdk/installing/migrate.html  This article does not follow these steps. These instructions are for a new project that hasn’t been opened in Eclipse.

npm update -g cordova
cordova -v [I got 3.6.3]
cordova create helloCordova
cd helloCordova
cordova platform add android

(When I followed the above steps in the Mac, an error was thrown in the last step above, telling me I need “android-17.” I had to run “android” to open the Eclipse SDK and download those packages. So although we are using Android Studio Beta, Cordova is still wedded to Eclipse for some tasks.)

The steps below chronicles the setup of the above stock Cordova build on Windows and Mac machines. Differences between the two OSs are prefaced in boldface with Windows: and Mac:.

Environments:
Windows 7 Pro, Mac OS 10.9.5
Cordova v3.6.3
Android platform

I. Install Android Studio Beta

1. Download the Android Software Development Kit here: http://developer.android.com/sdk/installing/studio.html The page will detect whether you are using the Windows or Mac OS and present the correct download button.
My initial Windows version included Beta v0.8.6. It was later updated to 0.8.9.

From Android page for Windows users:
“On some Windows systems, the launcher script does not find where Java is installed. If you encounter this problem, you need to set an environment variable indicating the correct location. Select Start menu > Computer > System Properties > Advanced System Properties. Then open Advanced tab > Environment Variables and add a new system variable JAVA_HOME that points to your JDK folder, for example C:\Program Files\Java\jdk1.7.0_21. The individual tools and other SDK packages are saved within the Android Studio application directory. If you need to access the tools directly, use a terminal to navigate into the application and locate the sdk/ directory. For example: \Users\<user>\AppData\Local\Android\android-studio\sdk\”

2. Windows: program files are set up in C:/Users/<name>/.AndroidStudioBeta and C:/Users/<name>/.android  Space required: 686.2MB for the .exe download.
Mac: after you click on the download file in your browser to open the dmg containing folder, you drag Android Studio.app into /Applications (646.3MB).

3. AS asks if you want to import settings from a previous version. I chose the second option, to not import, as this was a new install.

II. Android Studio Beta startup

1. On startup, AS shows a Welcome screen with several choices. Click on Open Project, select the root folder of your Cordova PhoneGap project, then OK.

What happens if you choose Import Project or New Project instead of Open Project? You won’t get the menu items that let you build a final apk or choose an AVD or SDK; specifically, Generate Signed APK and Build > Android. My notes below:

Choosing Opening Screen’s Import Project… (same as File > Import Project…) for a Cordova project which has never been opened in AS before does not display these menu items. It preserves the Cordova folder structure.

Choosing Opening Screen’s New Project… (same as File > New Project…) DOES display these menu items. (It creates a Gradle folder structure – not useful for cross-platform use.)

Choosing Opening Screen’s Open Project… (same as File > Open) for a Cordova project which has never been opened in AS before DOES display these menu items. It preserves the Cordova folder structure. A message says that a framework was detected. Click on Configure then OK in the Setup Framework popup. Then the missing menu items display.

2. A message says that a framework was detected. Click on Configure then OK in the Setup Framework popup. If you do not click on Configure then OK, you won’t be able to generate a signed apk from with AS. Important menu items will not be made available. If this message disappears before you can click on it, go to View > Tool Windows > Event Log to select it.

3. AS shows a blank gray screen with text tips in the middle, then opens the left Project panel where our imported project is listed. We are also greeted with a Tip of the Day. (The text tips don’t all work. For instance, tap on Shift twice, and an input box appears. Type “avd” and AVD Manager appears as a result. But nothing happens when you click on it.)

In some cases, with a fully developed project imported, AS presents an import-summary.txt showing what was NOT imported, asking whether they need to be imported manually. That listing was composed of various txt, jar, and bat files.

4. Windows: through a popup at the lower left AS screen, we are told to hover our mouse over the icon; doing so brings up a menu. You can find this same listing under View > Tool Windows. To return to the Projects listing, click on Projects in that menu or press the Alt + 1 keys together.

Our Windows project files are set up in C:/Users/<name>/AndroidstudioProjects

Mac: Hover over the extreme lower left icon and click on each of the menu items in the list that pops up. End on the Projects link. You can find this same listing under View > Tool Windows.

Our Mac project files are probably set up in the helloCordova project folder in the hidden folder, .idea. You can see the folder in AS’s Projects window.

III. Update and install packages: SDK Manager

1. In the lower band of the screen was a notice that a new version of AS is available. Let’s take care of that before going further.
Windows: go to Help > Check for Update… in the menubar above. Click on Update and Restart.
Mac: go to Android Studio > Check for Updates… in the menubar above. Click on Update and Restart.

2. We need to download and install several packages to make the download complete.
Windows: in AS, click on Tools > Android > SDK Manager in the menubar. (In my later version, the Android menu item went missing.)
Mac: in AS, click on the upper left red Exit button. The Welcome screen shows. Click on Configure > SDK Manager.

3. Keep the default selections checked. Make sure the following are checked in Tools: Android SDK Tools, Android SDK Platform-Tools, Android SDK Build-tool (highest version).

Make sure the following are checked in Android x.x (latest version): SDK Platform, ARM EABI v7a System Image.

In the Extras directory, check: Android Support Library. The Repository might already be installed; if not, check it.

To develop with Google APIs, Google Repository and Google Play service should be checked under Extras.

Check this line in your /platforms/android/AndroidManifest.xml: <uses-sdk android:minSdkVersion=”19″ android:targetSdkVersion=”22″ /> and download the “target” packages as well, in this case 19 (Android 4.4.2) and 22 in the SDK. Choose whatever packages you will be testing with.

Click on the Install X packages… button. Click on each main folder and accept the licenses to continue.

Go ahead and get a refill. Installing those packages will probably produce another list of packages to install just when you thought you were finished!

You may receive a message in the upper right asking if you want Google to gather usage stats and how often. You can go to File > Settings… > Usage Statistics to update this.

3. If you want to change the default SDK, you now can.  

Windows: Go to File > Project Structure…, SDKs. Click on the Build Target, navigate to C:/Users/<name>AppData/Local/Android/android-studio/sdk/platforms, and choose the SDK you want to be the default. Change the name to update it. Then click Apply and OK.

Mac: Go to File > Project Structure…, SDKs. Click on the Build Target, navigate to Macintosh HD/Applications/Android Studio.app/sdk.build-tools, and choose the SDK you want to be the default. Change the name to update it. Then click Apply and OK.

IV. Explore the Program

1. To do a code lint on your project, select the project name and Analyze > Inspect Code. Select Whole Project and click OK. Results will appear below neatly categorized. Clicking on exclamation point symbols will show more information and links about it. Drill down to Spelling > www and see if any spelling errors are critical in your own files.

2. Want to change to a darker color scheme? Click on View > Quick Switch Scheme… > Switch Look and Feel… > Darkula.

3. To update the files in AS after you made changes to the original files, right-click on the project name, then on  Synchronize ‘<helloCordova>’. However, you shouldn’t have to do this, as AS syncs on the fly. You can check this by opening the /www/index.html in AS to view it, then open the original file and delete all the comments at top. Save, then review the updated file in AS.

4. You can change the styling of your HTML in AS.
Windows: File > Settings > Code Style > HTML. See also Preferences > Editor.
Mac: Android Studio > Preferences > Code Style > HTML. See also Preferences > Editor.

5. You can decide what aspects of your files AS should or should check with Inspections.
Windows: File > Settings > Inpsections, Android, Android Lint.
Mac: Android Studio > Preferences > Inpsections, Android, Android Lint.

6. Register your version control system.
Windows: File > Settings > Version Control
Mac: Android Studio > Preferences > Version Control

7. Set up your external image editor.
Windows: File > Settings > Images.
Mac: Android Studio > Preferences > Images.

If you double-click on an image in your project (such as /www/img/logo.png) it will open in the Editor pane. Right-click on the image and select Jump to External Editor to open it in the editor you specified.

8. Improve startup speed by disabling plugins you won’t use or need. Restart AS to enable changes.
File > Other Settings… > Configure Plugins…

9. Show line numbers in Editor.
Windows: File > Settings > Editor > Appearance, Show line numbers.
Mac: Android Studio > Preferences > Editor > Appearance, Show line numbers.

10. If you navigate to /www/index.html and double-click on the file, it’ll open in AS’s Editor pane. Move your cursor over the page and icons of installed browsers will appear in the upper right of the pane. Clicking on one will open the page in that browser. View > Open in Browser… will do the same thing.

11.  Create a 9-Patch file from within AS. Navigate to your .png image (already saved to your project) in the Project window, right-click and choose Create 9-patch file…, and rename extension as .9.png. Double-click on a 9.png file in the Project window to open it in the 9-Patch editor within AS and add your marks around the edge. Saving is automatic. (https://iphonedevlog.wordpress.com/2013/07/02/creating-and-installing-a-splash-screen-for-android-using-eclipse-and-phonegap/)

If you open a finished project and your 9-patch file is faulty, Code > Analyze will point this out as one of your errors/warnings. Double-clicking on the image, you’ll be able to fix it right in AS.

12. You can use the terminal from within AS. View > Tool Windows > Terminal. You can perform Cordova and Phonegap commands on your project there.

13. Google wants your feedback on bugs found in the program: Help > Submit Feedback. This takes you to a web site. On that site, it’s wise to do a search of keywords related to the problem first.

14. Occasionally you’ll get a popup asking if you want to convert the project to Gradle. (Gradle is a build and automation system. Automates the building, testing, publishing, deployment, etc., of software packages or other types of projects.) A benefit of using Gradle is making multiple build versions in a project. You create several versions, but build each one separately.

15. Create your own keyboard shortcuts.
Windows: File > Settings > Editor > Keymap.
Mac: Android Studio > Preferences > Editor > Keymap. For Mac OS X keymap: Help > Default Keymap Reference (displays a PDF in the browser).

16. Quickly create a new file. In AS Project view, click on the /www directory, then Windows Alt + Insert or Mac Command + N to choose the file type and type the filename.

V. Create an Unsigned Apk

To build a debug apk (the file we use to test with) or a signed apk (what is uploaded to Google Play), we need Ant installed and in the PATH statement. If you already have that, then in Android Studio do the following steps.

1. Make sure the code is correct before making an apk file:

Analyze > Inspect Code…

(When running this command on a previously created app for an update to an app, this step resulted in 5 errors I’ve never encountered before.)

2. To create the unsigned apk in AS: View > Tool Windows > Terminal.

3. Make sure your starting position is within your project’s root folder of /helloCordova and run:

cordova build android

This creates the familiar debug apk files in /helloCordova/platforms/android/ant-build (check your Projects view window). I successfully installed helloCordova-debug.apk on my device and it displayed PhoneGap’s icon and Device Is Ready message.

VI.a Create a Signed Apk (Android Studio)

1. To create the signed apk for upload to Google Play:

Build > Generate Signed APK… . The module should be Android. Next.

2. Choose Create New… and fill out the Generate Signed APK Wizard form. Do not use illegal characters in the code, such as a comma, semi-colon, colon, quote marks, plus, or slash.

Key store path: click on the dropdown button and choose a location for the keystore file, then type in the filename for the keystore file. (The keystore file needs to be backed up and kept safe – it’s required to have on hand to make new versions of the same app.) I usually make the filename the same name of my app, without spaces. For some reason, this file ends in .jks and not the familiar .keystore.

Alias: use the name of the app, without spaces, if you wish.

Password, Confirm: create a password and note it carefully so you’ll use it and the jks keystore file together at a later date.

Validity (years): overwrite the 25 with 50.

Fill out the rest of the fields. For 2-letter country code, look up this list: http://www.worldatlas.com/aatlas/ctycodes.htm

3. Choose Next in the  next dialog.

4. In the next dialog, choose where you want your signed apk file to be saved. Default is /HelloCordova/platforms/android/android.apk. It will be saved with the filename android.apk; to change the name and location, click the dropdown button and choose the location at top and name at bottom. Clicking OK will bring you to the previous dialog with the updated information.

5. Check the Run ProGuard checkbox, then Finish. Your signed apk file should be in the location you specified.

VI.b Create a Signed Apk (CLI)

Follow these steps if the above VI.a does not work for you. I had problems with the Build > Generate Signed APK…  menu item being grayed out or not appearing in my earlier efforts. These steps will remain for the record.

Resource: http://www.intown.biz/2014/07/15/signing-your-cordova-android-app/

1. To create the signed apk in AS via CLI: View > Tool Windows > Terminal.

2. Make sure your starting position is within your project’s root folder of /helloCordova and run:

keytool -genkey -v -keystore hellocordova.keystore -alias hellocordova -keyalg RSA -keysize 2048 -validity 10000

Answer the questions at each prompt. For 2-letter country code, look up this list: http://www.worldatlas.com/aatlas/ctycodes.htm

3. If any of the information is wrong, type the two letters to re-enter that information. For instance, cn to change your first and last name. Confirm the information by typing “yes”.

4. Return if the password for the following information will be the same as the previous info (hit enter).

Your keystore file is saved at /helloCordova/hellocordova.keystore. Get the full path for use later: /Users/path/helloCordova/hellocordova.keystore (I grabbed my path by dragging the hellocordova.keystore file from the Finder window into the Terminal app.)

5. In Android Studio, Project view, double-click on hellocordova.properties.

6. Add two lines at the end (the file will be saved automatically):

key.store=hellocordova.keystore
key.alias=hellocordova

7. In AS, Project view, double-click on helloCordova/platforms/local.properties.

8. Add two lines to this file, even though it says, “This file is automatically generated. Do not modify this file – YOUR CHANGES WILL BE ERASED!”

key.store=<path to keystore file>/hellocordova.keystore
key.alias=hellocordova

The script will pause and you’ll be prompted for the password twice and it will not be obfuscated.

9. In AS, View > Tool Windows > Terminal, run:

cordova build android --release

10. Your hellocordova-release.apk file, signed and zip-aligned, is put in /helloCordova/platforms/android/ant-build (check your Projects view window). This is the file you upload to Google Play.

Observations on opening an app previously released to Google Play and updating it in AS:

When I opened an app in AS to update it to a new version, then Analyze > Inspect Code generated several errors. I was not able to resolve all of them. (For instance, it complained in the AndroidManifest.xml that it could not find the resource for @drawable/icon. I tried several permutations of the path to no effect.) When I have resolved this to my satisfaction, I’ll include a workflow in this spot for updating a current app. That would make the article more complete. I’m surprised at the number of things I had to change to make it work this far. Stay tuned. (Long-time readers know that I update my articles rather than post mini-blogs about updates. I don’t want to hunt all over the blog to find out how to do something and neither do you. Unfortunately, I don’t think you’ll get email updates for these little additions.)

VII. Configure an emulator: AVD Manager

I recommend using a real device for checking your work rather than using the onscreen device emulator – it’s way faster and more accurate.

1. We’ll configure a sluggish emulator called an AVD, or Android Virtual Device.
Windows: Tools > Android > AVD Manager.

Sometimes the menu item Android in Tools > Android appears, sometimes it doesn’t; I suspect it is a contextual issue, but haven’t found out what triggers it on and off. 

Windows: when I did my first project, I needed only to open Tools > Android > AVD Manager. But for this stock Cordova project, the Tools menu did not include an Android menu item in its list — I assume it was removed when updating to 0.8.9. I clicked on Help > Find Action… and typed in “avd,” then “AVD Manager” appeared as a result. Double-clicking on it resulted in nothing happening. A bug for sure.

Mac: click on the red Exit button in the upper left to return to the Welcome screen (it doesn’t shut down AS). Click on Project Defaults > Run Configurations. Click on Defaults to open the folder, then Android Application. Under Target Device, click on the “…” button next to Prefer Android Virtual Device. That will start the AVD Manager. (I’ve never gotten the selected AVD to appear in the Prefer Android Virtual Device drop-down.)

2. Click on the Device Definitions tab to see the preformatted AVDs. Choose the ones you are interested in. For our purposes, and to keep the download times short, we’ll just choose Nexus 7 (2012), then click on the Create AVD… button.

3. The Create new AVD dialog appears. The lower edge cut off the rest of the information and there are no scrollbars, so grab the lower edge and extend until you see the Cancel button.

4. For Target: choose Google API 17.
For CPU/ABI: choose ARM (not sure if this is best).
For Back Camera: Emulated.
For Skin: No skin.
Click OK, OK.

5. The AVD Manager displays the device we just set up. Close the dialog/window.

Windows: the AVD device info is added to C:/Users/<name>/.android/avd
Mac: the AVD device info is added to /Users/<name>/.android/avd

You’ll notice I don’t give instructions for the use of the emulator. That’s because although I configured an AVD, the emulator never showed the app. It only showed the home screen of the device. (“Unfortunately, Launcher has stopped.”) Perhaps my above AVD settings are wrong. An earlier version gave device startup and logcat information — then the upgrade left these out! When I have it working properly, I’ll update this page.

New terms I came across as I was learning about Android Studio

DSL (Domain Specific Language)
http://en.wikipedia.org/wiki/Domain-specific_language

Gradle (Gradle is a build and automation system. Automates the building, testing, publishing, deployment, etc., of software packages or other types of projects. This build language is based on Groovy, with some additions to make it easier to describe a build.)
http://www.gradleware.com/android/gradle-the-new-android-build-system/
http://www.gradle.org/docs/current/userguide/userguide_single.html
http://en.wikipedia.org/wiki/Gradle
http://developer.android.com/sdk/installing/studio-build.html

Groovy (dynamic language for the Java Virtual Machine; a plugin that compiles projects)
http://groovy.codehaus.org/

IntelliJ IDEA (Java IDE that AS uses)
http://en.wikipedia.org/wiki/IntelliJ_IDEA

JetBrains (created IntelliJ)
https://www.jetbrains.com/

Maven (packages dependencies; better than ant)
http://maven.apache.org/
http://search.maven.org/
http://spring.io/guides/gs/maven-android/

14 thoughts on “Using Android Studio Beta with Cordova PhoneGap

  1. Thanks, Steve! This is absolutely the most useful info I’ve been able to find anywhere, regarding integrating Cordova projects into Android Studio. Like many of us, I’ve been on the Android SDK/Eclipse for years, though with Android Studio coming out of Beta last week, I’m making the move for ALL Android dev now. That said, I’m thinking you might want to change your title of this article to not specify Beta. I’m about to try your method out on the non-Beta version that just went live last week…

    Best regards,

    Mike

  2. I appreciate this article, but it really does not address integrating Cordova with an Android Studio Gradle project at all, which is a significant gap in the context of Android Studio.

  3. Hi Steve, Thanks for your articles, I’ve referenced them a lot in the past.

    I’m having an issue with a cordova android project that I can’t seem to get around. I’ve been following this tutorial to try to build an app that is already released on iOS for Android but I alway run into the same error when I get to “cordova build android”. I’ve tried everything I can find on stack overflow and other places but it’s always the same.

    I noticed you got the same error in another post you wrote:

    Signing an Android Apk via CLI


    Error code 1 for command: ant with args: … command failed with exit code 8

    I tried what you suggested (cordova platform remove android, cordova platform add android) and still the same error.

    Any ideas how I can fix this?

    Thanks

    Here’s the rest of my error log:

    BUILD FAILED
    /Users/owenroberts/Library/Android/sdk/tools/ant/build.xml:653: The following error occurred while executing this line:
    /Users/owenroberts/Library/Android/sdk/tools/ant/build.xml:698: null returned: 1

    Total time: 2 seconds

    /Applications/cordova/lostly/platforms/android/cordova/node_modules/q/q.js:126
    throw e;
    ^
    Error code 1 for command: ant with args: debug,-f,/Applications/cordova/lostly/platforms/android/build.xml,-Dout.dir=ant-build,-Dgen.absolute.dir=ant-gen
    Error: /Applications/cordova/lostly/platforms/android/cordova/build: Command failed with exit code 8
    at ChildProcess.whenDone (/usr/local/lib/node_modules/cordova/node_modules/cordova-lib/src/cordova/superspawn.js:135:23)
    at ChildProcess.EventEmitter.emit (events.js:98:17)
    at maybeClose (child_process.js:735:16)
    at Process.ChildProcess._handle.onexit (child_process.js:802:5)

    • As you see with your own research, there are a number of success stories at fixing this problem, and I was blessed to have found so simple a solution among them. I’m in the dark as to what to suggest to you. Can you post your steps in Stackoverflow.com for a solution?

      • Thanks for the reply. I finally got it working by creating a new project and copying all of the files into that project… Probably should have been the first thing I tried : /

  4. Hi Steve, thanks for the write up.
    I managed to all that setup and generate the Hello app and ran it on the Android emulator fine.
    But then I thought why? What advantage due you on using AS over any other IDE if at the end you have to drop to CLI the build the app?

    • When I wrote the article, that was the state of the art of using PG with AS – not much of an advantage! An AS engineer wrote and told me that AS 1.0 was not taking 3rd-party programs into consideration at the time. They’ll work on PG integration after 1.0.

  5. hii steve,
    im building app in android studio and i want to connect it with a wordpress panel to management and update the content and app use wordpress host and database.if you know the answer or any solution i will be greatful to know it.plz its so important for me

    • I don’t understand. You can open Chrome on the device, enter your WordPress site, sign in, and use the panel, right? So you can simply provide a button in your app that points to your panel, where you’ll sign in to use it.

      • no,i don’t need any wordpress site,i want to build android app with android studio and use wordpress to update app content.and also the host and datab base of app and wordpress sholud be one.I hope I explained correctly

      • You’ll need to ask this question on Stackoverflow.com. I have no experience with using WordPress to update an app. In addition, I don’t believe the way you’ve worded your question is clear enough. You simply want a post in WordPress to update on the app? If that’s not it, then like I said, you are not clear about what you are really trying to do.

  6. Pingback: Making an Android App Bundle .aab file from a Cordova project | iPhone Dev Log

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.