Codename One - UITimer when the app is in backgrou

2020-07-23 09:40发布

问题:

This question is related to a previous one: Codename One - Notify something to the user every five minutes

I discovered that UITimer doesn't work when the app is in background or when the smartphone is idle.

Consider the following code (tested on Android):

public void start() {
        if (current != null) {
            current.show();
            return;
        }
        Form hi = new Form("Five minutes alert", BoxLayout.y());
        hi.add(new Label("Alert every five minutes..."));
        Button button = new Button("Go to background");
        button.addActionListener(l -> {Display.getInstance().minimizeApplication();});
        hi.add(button);
        hi.show();
        sound();
        UITimer.timer(1000 * 60 * 5, true, () -> {
            sound();
        });
        Display.getInstance().minimizeApplication();
    }

    private void sound() {
        try {
            Media m = MediaManager.createMedia((Display.getInstance().getResourceAsStream(getClass(), "/bell.mp3")), "audio/mpeg");
            m.play();
        } catch (IOException err) {
            Log.e(err);
        }
    }

The problem is that when the app is opened the bell.mp3 is played, after that the app goes automatically to background, the smartphone becames idle (that means black screen) after few seconds (according to the Android settings), and the sound() method is not called after five minutes. It will be called when I wake up the smartphone (pressing the power button and moving one finger on the screen) and only after pressing the "home" button and putting the app on foreground. The problem is the same if the app is already on foreground but the smartphone is idle (that is its normal status when the user is not using it).

So, this is my question: I need to execute the sound() to play automatically a sound every five minutes (or to do something else). What is a correct method to do it?

回答1:

The EDT doesn't run in the background so no UITimer no callSerially etc. If we did run the EDT we'd consume battery resources and the OS would kill the app so that isn't something you'd want.

What you are probably looking for is background music which is discussed in the background music section here.



标签: codenameone