问题
I need to notify something to the user every five minutes, regardless the app is running in foreground or background and regardless the user is using the smartphone or not.
My first attempt was to use "UITimer" + "Display.getInstance().vibrate(10000)", but the vibrate method doesn't do anything in my Android smartphone.
My next attempt was to the LocalNotification. Maybe the LocalNotification API documentation is not correct, because using 10 as time (like in the API example) produces a runtime exception (java.lang.IllegalArgumentException: Cannot schedule a notification to a past time
). I guessed that the time is from the epoch, so I wrote the following code. The problem is that it's not working as I need, because it notifies the message to the user only when the user is using the smartphone. I mean that the notification sound is played only when the user is touching the smartphone after "at least" five minutes, but if the user is not touching the smartphone no sound is played. It seems that the app is waiting for the user interaction before launching the notification.
To be more clear: I need something like an alarm clock that gets the user attention (with a sound and/or a vibration) every five minutes.
Form hi = new Form("Five minutes alert", BoxLayout.y());
hi.add(new Label("Five minutes alert"));
hi.show();
UITimer.timer(1000 * 60 * 5, true, () -> {
long time = Calendar.getInstance().getTime().getTime() + 1000;
LocalNotification ln = new LocalNotification();
ln.setId("LnMessage");
ln.setAlertTitle("Alert title");
ln.setAlertBody("Alert message");
ln.setAlertSound("/notification_sound_bell.mp3");
Display.getInstance().scheduleLocalNotification(ln, time, LocalNotification.REPEAT_NONE);
});
回答1:
The time is from System.currentTimeMillis()
i.e. absolute time. But local notification will only work properly when the app is in the background not when it's in the foreground.
Vibrate should work but might not have worked for your device if it's in complete mute mode.
来源:https://stackoverflow.com/questions/48069110/codename-one-notify-something-to-the-user-every-five-minutes