问题
What is a correct approach to deal with Internet connection unavailability (that is common on mobile devices)?
Maybe it's a big question (or maybe not), however I didn't find any Codename One tutorial / article / video or API to deal with an unstable Internet connection (that is the normality on mobile) without errors or unexpected behaviors. I've found an app (Protonmail) that has a functionality that I would like to replicate in my apps. Please look at the following two screenshot: the first one is taken when the Internet connection is available, the second one when it's not available.
I noted that the ToastBar appears not only when Internet is explicitly disabled, but every time that the server is not reachable. When the "No connectivity detected" message is shown, the app pauses the Internet activity, so no errors are generated (and the messages written by the user are not lost). When the app server returns to be reachable, the ToastBar disappears automatically (without pressing the "RETRY" button).
What is a correct way to implement a similar functionality in Codename One, in a way that is as most as possible independent from the specific app? Is it possible to suspend the Internet activity of a Codename One app and then restore it?
I'm imagining something like this:
- the app tries to do a simple request (like a ping) to a server every few seconds, implementing the performBackgroundFetch method;
- if there is no response in a fixed time (i.e. three seconds), the Internet activity is suspended and the ToastBar is shown;
- if there is response, the Internet activity is restored, the paused or failed downloads are restarted and the ToastBar disappears;
- ideally all of this should works also with a BrowserComponent.
回答1:
You can detect a networking error in the NetworkManager
class by using:
NetworkManager.getInstance().addErrorListener(e -> {
// prevents the error from propagating into the ConnectionRequest class
e.consume();
ToastBar.showMessage("Connectivity error, retry?", FontImage.MATERIAL_ERROR,
ee -> ee.getConnectionRequest().retry());
});
As explained here: https://www.codenameone.com/manual/files-storage-networking.html
The toast bar code just prompts in a similar way and offers a retry on the connection request. Notice that this is the generic global approach.
This will not work for things like browser component which connects on its own without "us". In there you will need to handle errors in the JavaScript side.
来源:https://stackoverflow.com/questions/45844443/codename-one-toastbar-when-no-connectivity-detected