Friday, February 17, 2006

Recently on the way back from my holidays in Bali, I took a flight from Denpasar to Jakarta with Adam Air. I’ve heard about this relatively new airlines from several friends who all mentioned that Adam Air have brand new aircrafts and are even authorised to fly to Singapore. It sounded extremely good especially considering the one way ticket price of Rp295.000, which was just a bit higher than offer from the cheapest “metro-mini” style none-budget carrier Lion Air. The offer seem to be so good that base on my experience of living in Indonesia for several years, I immediately started thinking that this is just too good and there must be something wrong. Anyway, I decided to try my luck and fly with Adam Air. Apparently many other passengers thought the same, as the flight was totally booked – comparable to Garuda flight which had almost no passengers.

When boarding I immediately noticed that the Boeing 737-400 aircraft had the engine cover scratched everywhere, wings were all dirty and had broken paint in multiple places, aircraft door also looked very old and far from what I would expect from a brand new aircraft. Nevertheless, I decided to test the level of my fear of flying and get on the plane. Just for the record I noted the airplane registration code PK-KKI.

When arrived in Jakarta I looked up the airplane code in the database and the “brand new” aircraft that I was flying apparently had its first flight on 10-12-1988, thus being 17 years old age aircraft, which if compared humans, the airplane would be in its late forties. In its long life the mentioned airplane also travelled a lot as it was previously used by Sahara India Airlines, Sierra National Airlines and Air Belgium (first owner), thus having pretty much interesting life as an aircraft.

Now a question arises if I had a bad lack to fly with the only old airplane in Adam Air's fleet or actually the fleet is not as new as I’ve expected. Following my curiosity I prepared a table of Adam Air owned aircrafts providing the age of each aircraft:

Registration Aircraft First flight date Aircraft Age
PK-KKF 737-200 12-2-1980 26
PK-KKN 737-200 21-3-1980 25
PK-KKQ 737-200 16-1-1981 25
PK-KKJ 737-200 3-2-1982 24
PK-KKL 737-200 12-4-1984 21
PK-KKE 737-300 31-8-1987 18
PK-KKP 737-200 31-5-1988 17
PK-KKH 737-400 11-7-1988 17
PK-KKU 737-300 4-8-1988 17
PK-KKI 737-400 10-12-1988 17
PK-KKD 737-400 22-12-1988 17
PK-KKR 737-300 9-1-1989 17
PK-KKS 737-400 28-1-1989 17
PK-KKT 737-400 5-9-1989 16
PK-KKG 737-400 7-1-1991 15
PK-KKC 737-400 9-1-1992 14
PK-KKA 737-500 10-6-1997 8

Looking at that I feel I was actually lucky as the 17 years old aircraft I had a pleasure to fly with is actually very new if compared to another Aircraft used by Adam Air registered as PK-KKN (KKN is actually one of the most popular acronyms in Indonesia originated from Korupsi-Kolusi-Nepotisme) which at a current date is 25 years old. Comparable to human age this aircraft would be in its late seventies and probably already having one spot booked at the graveyard.

Base on the table above we can also calculate an average age of the Adam Air's fleet, which is 18 years. Actually, there was only one airplane that was less than 10 years old and if I’m not mistaken that must be the Adam Air aircraft authorised to land in Singapore.

Clearly, many passengers chose Adam Air airlines thinking about the new airplanes, when actually the fleet is full of refurbished aircrafts with only one relatively new aircraft which is used by Adam Air marketing team to create an image or rather mirage, of having fleet of new aircrafts.

Maybe Adam’s Air definition of “new” is somehow local Indonesian definition, thus I might have wrong perspective. To verify that I compared age of major Indonesian airlines and came up with the following statistics of indonesian aircraft carriers average age of the fleet:

Garuda Indonesia - Age 10 years
Lion Air - Age 17.2 years
Adam Air - Age 18.1 years
Awair - Age 18.8 years
Merpati - 21.8 years
Batavia - Age 23.4 years
Sriwijaya Air - Age 23.5 years
Mandala Airlines - Age 23.9 years
Bouraq Indonesia Airlines - Age 25.1 years

Shocking! With 18 years old fleet of elderly aircrafts Adam Air comes on the third position of the newest aircraft fleet in Indonesia. Garuda Indonesia leads with 10 years old fleet. Another great surprise is that none-budget carried Lion Air comes second with just a little over 17 years old fleet – that is almost half older fleet than Garuda Indonesia. The list is closed by Bouraq Indnonesia Airlines which with 25 years old fleet gives me an idea of a Fear Factor stunt “Flight with Bouraq” for test of flying phobia. Mandala Airlines comes second from the end.

Having Mandala Airlines so low in the list reminds me about the Mandala’s Boeing 737-200 crash on 05/09/2005 which resulted in total body count almost 150. At the date of incident the PK-RIM aircraft was almost 24 years in service. For comparison the Lion Air's McDonnell-Douglas MD-82 airplane that crashed in Solo Airport on 30/11/2004 at the date of incident that resulted in 25 fatalities was 20 years in service. At last report, it had accumulated 56,674 flight hours and 43,940 landings!

I somehow think that it’s not just a coincidence that the aircraft that crashed were at least 20 years old.

To compare that to the foreign airlines, I checked the average age of fleet of pervious owners of the Adam Air’s PK-KKI aircraft I was flying with.

Blue Panorama Airlines: Age of the fleet - 11.6 years
Sahara India Airlines: Age of the fleet - 10.5 years
Interesting, 11.6 years and 10.5 years which I think proves that both airlines found this plane too old to operate, while Adam Air management thinks operating 17 years old aircraft is perfectly fine.

Browsing through recent newspapers I’ve found several articles that will be a good conclusion for this post.

The first one comes from The Jakarta Post (dated 11 February 2006):

An Adam Air Boeing 737-300 plane serving the Jakarta-Makassar route was forced to make an emergency landing Saturday at the small Tambulaka Airport in Sumba, East Nusa Tenggara, a spokesperson for Adam Air said.

The plane took off from Jakarta's Soekarno-Hatta International Airport at 6:20 a.m. with 145 passengers on board. It was scheduled to land at Hasanuddin Airport in Makassar at 9:25 a.m. local time, Suwandi, Adam Air supervisor for Makassar, said. There is a one hour time difference between Jakarta and Makassar.

However, navigational problems caused pilot Tri Tuniogo to lose contact with the destination airport, he said. The plane was later found to have landed at Tambolaka at 9:45 a.m. local time.

"No one was hurt in the incident," Didik, Adam Air's public relations officer for Jakarta, said, adding that the emergency landing was made due to bad weather. "As to whether it was a storm or heavy rain that forced the pilot to land -- we remain uninformed," he said.
Ok, so there was a bad weather and airplane had to land. Nothing unusual, right? Until you read the follow-up published on the Valentine’s day.
The ministry of transportation considers that Adam Air committed a serious violation when operating a plane still required for "evidence" following a serious incident affecting the navigation system of the plane. "That is a serious violation and the first ever committed by an airline in Indonesia. The Adam Air management needs to be examined in connection with it," the ministry's director general of air transportation, Iksan Tatang, said replying a reporter's question here on Monday.

Adam Air's Boeing 737-300 aircraft with flight number DHI728 had made an emergency landing at Tambolaka airstrip in West Sumba, East Nusa Tenggara, after wandering for three hours due to a navigation system failure on its way from Jakarta to East Nusa Tenggar with 145 passengers on board.

On Sunday the aircraft was flown by the airline's operations director, Ade Salmiar, to Hasanuddin airport in Makassar, Sulawesi, after technicians from the Ngurah Rai airport in Bali repaired it.

The director general said the plane should not have been flown pending an examination by the National Committee of Transportation Safety (KNKT) and the Directorate of Airworthiness Certification.

"In view of that the Adam Air management must be examined, including the pilot that flew it," he said adding that if the pilot was found to be aware that his action was actually wrong he could have his license revoked.
That’s interesting. Previously it was a bad weather and now it is a navigation system failure. Huh? I think the real story came up only because of the serious violation committed by Adam Air. FYI two of my friends flew with Lion Air from Manado and airplane had a serious malfunction to the extent that stewardess ordered everyone to wear a life vest. Fortunately flight finished without fatalities and nothing appeared in news - probably thanks to the KKN acronym I’ve mentioned before.

You probably wonder how old was that Boeing 737-300 which got navigation system failure acka landed because of bad weather? Looking at the age of Adam Air’s 737-300 fleet the plane must be at least 17 years in service. That is probably 3 years too short to have this small incident resulting in fatalities and adding another Indonesian airplane crash to the list. Looking at the whole picture, I predict there will be at least one Indonesian aircraft accident before the end of this year. Thus, have a nice flight everyone! Meanwhile, I'll fly with Garuda.

Update: Follow-up on the PK-KKW crash here.

Thursday, January 26, 2006

I’m now on my holidays in Bali, which should explain lack of updates on my blog. It is rainy season here, thus the weather is quite cloudy and rains at least once a day. I personally think this type of weather is pretty much perfect for holidays, as it is not too cold and not too hot.

Cloudy Bali.
Surprisingly, thanks to strong Bali sun even in a very cloudy weather I could get sunburned. The hotels also give even 50% discount as it is off season and after recent Bali bombs, very few foreigners decided to chose Bali as their holidays destination and the occupancy rate of most hotels is below 30%. Overall, I enjoy my holidays a lot, yet it is not all pure holidays for me, as I still have to follow-up on my current projects.

My most urgent project with a very short deadline is outsourced development of a user interface for my client’s application. It is mainly PHP, advanced Java scripting, XML and MySQL, thus I can pretty much work on the project from my laptop at the hotel. I can even get dial-up Internet connection from my hotel located in a remote area of Bali and even GPRS connection from my mobile phone. It’s pretty much amazing to be able chat with your friends while sitting on remote beach few kilometers from nearest village or somewhere high in the mountains surrounded by monkeys.
My parents feeding monkeys at the temple (1 hour walk up the mountain).
Moreover, I could even shoot a photo with using my phone and send it directly to my friend’s e-mail. Five years ago this would be something unimaginable or at least would have to involve extremely expensive satellite phone, now it’s just matter of a smart phone that can run Java based chat application, e-mail client and can connect to Internet via GPRS.
Remote beach in Bali.
The good news is that I am not so geek to take my laptop everywhere, the bad news is that I need to leave it somewhere. Fortunately, I have a Kensington laptop cable lock with me, thus I can simply lock it in my hotel room or at a pool café.
My IBM ThinkPad laptop locked at the pool side.
Yet, this is all not so great, because laptop is not only the laptop chassis. Users of cable locks often forget that there are many parts of the laptop that can be removed in a few seconds. The following photo shows parts of my laptop that I could remove within less than 10 seconds.
IBM ThinkPad Laptop parts removed within 10 seconds.

It is a DVD drive that could be removed within two seconds, laptop battery removed within one second and hard disk removed after 5 seconds of removing a single screw. Clearly, even if laptop is locked with a cable lock, it is still possible for a potential theft to benefit. The total value of these parts is around 250$, not including the keyboard keys that also could be simply removed. Moreover data on a laptop hard disk can often be extremely valuable, more than laptop itself. Myself, I use PGP Disk to secure most sensitive data on my Windows partition and EFS for some less important files. I also use GnuPGP to secure data on my Linux partition. Some work related data that I don’t want to lose I regularly burn on CD-RW and save on USB disk.

I feel I pretty much know how to secure my data while traveling. Yet, the methods described here can be bit complicated for less advanced users, thus for those users who feel encrypting data on laptop is too complicated or not having any method of backing up data, I’d recommend keeping your hard disk at hotel’s safe deposit box, as it won’t be protected with your cable lock. If you don’t even have a laptop cable lock, I’d strongly recommend buying one. It may not protect your hard disk, but at least it will discourage theft from stealing a complete laptop and most thefts won't probably know how to remove a hard disk.

Saturday, January 14, 2006

In the part one of the article series I’ve introduced the very basics of mobile application development that is a preparation of mobile application development environment. I’ve also introduced the technology that will be used in all the series of “Mobile Application Development: Can I do it?”. The chosen technology is Java 2 Platform, Micro Edition (J2ME) and NetBeans IDE (Integrated Development Environment) as our development tool. Both products are FREE for commercial and non-commercial use allowing everyone to start mobile development immediately without spending a single dollar. After reading the part one of the article series, many of you tried the sample projects provided together with NetBeans 4.1. Base on the initial input I've received it seems that many of you got surprised with impressive results that can be achieved with only short Java code. You also start asking “How to make my own J2ME project using NetBeans?” or “How to transfer builded application to my mobile phone?”. The second part of the article series provides step-by-step answer to both questions.

In the next four parts of the series I’d like to focus on the fun part of a mobile application development which is making mobile games. I’ll show how to build a simple, yet interesting game step-by step, from very basic code, graphics up to the code optimisation and fully working game.

Let’s start

The very early stage of mobile game development is usually a creation of a very basic template (skeleton) type of our game code. Such skeleton code includes the basic functions of our mobile game such a handling graphics, control of the game by the users, control of application lifecycle. Thus, in our earliest J2ME game coding we will create our first MIDlet – that’s how we name Java 2 program on embedded devices.

In the first step let’s create new project in NetBeans IDE. Start the NetBeans IDE and select File -> New Project (or use keyboard shortcut Ctrl+Shit+N). A New Project wizard will appear.
Figure 1. New project wizard.

In the first choice we have to choose the type of project. The best option for creating a mobile game skeleton project is to select Mobile in Categories and chose Mobile Application. Click Next.

In the next menu set the name for the project i.e. MyFirstGame and the location of the project where all project files will be stored. For the purpose of this article please do not select the “Create Hello MIDlet” option, as we will create MIDlet ourselves. Click Next.

In the last stage of the project creation wizard, we need to select the type of device that we will use to run our mobile game.
Figure 2. Platform selection in a New Project wizard.

The important options to configure at this stage are Device Configuration and Device Profile.

In the first Device Configuration setting the CLDC stands for Connected, Limited Device Configuration. In general it is part of framework that provides the most basic set of libraries and a virtual-machine feature that allows our MIDlet to run on the device. It is designed for resource-constrained devices such as smart phones, PDAs and small electronic equipment. There are currently two CLDC specifications available, version 1.1. (JSR 139) and the first release version 1.0 (JSR 30). At this stage you need to check which version is supported by mobile phone that you want to use in application development. My device is Sony-Ericsson P900 and by referring to the documentation I checked that it supports CLDC version 1.0. Thus, my option for Device Configuration is CLDC-1.0.

Second important setting is a Device Profile, available in two options MIDP-1.0 and MIDP-2.0. MIDP stands for Mobile Information Device Profile, and is also part of the J2ME framework, that together with CLDC enables Java on your mobile phone. By referring to documentation I checked that my SE-P900 phone supports MIDP-2.0 thus this will be my option. MIDP-2.0 provides lots of new and very useful features, which will make our game development much easier. Unfortunately, if your mobile phone does not support the new MIDP-2.0, some parts of the code provided in this article may not be supported on your mobile phone (especially GameCanvas related). You will be able to work on your mobile application in NetBeans but it will be a problem to make it work on your MIDP-1.0 phone.

After clicking Finish, MyFirstGame project will be ready for development.

Figure 3. Creation of New MIDlet.

As previously we decided not to create default MIDlet, we need to create it manually. Thanks to NetBeans, it is extremely simple. Simply click right button on (, select New and MIDlet [Figure 3]. In the newly opened wizard, enter the name of the MIDlet in the “MIDlet Name” field. For the purpose of this article name it MyGameMIDlet and click Finish. Our MIDlet will be created. If you wish to change the to a different name such as “mygame”, you can do it by clicking right button on it, selecting Refractor and Rename from the menu (optionally, you can use keyboard shortcut Alt+Shift+R).

Newly created MIDlet named MyGameMIDlet is our starting point for the game template development. By default it already includes three methods that are mandatory for every MIDlet, that is startApp(), pauseApp() and destroyApp().

package mygame;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MyGameMIDlet extends MIDlet {

public void startApp() {
}

public void pauseApp() {
}

public void destroyApp(boolean unconditional) {
}
}

The first method startApp() is called by Application Management Software (AMS) when MIDlet starts or it is being resumed. Since it is invoked after resume, it is clear that it can be executed more than once. For this reason it is important to control how new objects are initialised in this part of the code, as there is a risk of initialising object more than once.

The next mandatory method is pauseApp(). It is invoked by AMS in situation such as user receiving a phone call during the game, low battery warning etc. and can be used to minimise CPU, memory or even a power consumption, when application is not in the active state. It is important to remember that pauseApp() is not always called when MIDlet is going into background (loose focus), as it is on Series 60 phones. In such situation MIDlet should detect when application is not in focus and call notifyPaused() method.

The last mandatory method is destroyApp(). This method is called to destroy MIDlet by AMS to prepare MIDlet for termination. It should execute clean-up actions releasing resources etc. and notify AMS about completion of cleanup tasks with notifyDestroyed().

These three methods are part of something called MIDP Lifecycle. It is very important for every J2ME programmer to know this subject well, thus I refer to the PDF document Programming the MIDP Lifecycle on Symbian OS that explains it in details and provides information on mistakes that should be avoided by newbie J2ME programmers. I also strongly recommend reading MIDlet Lifecycle Article on Sun Developers web-site.

Base on information mentioned in these guidelines, our implementation of MIDP lifecycle in the MyGameMIDlet.java looks as follow:

package mygame;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MyGameMIDlet extends MIDlet {
    private final static int PAUSED = 0;
    private final static int ACTIVE = 1;
    private final static int DESTROYED = 2;

    private int stateTracker = PAUSED;

public void startApp() {
       stateTracker = ACTIVE;
}

public void pauseApp() {
       stateTracker = PAUSED;
       notifyPaused();
}

    private synchronized void performDestroyCleanup() {
        if (stateTracker != DESTROYED) {
            stateTracker = DESTROYED;
            notifyDestroyed();
        }
    }

public void destroyApp(boolean unconditional)
  throws MIDletStateChangeException {
       performDestroyCleanup();
}
}

Beside MIDlet, one more Java Class will be required, a GameCanvas. This is a special class that will handle game-specific features such as efficient graphics or game control with keys pressed by the user. For those one unfamiliar with GameCanvas I recommend to read the Game Canvas Basics article followed by Using GameCanvas in MIDP2.0.

We can add this class to our project by right-clicking on the package (mygame or if you didn’t change the name before), selecting New and Java Class. In the form that appears we can name the class. Fro the purpose of the article let’s name it MyGameCanvas and click Finish. The default class will include mandatory code.

Figure 4. Creation of New class used for GameCanvas.

The first task to do is to import additional classes to support required functions. For the purpose of our article, the following three classes should be added:
import   javax.microedition.lcdui.Graphics;
import   javax.microedition.lcdui.Font;
import   javax.microedition.lcdui.game.GameCanvas;

Their functions are as follow: javax.microedition.lcdui.Graphics (provides simple 2D geometric rendering capability); javax.microedition.lcdui.Font (provides fonts capability); javax.microedition.lcdui.game.GameCanvas (introduced in MIDP-2.0, provides gaming features).

Since GameCanvas is already supported, we should modify the default MyGameCanvas constructor to extend GameCanvas and implement Runnable for the purpose of threads. To do so, we need to modify our default constructor:

public class MyGameCanvas

as follow:

public class MyGameCanvas extends GameCanvas
 implements Runnable {
Use of GameCanvas, also requires us of super() to suppress the normal key event mechanism, inherited from the Canvas class, as we do not require these notifications in our MyGameCanvas.

Finally, implementation of Runnable interface for the purpose of tasks (read more here) requires us to add one more method called run(). The modified basic MyGameCanvas.java code looks as follow:

package mygame;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.game.GameCanvas;

public class MyGameCanvas extends GameCanvas
        implements Runnable {

public MyGameCanvas() {
     super(true);
}

    public void run() { 

    }

}

Game loop

Every game is build with the same concept of repetitively executed code that modifies graphics, resulting in animation and game action. Thus, in next step we need to create a primary game loop.

Such game loop will require creation of a new thread, starting the thread, within the thread executing all the actions and repating these actions with specified time delay. To organise the code better, we also added custom startGame() and stopGame() methods. The startGame() method will be used to execute the thread, which will then call run() and go into the game loop. The stopGame() method will be used to stop the thread. The delay between repeating tasks in the loop can be easily done with Thread.sleep(milisecond), which will sleep a thread for a specified number of milliseconds, before repating the actions and creating a next frame of the game.

The modified MyGameCanvas.java code looks as follow:

package mygame;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.game.GameCanvas;

public class MyGameCanvas extends GameCanvas
 implements Runnable {

public long GameFrameDelay = 30;

Thread thread = new Thread(this);

public MyGameCanvas() {
super(true);
}

public void startGame() {
  thread.start();
}
    
public void stopGame() {
  thread = null;
}

public void run() {

   while ( true ) {

      try { Thread.sleep(GameFrameDelay); }
      catch (InterruptedException ie) {
            stopGame();
      }

   }

}

}

At this stage we have finished our game loop. However, if we run (press F6) the MIDlet, we will not see any game canvas or any graphics. You probably wonder why? The answer is very simple, it is because we haven’t linked MyGameCanvas with MyGameMIDlet. To do it we need to start MyGameCanvas thread from MyGameMIDlet and link the canvas.

First, we need to create a unique Display object mygameDisplay and MyGameCanvas object mygameCanvas in MyGameMIDlet.java. These two objects will be our reference for graphics. Now, in the startApp() we need to allocate our canvas and start the thread in MyGameCanvas through startGame() method. Following that we need to allocate display and set mygameCanvas to be our current canvas. This done with getDisplay() and setCurrent(). Following are the code changes to MyGameMIDlet.java:

package mygame;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MyGameMIDlet extends MIDlet {
private final static int PAUSED = 0;
private final static int ACTIVE = 1;
private final static int DESTROYED = 2;

private int stateTracker = PAUSED;

    private Display mygameDisplay;
    private MyGameCanvas mygameCanvas;

public void startApp() {
       if (mygameCanvas == null) {
            mygameCanvas = new MyGameCanvas();
            mygameCanvas.startGame();
        }
 mygameDisplay.getDisplay(this).setCurrent(mygameCanvas);
 stateTracker = ACTIVE;
}

public void pauseApp() {
stateTracker = PAUSED;
notifyPaused();
}

private synchronized void performDestroyCleanup() {
 if (stateTracker != DESTROYED) {
     stateTracker = DESTROYED;
     notifyDestroyed();
 }
}

public void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
performDestroyCleanup();
}
}

If we run our project in the emulator (F6), it will only produce a blank screen. This is simple because we haven’t added any graphic to MyGameCanvas code, yet.

Adding Graphics to MyGameCanvas

Now, let’s try to make our application display some graphics during the game loop. The beginning step would be creating a background for our graphics. To keep it simple we will fill up the screen with one solid colour. The simplest method to do so is to create a coloured rectangle that fits the size of the screen. To create such rectangle, we need to first create an object that will be used for graphic operations using getGraphics() method. As next step, we need to get the width and height of the mobile device screen using getWidth() and getHeight(). With this information we know dimension of the rectangle required to cover all the space of the screen. Now only need to set the drawing colour using Graphics method setColor() and fill the canvas with rectangle using fillRect() method, with a dimensions set to cover the screen.

The rectangle is created on game canvas. However, if you run the project the rectangle will not appear on the mobile device screen yet. To do so we still need to flush all the graphics changes on the screen. For this purpose we can create a custom method called paintScreen() (name it whatever you like) that calls flushGraphics() method, resulting in graphic changes appearing on the screen.

The modified part of the MyGameCanvas.java code looks as follow:

...

public void run() {

   Graphics g = getGraphics();

   int scrWidth = getWidth ();
   int scrHeight = getHeight();

while ( true ) {

        g.setColor(0x00ff00);
        g.fillRect(0, 0, scrWidth, scrHeight);

        paintScreen(g);

      try { Thread.sleep(GameFrameDelay); }
     catch (InterruptedException ie) {
         stopGame();
     }

}

}

    protected void paintScreen(Graphics g) {
        flushGraphics();
    }

...
If we run the MIDlet a green (0x00ff00 in hex) background should appear on the screen. After checking it you will probably quickly notice one problem that is lack of ability to close midlet by the user. For this purpose we need to add Exit command to our game canvas. This will require implementation of CommandListener, creation of a new exitCommand command and adding command to the mygameCanvas with addCommand method. Additionaly, we will also need to create commandAction()method that will handle command actions. Additionally, we need to make a small change to startApp() to provide us with control on the state change exceptions. Modified MyGameMIDlet.java looks as follow:

package mygame;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;

public class MyGameMIDlet extends MIDlet
  implements CommandListener {
private final static int PAUSED = 0;
private final static int ACTIVE = 1;
private final static int DESTROYED = 2;

private int stateTracker = PAUSED;

Command exitCommand = new Command("Exit",Command.EXIT,2);

private Display mygameDisplay;
private MyGameCanvas mygameCanvas;

public void startApp()throws MIDletStateChangeException {
if (mygameCanvas == null) {
   mygameCanvas = new MyGameCanvas();
   mygameCanvas.startGame();
  mygameCanvas.addCommand(exitCommand);
  mygameCanvas.setCommandListener(this);
}
mygameDisplay.getDisplay(this).setCurrent(mygameCanvas);
stateTracker = ACTIVE;
}

public void pauseApp() {
stateTracker = PAUSED;
notifyPaused();
}

private synchronized void performDestroyCleanup() {
 if (stateTracker != DESTROYED) {
     stateTracker = DESTROYED;
     notifyDestroyed();
 }
}

public void destroyApp(boolean unconditional)
throws MIDletStateChangeException {
performDestroyCleanup();
}

public void commandAction(Command c, Displayable s) {
if (c.getCommandType() == Command.EXIT) {
try {
     destroyApp(true);
  } catch (MIDletStateChangeException ex){ }
}
}

}

Keypad based game control

The last missing element of our mobile game template is user control of the game with mobile phone keypad actions. This functionality is supported by GameCanvas class with getKeyStates() method. To make our code cleaner we can put this method into a custom method processKeyStates(), where we can check states of the keypad keys and base on user pressed keys we can take action. Our sample action for the purpose of this text is to modify a text variable that will contain information on pressed keys. However, before we display this information on the screen, we can display welcome text Hello. Press Keys. informing user that he/she should press the keypad buttons. In order to display the string on the screen we need to first set-up the font. This can be easily done with getFont(), which allows us to customise the font, such as making it bold with parameter Font.STYLE_BOLD. We also set a colour of a phone with g.setColor(0x990000), measure the width of the text and finally print it on the game canvas using Display method drawstring(). The modified code looks as follow:
package mygame;

import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Font;
import javax.microedition.lcdui.game.GameCanvas;

public class MyGameCanvas extends GameCanvas
 implements Runnable {

public long GameFrameDelay = 30;

String txt = new String("Hello. Press Keys.");

Thread thread = new Thread(this);

public MyGameCanvas() {
super(true);
}

public void startGame() {
thread.start();
}

public void stopGame() {
thread = null;
}

private void processKeyStates() {
 int keyState = getKeyStates();
 if ((keyState & UP_PRESSED) != 0) {
txt = "Key: UP";
}
 if ((keyState & DOWN_PRESSED) != 0) {
txt = "Key: DOWN";
}
 if ((keyState & LEFT_PRESSED) != 0) {
txt = "Key: LEFT";
}
 if ((keyState & RIGHT_PRESSED) != 0) {
txt = "Key: RIGHT";
}
 if ((keyState & FIRE_PRESSED) != 0) {
txt = "Key: FIRE";
}
}

public void run() {

Graphics g = getGraphics();

int scrWidth = getWidth ();
int scrHeight = getHeight();

   Font myfont = g.getFont();
   myfont = Font.getFont(Font.FACE_SYSTEM,
                          Font.STYLE_BOLD,
                          Font.SIZE_MEDIUM);

   int fontHeight = myfont.getHeight();
   int fontWidth = myfont.stringWidth(txt);

   g.setFont(myfont);

while ( true ) {

 g.setColor(0x00ff00);
 g.fillRect(0, 0, scrWidth, scrHeight);

 processKeyStates();

 g.setColor(0x990000);
 fontWidth = myfont.stringWidth(txt);
 g.drawString(txt, (scrWidth - fontWidth)/2,
          (scrHeight - fontHeight)/2, g.TOP|g.LEFT);

 paintScreen(g);

     try { Thread.sleep(GameFrameDelay); }
     catch (InterruptedException ie) {
         stopGame();
     }

}

}

protected void paintScreen(Graphics g) {
 flushGraphics();
}

}

The result of running the final code in the emulator is a green background with welcome text changing base on the user input, as seen below:

Figure 5. Final template running in emulator.

Now, the only task left is to Clean and Build Main Project (Shift + F11) [Figure ].

Figure 6. Cleaning and Building Project.

The generated file MyFirstGame.jar can be uploaded to the mobile phone via Bluetooth, installed and launched. Below screenshot shows MIDlet running on my SE-P900 phone.

Figure 7. Final MIDlet runnign on SE-P900 phone.

Conclusion

Thanks to NetBeans IDE and J2ME technology, mobile game development is trivial. With less than 100 lines of Java code we were able to create a MIDlet that displays text and graphics, can be controlled from mobile phone keypad and integrates with phone Application Management Software (AMS). We were also able to quickly verify the result thanks to emulator, which can be launched from NetBeans with a click of a button. Finally, with another click of the button we were able to clean the code, build it and run the generated JAR file on a mobile phone. Clearly, creating a basic mobile game is not as difficult as you may previously have thought.

In the third part of mobile application development series, I will present a game concept of our article game, add all the necessary 2D graphics to the game template and provide code responsible for game animation. As usualy, I’ll explain everything step-by-step, from making game graphics in Adobe Photoshop, preparing it for use in our MIDlet as well as displaying graphics and animating it. Now, just for an introduction, please meet two main characters of our game:
Figure 8. Main characters of our game.

As you can see we even got well known celebrities as our game characters! Thus, please be patient waiting for the part three of the article series, while I'll continue to work with our celebrities on the game animations. Drop me an e-mail if you have any comments or questions.

The complete game template from this article including detailes comments and explaination of each line of the code can be downloaded from here.

Thursday, January 12, 2006

Indcoup writes about problems of food safety in Jakarta. Dangerous food is on my top 3 most disturbing things in Jakarta, just after the nightmare traffic and scary butcher doctors. Just read the post and join the discussion. Meanwhile, Jakartass writes about various problems with customer service often faced by ppl in Jakarta. All very interesting read.

Wednesday, January 11, 2006

A friend of mine has been researching Windows Embedded Open Type (EOT) Font vulnerability that he discovered in Windows about a week ago. Just when he finished the analysis, eEye released the vulnerability advisory, thus being ahead of him. Anyway, to this moment his analysis is the best known publicly available analysis of this vulnerability.

Overall, the vulnerability should be considered as CRITICAL, mostly due to the simple fact that EOT is supported by Internet Explorer, Microsoft Word, Excel and several other applications that allow to include EOT fonts in the document/file. It means that every .doc file or Internet web-site could potentially result in malicious application being exedcuted on your computer. Thus, it is extremely important to update all Windows computers at office or home quickly.

You can download patch from here. Install it ASAP!

Tuesday, January 10, 2006

I’ve received number of interesting e-mails from my readers in relation to the Wi-Fi Hotspots in Jakarta – Hacker’s playground article. One of the often repeated subjects in e-mails was the terms and conditions of hotspot service set by local ISPs. Someone pointed out that one of the Indonesian ISPs obligates users to accept the fact that the hotspot service is insecure. The following clauses in the terms and conditions of service were attached in e-mail:

English version:

2. Due to security reasons, Customers are advise not to use Hotspot for electronic transaction or other confidential information.

4. Hereby the Customer understands and aware of any risk on using Hotspot, therefore Customer releases CBN for any loss or responsibility due to such risk.

Indonesian version:

2. Karena alasan keamanan, Pelanggan tidak dianjurkan menggunakan fasilitas Hotspot untuk melakukan transaksi keuangan atau informasi rahasia lainnya.

4. Pelanggan dengan ini memahami segala resiko atas penggunaan atau ketidaksanggupan layanan yang disediakan, untuk itu Pelanggan bersedia membebaskan CBN dari segala tuntutan ganti rugi maupun tanggung jawab yang timbul akibat resiko sebagaimana telah dijelaskan.

I verified correctness of this information and as you can see on the screenshot below, the CBN Hotspot Terms of Service indeed include such clauses:

When reading these terms and conditions set by CBN, several question arise. First of all, what happens if I use the insecure hotspot service to receive my e-mail and some hacker benefiting on lack of encryption of wireless data and captures my e-mail password and reads my confidential data? The terms of service do not mention anything about lack of encryption of service, it only states Customer understands and aware of any risk on using Hotspot, therefore Customer releases CBN for any loss or responsibility due to such risk, plus the article about on-line banking and confidential information. I don’t know how about my readers, but “any risk” sounds very much broad to me. If presumably there is a problem with billing on the hotspot and the consumer bill for use of the service increase to a very high amount, is it also included in any risk? I say there is some risk of damage to my wireless card, thus how about if my wireless card gets damaged due to malfunction of wireless hotspot? Is it also within any risk? Stating that company is not responsible for any risk sounds totally crazy to me.

I couldn’t believe that offering a commercial telecommunication service to consumers with such terms is legal. Unfortunately, I can not answer this question myself as my understanding of Indonesian law is very blurry. I also don’t have a license of an Indonesian lawyer allowing me to provide any legal opinion, so to clarify everything I decided to seek opinion of experts in consumer protection and telecommunication laws. My choice was REM Asia Pacific & Co. law firm as they got one of the best legal experts in both telecommunication and consumer protection laws, which perfectly fits my need.

The opinion of REM Asia Pacific’s Partner, Reno Iskandarsyah, is as follow:

Is it legal? The answer is, No! In Indonesia we have the Consumer Protection Act No.8/1999, which provides protection against bad behaviour, unfair treatment by enterprises (company), and rules the equal right and obligation between consumer and the company. The term Consumer shall mean as every person using goods or services for their own need, their family, relatives, or mankind not to sell or get benefit from the goods or services. The term company is defined as every person, institution, company, who sell, produce or provide goods or services to the consumers.

The Terms and Conditions given by CBN, is categorized as “standard clause”. It contains the rights of CBN (as service provider) and the obligations of consumer (as subscriber). However, as obviously noticed, the positions of the service provider and the subscriber are not equal in CBN case. A service provider shall not simply leave an option to its subscriber, i.e.: if you disagree with the terms, you can leave CBN and no longer using their network, if the terms are acceptable to you, you may continue using the network, but, when the network disturbance occures, CBN shall not be responsible for any loss incurred.

Under Article 4 Act No.8/1999 consumer has the right to enjoy comfort, protection, safety, while using or consuming goods or services, and she/he has a right to be compensated for any malfunction. Additionally, Article 7 obliged the service provider to provide the service in good faith, in truth (regarding giving information about the service), honesty, non- discrimination, as well as giving warranty for the standard quality of the service or goods.

The issue of “standard clause” in CBN Terms and Conditions, basically in breach of Article 18. Under this article, a company may not or not allowed to create a standard clause in every documents nor terms and conditions regarding:

a. assignment of liability of the company;

b. consumer is abide by the amendment to the standard clauses made by the company during the utilization or consumption of the purchased service or good.

A breach of this article will be subject to a crime sanction of 5 (five) years in jail or the penalty of Rp. 2,000,000,000 (IDR Two Billion, ~US$210,000).

Clearly, in Indonesia consumers are being protected by the law. You can fight for your rights and can file a complaint about the terms and conditions that were given by CBN. CBN must protect their network from any disturbance, hackers and malfunction, and can’t handover their liability to their customers. If CBN remain silent on this, then the consumers shall have the right to file a claim for compensation or the worse would be to lodge a legal suit.

Frankly, I feel completely stunned with this answer! Considering the simple fact that Reno was a lawyer for the Indonesian Consumers Foundation (YLKI), this becomes a serious issue.

I’ve also asked Rakhmayanti Esther Makainas – well known expert in telecommunication law – for her comment on this matter. Here it goes:

In Indonesia, the service provided by CBN or similar provider is governed under Telecommunication Act No.36/1999; Government Regulation No.52/2000; Minister of Communication Decree No.21/2001, as what is defined as Multimedia Service Provider or particularly an Internet Service Provider. In principal, a service provider is obliged to ensure the quality of the provided services. Even further, under Article 68 of that Government Regulation No.52/2000, a Service Provider shall be liable for any loss incurred by any parties due to such negligence or failure made by the Service Provider. Imagine if someone captured your company’s confidential documents/information while you were using Internet service at the hotspot due to the lack of security, which relates to the quality of service.

After reading opinion of two highly qualified lawyers, I think you already know what to do in case of problems with your ISP.

From the technical point of view, I clearly understand that providing insecure, unencrypted wireless Internet access service creates a great risk to the consumer. It doesn't take much hacking skills to sit down at a café with hotspot and begin intercepting and reading all the unencrypted wireless transmissions passing through the air. There are number of ways to secure public wireless hotspot and it seems that ISP simply doesn't bother to implement it. It also does not involve high cost, as the wireless service can be effectively secured with a simple solution.

FYI in Europe, before any product is accepted for use at a telecommunication company, it is first being tested by group of security experts at company’s research department. The product will not be used by the company if there is no positive security approval from the research department. Unfortunately, it is not the case in Indonesia. I’ve never heard of any research department in a local telecommunication company and vendor products is installed without any independent testing, which often results in serious insecurities of telecommunication networks. For instance many products that haven’t received positive security approval from European telecoms are often being used in Indonesia.

I'd like to end this article with a quotation from CBN's web-site expressing the vision of the company:

As the leader among Internet Service Providers in Indonesia, CBN is working for a recognition as“The Brand You can Trust”.

Trust?! I leave comment on that to the growing number of readers of my Blog.

PS: If you are frustrated with service offered by your ISP, drop me an e-mail.

web statistics