Codename One - UITimer when the app is in backgroud or the smartphone is idle

限于喜欢 提交于 2019-12-12 09:08:51

问题


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.



来源:https://stackoverflow.com/questions/48122808/codename-one-uitimer-when-the-app-is-in-backgroud-or-the-smartphone-is-idle

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!