I wonder how to deal with OutputStream
s in codenameone, which have to be kept open for a long time. There are many places, where they get written and it's be neither efficient nor error-proof to try to flush the stream everywhere. So I wrote this:
private boolean needsFlush;
private void write(byte[] data) throws IOException {
assert Display.getInstance().isEdt();
out.write(data);
if (!needsFlush) {
needsFlush = true;
Display.getInstance().callSerially(this::flush);
}
}
private void flush() {
try {
out.flush();
needsFlush = false;
} catch (final IOException e) {
throw new RuntimeException(e); // UGLY!
}
}
which should ensure that after every write, there'll be a flush sometime. Unless the app gets closed or alike.... that's why I need to ask.
stop()
of the "main" class?destroy()
?I would suggest closing the output stream on stop()
and re-opening it on start()
. Notice that if the stream points to FileSystemStorage
you can append to the end of the stream using CN's: OutputStream os = openFileOutputStream(filePath, lengthOfFile);
.
You need to close on stop()
as the app is sent to the background. In that state you should avoid open connections as they might be terminated suddenly by the OS. The entire app can be killed because of a wayward stream.
If you have background support in the app you should open and close the stream every time you need it.