views:

456

answers:

3

I have a j2me midlet running on a cell phone. The code works fine, but the issue that comes up is that the program seems to be running more than one instance of itself. I have code at the beginning of the application inside the appStart() method that runs twice when the application starts. During the lifetime of the program, the code can be seen running twice when text is written to the screen.

The code looks like this:

public MyClass()
{
    form = new Form("MyProgram");
    cmdClose = new Command("EXIT", Command.EXIT, 1);

    form.addCommand(cmdClose);
    form.setCommandListener(this);

    display = Display.getDisplay(this);
    display.setCurrent(form);
}

public void startApp()
{
    form.append("App starting\n");
    // Rest of program
}

I have no idea why the code is being called twice.

I'm coding on the i290.

A: 

It might be a JVM issue, which phone are you using?

kiks
A: 

Maybe you did something that made the runtime call pauseApp() and then when you set the focus to the app the runtime called startApp() again.

Put logging in pauseApp() and see what happens.

Hans Malherbe
+2  A: 

This is definitely a JVM bug. startApp() should be called only once at startup and can't be called again until pauseApp() is called or you call notifyPaused() yourself.

What I suggest is the following code:

private boolean midletStarted = false;

public void startApp() {
    if (!midletStarted) {
        midletStarted = true;
        //Your code
    }
}

This way you can track midlet state changes. But in fact it is better that you don't use this method at all and use constructor instead.

Oh, by the way, I don't think that there are some multiple instances or something like that, this is merely a JVM error.

Malcolm
it need not be a JVM issue, because startApp() may be called in varioud instances, like when the phone screen dims off or due to various events that puts the applications to the background and foreground. The fix that you have given is correct however!
Ram
If the application is put to background, pauseApp() should be called in first place. In this case the bug would be not calling pauseApp() method, but it's still a bug anyway.
Malcolm
pauseApp() is not necessarily called in all implementations, rather the showNotify and hideNotify are being used. However your connotation is right!
Ram
A "midletStarted" boolean is absolutely the right way to deal with this, +1
funkybro