问题
Oddly when I play a video using MediaPlayer
in a non-native way, after a few seconds (depending on the mobile phone settings) the power saving mode starts, which turns the screen off. This is an unwanted behavior, because when playing a video the screen must never turn off or dim. I don't understand if this is a Codename One bug or a feature, however it happens both on Android and iOS.
Apparently I fixed the problem using CN.setScreenSaverEnabled(false);
. My problem, however, is that it doesn't work all the time. The following code sometimes makes the screen stay active, sometimes it doesn't. I don't understand why sometimes it works and sometimes it doesn't.
To better understand the following code, videoUrl is an HLS stream.
private void playVideo(Form parent, String videoUrl) {
CN.setScreenSaverEnabled(false);
Form player = new Form(new BorderLayout());
player.getToolbar().setBackCommand("Back", Toolbar.BackCommandPolicy.ALWAYS, e -> {
if (mp != null) {
mp.getMedia().cleanup();
}
CN.setScreenSaverEnabled(true);
parent.showBack();
});
player.add(BorderLayout.CENTER, FlowLayout.encloseCenterMiddle(
new SpanLabel("Stream will start playing automatically when it is live")));
player.addShowListener(l -> {
while (!Util.downloadUrlToStorage(videoUrl, "temp.m3u8", false)) {
CN.invokeAndBlock(() -> Util.sleep(1000));
}
try {
// note that we cannot play the locally downloaded m3u8
Media video = MediaManager.createMedia(videoUrl, true, () -> {
// completion handler, it's invoked when the stream connection is lost
if (mp != null) {
mp.getMedia().cleanup();
}
CN.setScreenSaverEnabled(true);
parent.showBack();
});
video.setNativePlayerMode(false);
if (mp != null) {
mp.getMedia().cleanup();
}
mp = new MediaPlayer(video);
mp.setAutoplay(true);
mp.setHideNativeVideoControls(true);
mp.setMaximize(false);
player.removeAll();
player.add(BorderLayout.CENTER, mp);
player.revalidate();
} catch (Exception err) {
Log.e(err);
ToastBar.showErrorMessage("Error loading straming");
}
});
player.show();
}
来源:https://stackoverflow.com/questions/63007943/cn-setscreensaverenabledfalse-and-mediaplayer