Category Archives: PhoneGap

Installing Crosswalk in an Older PhoneGap Project

08 Sep 2015

Starting with Android 5.0 the webview has been separated from the OS and is now itself an app that will receive updates like any other app. The implication here is that from Android 5.0 and up users won’t have to receive an OS update to get better webviews for PhoneGap apps to use, they can now download and install WebView updates separate from the OS.

All fine and good – in the meantime older Android versions still have the webviews that shipped with the OS / device. OS updates don’t happen very often, typically only occurring when someone gets a new phone or until the device manufacturer decides to issue an update. In even rarer instances a device might be updated if it is rooted and a custom ROM is applied.

Until recently this meant that PhoneGap developers would still have to deal with the various webkits that their apps may encounter and whatever features might be lacking (The most infamous example of a lacking feature that comes to mind was the completely missing toDataURL() canvas method a few years ago.)

Given all the different Android devices in the wild it is sometimes quite a task for developers to be able to create hybrid apps that behave predictably in all the different webkit flavors. The Crosswalk plugin addresses this issue by embedding a web runtime in your Android apps (Android 4 and up) meaning that you don’t need to worry about the version of webkit on older Android OS’s as you now have an modern embedded Chromium under the hood giving you a consistent environment for your apps to execute within.

Today I’m trying to update an older app of mine so that it will use Crosswalk and I hit an issue that prevented me from installing it. The error:

“Plugin doesn’t support this project’s cordova-android version. Cordova-android: 3.6.3, failed requirement: >=4”

corsswalk_1

The first thing to be aware of is that the CrossWalk plugin requires Android 4. While searching online revealed some hacks to force Crosswalk to install that wasn’t something that I wanted to do.

My first instinct was to edit the manifest.xml since I recall from having previously used Eclipse to compile my apps that that would be the course of action to take. Unfortunately as you may know the Eclipse ADT no longer works with Eclipse and the latest SDK’s so thats not something I want to try and get working since the Cordoca CLI makes compiling a lot easier.

Anyway, editing the manifest.xml didn’t seem to have an effect as rebuilding did nothing and trying to re-add the platform resulted in the “Platform android already added” error message. Searching online revealed a few hacks that could be done and seems to have worked for some people but I didn’t want to pursue any hacky methods so I stopped bothering with trying to use my current project files.

In the end I decided to rebuild my PhoneGap project and target a specific version of Android so as to meet Crosswalk’s requirements. The takeaway is that yes, you’ll have to rebuild and wont be able to install CrossWalk for apps targeting pre Android 4 devices.

The easiest way to rebuild the project to target more recent versions of Android is to simply delete the Android folder out of the project and then rebuild it. While a wholesale delete works a cleaner method (presumably) is to issue the CLI command to remove the platform. Either way you don’t have to worry about reinstalling all of your plugins as Cordova will detect their prior installation and install them all for you when the new target platform is created.

So then, I deleted the Android folder using the CLI via this command…

  • cordova platform remove android

…and then reinstalled Android making sure to target a specific version using this syntax:

  • cordova platform add android@x.x.x

Where the @x.x.x represents the desired version of the OS.

An easy way to see what version numbers will work is to try to create an Android project with a version that doesn’t exist. Try Android 4.2 and Cordova will of course fail the attempted platform add but also show you the valid version numbers / install targets that it expects.

corsswalk_2

That’s a nice reference – I decided to go for Android 4.1.1 JellyBean.

  • cordova platform add android@4.1.1

In the image below you can see the result of the install followed by a list of all the installed plugins – note that it happened on its own since if you were to look in the project folder all the plugins are there – all we did was delete the platform so Cordova still knows what plugins to install.

corsswalk_3

A quick build showed my app working – all done!

Installing The SQLite PhoneGap Plugin via the CLI

30 Apr 2014

For some reason I had issues trying to install the PhoneGap SQLite plugin for Android on my Windows 8.1 laptop using the CLI. Attempting to run the install resulted in a Command failed: fatal: could not create work tree dir error. After some fruitless searching for a solution I took another look at the error message and thought that maybe the problem would be something simple to resolve.

This type of CLI command usually works:

$ phonegap plugin add https://github.com/brodysoft/Cordova-SQLitePlugin.git

As mentioned this resulted in the following error:

sqlite_npm_install

 

The key to solving this is in the error message – apparently the temp path can’t be created…. so… create it!

Using Explorer navigate to this path:

  • C:\Users\[YOUR USER NAME]\AppData\Local\Temp

 
Note that “AppData” is likely a hidden folder – just enter the path (use your own user name where appropriate). For example:

 

sqlite_npm_install_path

 

Once in the Temp folder create the necessary directories to recreate the following path:

  • C:\Users\[YOUR USER NAME]\AppData\Local\Temp\plugman\git

 
And once again run the CLI command for installing the plugin. This time everything runs without error:

 

sqlite_npm_install_success

 

Disable Android Back Button in InAppBrowser

21 Apr 2014

This is a quick hit – if you’re using the InAppBrowser plugin in your PhoneGap app on Android you may want the child browser to display without the location bar and the included “close” button. The PhoneGap docs explain how to do this well enough, however Android’s back button is still functional. If you tap it enough you will eventually shutdown the child web view which may not be what you wanted to happen.

You could try to over-ride the default behavior by creating an event listener for the backbutton event but once InAppBrowser launches it handles the back button on its own. The backbutton event won’t fire until **after** the InAppBrowser child view has closed which of course is too late for our purposes.

An easy way to solve this is to just comment out the InAppBrowser function that handles the backbutton behavior. Locate InAppBrowser.java in your project and search for a function called closeDialog. Once you locate it just wrap a c-style comment around the body of the function and save.

If in addition to preventing the web view from shutting down you also want to have the back button function like a web browser’s back button then you need to be a little more precise with your edit. As before, locate the closeDialog. It should look like the code sample below – note the changes:

  • Line 16: Comment out this line
  • Line 23: Comment out this line
  • Line 24: add the following: childView.goBack()
    public void closeDialog() {

        final WebView childView = this.inAppWebView;
        // The JS protects against multiple calls, so this should happen only when
        // closeDialog() is called by other native code.
        if (childView == null) {
            return;
        }
        this.cordova.getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                childView.setWebViewClient(new WebViewClient() {
                    // NB: wait for about:blank before dismissing
                    public void onPageFinished(WebView view, String url) {
                if (dialog != null) {
                    //dialog.dismiss(); // COMMENT OUT THIS LINE
                }
            }
        });
                // NB: From SDK 19: "If you call methods on WebView from any thread 
                // other than your app's UI thread, it can cause unexpected results."
                // http://developer.android.com/guide/webapps/migrating.html#Threads
                //childView.loadUrl("about:blank"); // <<< COMMENT OUT THIS LINE
	        childView.goBack(); // <<< ADD THIS LINE
            }
        });

        try {
            JSONObject obj = new JSONObject();
            obj.put("type", EXIT_EVENT);
            sendUpdate(obj, false);
        } catch (JSONException ex) {
            Log.d(LOG_TAG, "Should never happen");
        }/**/
    }

This worked for me on my HTC One M8 - but, I'm not a Java Developer so please look at the above with a critical eye. Let me know in the comment section below if you have changes to whats here!

Error Installing NPM Package

09 Apr 2014

I was setting up a Mac today for PhoneGap development and I ran into this error message while attempting to install Ripple:

  • npm ERR! Please try running this command again as root/Administrator

npm_install_err_01

The solution is to change ownership of everything in /usr/local to the current user via the terminal:

  • sudo chown -R $USER /usr/local

You’ll be asked for your password after which the relevant files will be changed. As can be seen in the following image I succesfully executed the command and thereafter didnt have any issues installing Ripple.

npm_install_err_02

Android 4.1.2/PhoneGap 3 AdjustPan with Fullscreen Theme

17 Mar 2014

If you’re reading this you’ve been stung by the AdjustPan bug in PhoneGap – this is where the softkeyboard appears when one of your text fields gets focus but the view does not shift up to reveal the field that you’re attempting to type into. Setting the windowSoftInputMode in your application manifest to “adjustPan” should in theory accomplish this. Apparently no amount of XML / main activity settings will create the desired result so the average PhoneGap dev – one who is not a Java Developer – has to rely on whatever work-around the community decides to share.

Go here to read about the expected behavior of windowSoftInputMode’s “AdjustPan” setting. You may also want to read about the bug. Various posts I have read say that this bug seems to manifest itself because PhoneGap is running fullscreen (using a Fullscreen Theme).

To be honest, I *have* seen this work in an older project so it must be something that was introduced to Android after my last viewing of it.

In any event the community at large has provided a fix – after some Googling I came across this StackOverflow post:

http://stackoverflow.com/questions/19849462/phonegap-android-how-to-adjust-layout-in-full-screen-mode-when-softkeyboard-is

The above gives enough directions to get started though some small points are left out. The missing step-by-step is why I’m posting today – I’m going to walk through the entire process and to touch briefly on the variant of the fix also posted in the above link.

app_adjust_pan_compressed

The “AndroidBug5497Workaround” & “AdjustInputHeight” Java Classes

“AndroidBug5497Workaround” is the name of the class that defines the first fix. It works as advertised and in fact performs better than the variation of it on my Samsung Galaxy S2 (Android 4.1.2). This fix will bump up the display immediately with no delay or animation. The view stays shifted upwards revealing the element with focus until the keyboard is put away where the view then returns to normal.

The second example, a variation of the first, animates the view up but has a bug that shifts the view down to its default position after the first keystroke. Thereafter, it works fine. Again, I found the first example to be more reliable and in fact preferable to animating the view.

If you’re curious you can implement the second one and play with the animation time setting – look for the number “500” in the source. I assume it represents milliseconds.

How To Implement

Navigate to the root of your project

Locate your “src” folder. In a PhoneGap 3 Project it would be here (substitute the bracketed text for your own project-specific values):

  • projects\[APP NAME]\platforms\android\src\com\[NAMESPACE]\[APP NAME]

Or in Eclipse you might find the “src” folder in the Package Explorer.

Once you locate your “src” folder you should be looking at your main activity java file – we’ll be giving it a friend…

Create a new text file to hold the fix

Create a new text file. Then, go to the link given above and copy the source for the first AndroidBug5497Workaround example and paste it into your new text file – save and close.

Rename the file

Next, rename the file so that it matches the class that it holds and give it the java extension. It should look like this:

  • AndroidBug5497Workaround.java
Open your Main Activity

With a text editor open your main activity Java file – it was the first file you saw in your “src” folder and probably is named after the name of your app. Look at the top of the file – you are looking for line a that looks like this:

  • package com.[NAMESPACE].[APP Name];

Its the only line that starts with the word “package” – copy that entire line and paste it at the very top of the other file – the one you’ve just created.

Add the fix to your main activity

Go back to your main activity Java file – you will need to paste this line after the super.loadUrl line:

  • AndroidBug5497Workaround.assistActivity(this);

It should look like this when you’re done:

adjustPanFix

Thats it – If in Eclipse clean your project and try it.

If you want to try the other example (again at the StackOverflow link given at the top of this page) then just follow the same procedure but be sure to use its class name (AdjustInputHeight) as the name of the file and when adding to your main activity.