Wednesday, September 19, 2012

Phonegap for Blackberry

Hello Again

So although i have not completed the ios post we will continue onto the dreaded Blackberry. Funnily enough this was one of the easiest ones to create.

I make use of the apache ant compile using the config.xml to allow access to features and whatnot. So where do we begin, well for a start read through phonegap tutorial here is the link, this instructs you to setup the correct environment and gives you a sample that you can compile and test.

ps. One quirk is that I was unable to compile using the latest webworks and had to use version 2.3. You may not have this problem but if you do here is the solution.

I will post more on the setup and compiling using apache ant later.


So notifications where do we start, the best place would be to understand a little about the compiling of the phonegap application. The application is compiled through webworks which is very good because it allows us to not only make use of the phonegap methods but allows us to make use of the webworks methods as well. I find that step by step tutorials are the easiest to follow so I will put it out in the way.

More to come...

First lets look at the webworks push notifications listener here is the link . So as instructed we have adapted the .xml file to cater for receiving the notifications, now onto the code. I found out that inserting the code in the ondeviceready function seemed to work the best as the listener must be run each time the application is opened. I made use of the openBISPushListener which is supplied in the sample code in the link above.

Secondly now that you have got your head around the sample code you need to enroll with the Blackberry push service.After a while they will supply you with details that you will put into your BIS port and in the php code to send the push notification. I will provide a link to this later.

There is one thing that you need to take into account when sending a notification to your application. In order to receive when the application is exited you need to capture the onexit event that gets fired and set your application to run in the background. I will supply the code to do this at a later stage.

More to come on sending the push and setting a icon in the banner.....

At last here is the code for the banner plus the beep to alert the user he has received a notification"icon.png",1); //I have set the count to one however you might want to calculate how many notifications are outstanding.

navigator.notification.beep(1);//This is the beep that will be played on receiving the message

These two methods must be placed in the ondata method.

Tuesday, September 18, 2012

Phonegap for IOS

Hello Again

So today we start on IOS we have already created our html and have gone through the ios guide. The sample app is a little bit different from the previous way which had templates that were incorporated into xcode. The new way is a little more tricky but follow the guide step by step and you will get there.

One thing to take note of is the quirks that phonegap documentation warns you about do not gloss over them as it can save you a lot of trouble.

The second thing to keep in mind is the whitelisting of the urls that you plan to use within your phonegap application. If you look in your Cordova.plist file you will see there is a property ExternalHosts add your urls in here.

Lastly I will explain this in detail later but if you are planning to upload your app you will need to create a developer account with apple. So that you can deploy to the app store.

More to come ....

So your application is ready for the app store where do we start?

Step 1: Enroll in the apple development program.
Step 2: Go through the steps in link
Step 3: Assign your code in the info tab of your program settings
Step 4: Archive your code
Step 5: Setup your app on apple connect (upload pictures and description)
Step 6: In your Archives click distribute follow the instructions to finalize your application 

So after a long wait apple has approved your application. Now you are ready for the next version.


I looked and urban airship and push woosh but both left me missing something plus you have to pay for them so after looking around a bit I found this plugin here is the link. This plugin is very well explained and works very well.

Unfortunately we are not out the water yet although we can setup the device to receive quite easily we need to push to the device. Luckily for us we have apns for php download the code from this link then once you have got your head around it go to this link and follow the instructions very carefully as this will instruct you on how to create a .pem file which is needed to send the notifications.

Don't worry if you are still struggling as later on I will do a step by step tutorial that you can follow.

So you have configured your push account and created your .pem file which you have included in you code finally you are receiving notifications.

Custom Methods

Ok so you are now a phonegap guru, not really but you might think you are, so we move onto the next step.

Plugins in phonegap are very well documented and nice and easy to create

More to come...

Phonegap for Android

Hello Again

Although I own a macbook pro and an iphone I am a fully fledged Android fan so we will start with the easiest and best :) .

If you have not looked at the phongap documentation for Eclispe setup here is the link

Ok so now you have downloaded and done about a gig of updates and installed all the google api platforms, at last we can begin.

All of the functions you need to create a basic phonegap application are provided in this link .


Alright so you are using your phonegap application and all is working nicely and just as you put that last finishing touch in your boss asks you for notifications. So now what do you do, you have a limited knowledge of the java language and dont know where to start. Luckily for you all has been done, here is the link that will solve your problems link .

Unfortunately this plugin doesn't allow us to get the data from the notification if we enter the app by clicking the notification in our notification bar as described below. So what do we do to get hold of the data which we have passed through in our notification? This is a good tutorial for creating a phonegap plugin so i have listed it below under custom methods.

In order to show the notifications in the notifications bar when the application is off add this code to the onMessage in the GCMIntentService

        NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
        int icon = R.drawable.icon;
        CharSequence tickerText = extras.getString("title");
        long when = System.currentTimeMillis();
        Notification notification = new Notification(icon, tickerText, when);
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        //notification.number += 1;
        Intent notificationIntent = new Intent(this,;
        CharSequence contentTitle = extras.getString("title");
        CharSequence contentText = extras.getString("message");
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
        notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
        Random generator = new Random();
        mNotificationManager.notify(generator.nextInt(), notification);

Ok so what now I have the phonegap notifications plugin on my device but how do i send a notification to my device? Here is the code

private $gcmurl = "";
    private $androidappid = "your id from gcm";
$message = "This is the message";

$messagearray = array('message' => $message, 'title' =>'this is the title');

        $headers = array("Content-Type:" . "application/json", "Authorization:" . "key=" . $this->androidappid );

        echo $data = array(
            'data' => $messagearray,
            'registration_ids' => $ids

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_URL, $this->gcmurl);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt ($ch, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
        $response = curl_exec($ch);

Ok now i have ready many tutorials on the net and a lot of the time they dont work, however I have tested this and have got it working on my Android device.

Custom Methods

So if you have got this far I presume that you have quite a good understanding of the phonegap and java language. What you now have is a phonegap application with notifications built in so what is next?

Your boss decides that all your brilliant features are not enough what you need is a custom feature that no one else has. So where do you begin well I am not going to tell you what you feature is going to be but I am going to point you in the right direction to make it happen.

Phonegap has provided us with a very nice simple feature for creating plugins and yes it has examples. Here is the link . I will continue later with a full step by step example of my own

ALERT: This plugin that I am creating here is in development and I am writing as I go so it might have issues at the moment

We are going to create a plugin that allows us to store the notification data in SharedPreferences then retrieve it for use in our phonegap application. I am sure you have read how, I will start at the beginning , first lets look at creating the java class

public class Notifications {

        //We need the context in order to gain access to the getSharedPreferences method
Context thisContext;
public Notifications(Context ctxt)
   thisContext = ctxt;

public String GetNotifications()
                //First we open a shared preferences instance with the package name of our app
SharedPreferences notificationvars = thisContext.getSharedPreferences(
     "", Context.MODE_PRIVATE);
//This gets the string from the shared preferences with the key of json
String json = notificationvars.getString("json", "this is default");

                // Once we have read the data out we clear the variable
SharedPreferences.Editor editor = notificationvars.edit();
   editor.putString("json", "");

            //We commit our changes back to shared storage

//Add in here notification manager cancel all method to clear all the notifications

return json;
public void SetNotifications(String json)
//First we open a shared preferences instance with the package name of our app
SharedPreferences notificationvars = thisContext.getSharedPreferences(
     "", Context.MODE_PRIVATE);

//This gets the string from the shared preferences with the key of json
String jsonorig = notificationvars.getString("json", "");
SharedPreferences.Editor editor = notificationvars.edit();

//Check if there is already notification data in the variable if there is append your new data onto the end
  //TODO put trimming in here for passing multiple json methods

String jsonfinal = jsonorig + ","+json;
editor.putString("json", jsonfinal);
editor.putString("json", json);
//Commit our changes

This is our controller class it reads and saves to the shared preferences. Now we will go onto the plug java code.

public class NotificationValuesPlugin extends Plugin {

     * Executes the request and returns PluginResult.
     * @param action        The action to execute.
     * @param args          JSONArry of arguments for the plugin.
     * @param callbackId    The callback id used when calling back into JavaScript.
     * @return              A PluginResult object with a status and message.
    public PluginResult execute(String action, JSONArray args, String callbackId)
            if (action.equals("GetValue"))
//First we create an instance of our notifications class we have just created and input the current context
            Notifications not = new Notifications(cordova.getContext());
//Get notification data
                String value = not.GetNotifications();
//Send the string back to the phonegap webview
                return new PluginResult(PluginResult.Status.OK, value);
                return new PluginResult(PluginResult.Status.INVALID_ACTION);

We are not finished with the java side just yet there is one more thing to do in the GCMIntentService in the onMessage you must replace GCMPlugin.sendJavascript( json); with GCMPlugin.sendJavascript( json , context);

and in the GCMPlugin you need to insert this code which will overload the other sendJavascript method. This part is not tested yet I am currently working on it.

 public static void sendJavascript( JSONObject _json ,Context ctxt)

Notifications not = new Notifications(ctxt);

    String _d =  "javascript:"+gECB+"(" + _json.toString() + ")";
        Log.v(ME + ":sendJavascript", _d);
        if (gECB != null )
          gwebView.sendJavascript( _d );

The next step is our javascript file

var NotificationValuesPlugin = function(){};

//Here we call the GetValues method in the execute method
NotificationValuesPlugin.prototype.GetValues = function (success, fail, resultType) {
      return cordova.exec( success, fail,
                           "GetValue", [""]);

//Here we add the plugin to cordova
if( cordova.addPlugin ){
  cordova.addConstructor(function() {
    //Register the javascript plugin with Cordova
    cordova.addPlugin('NotificationValuesPlugin', new NotificationValuesPlugin());
  window.NotificationValuesPlugin = new NotificationValuesPlugin();

After creating our js file we are almost complete just a few final touches. We need to add this <plugin name="NotificationValuesPlugin" value="packagename.NotificationValuesPlugin" /> to your plugins.xml or config.xml whichever you have. Lastly you have to add a reference to the html page that you will be using <script type="text/javascript" charset="utf-8" src="js/NotificationValuesPlugin.js"></script> .

Your plugin is now complete you can call the method by using this code

function getPushStorage() {

function pushStorageResult(result) {
   alert("SUCCESS: \r\n"+result );

function pushStorageError(error) {
   alert("ERROR: \r\n"+error );

Please comment if you think that there are things that need to be added or questions on how to do any of the above.

Phonegap Resources

Hello Again

To start your phonegap application begin with downloading phonegap for here .

A few things that must be considered when beginning your application:

First: How are you planning to compile your applications. If you are going to be creating an open          source or are willing to pay for each compile then you can send your html file to phonegaps build servers and you will receive a nicely compiled program to distribute. However if you are planning on compiling the code yourself phonegap has provided us with nice documentation to get us started, here are the links .

To start my application I have decided to make use of a mix of jquerymobile and jquery, this allows for a lot of visual customization. For those of you that do not know what these are I suggest you go and look at the links i have provided.

So you have downloaded phonegap and jquery, now there is one more thing before we start, the thing is what platforms are we going to develop for? In my case I am developing for IOS,Android and Blackberry.

Sunday, September 16, 2012

Starting Phonegap

So my boss has asked me to create a cross platform mobile application.

Where do I start , after looking at few platforms I have decided on phonegap. The reason for this is I know that although I was asked for something simple we know that nothing stays simple and phonegap has a very easy plugin system.

So what is phonegap you may ask, well as programmers we know that it doesn't take one day to learn a new language, so we need to compromise a bit. Phonegap makes use of built in webviews this allows you to create a native application with access to any feature on the device. Although it is not as optimized as a fully native application its quick and easy and allows you to create a feature rich application in no time at all.

More to come....