Issue
I have an Android App written in Cordova. In this app I call a setInterval function with an interval of 100ms. When I am in foreground everything is fine but whenever I go to background I noticed that the function is called every 1s instead of 100ms.
A code for testing is this:
setInterval(function() {
console.log("Tick: " + new Date().getTime());
}, 100);
I really need this method to be called every 100ms in background. Furthermore, the device is always attached to a power supply so any performance related optimisations in the background I can ignore if it helps.
Does anybody know how I manage that the setInterval function is called every 100ms and not 1s when the app is in background?
Solution
I was looking for two days and the only solution I found is a workaround based on the cordova-plugin-background-mode.
Whenever you go to the background you can set the visibility of the webview to Visible with this method in your Java code
appView.getEngine().getView().dispatchWindowVisibilityChanged(View.VISIBLE))
then the interval is back to 100ms.
Sample code:
public class MainActivity extends CordovaActivity implements LifecycleObserver {
/* .. other code .. */
// init go to background observer
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void onToBackground() {
new Timer().schedule(new TimerTask() {
@Override
public void run() {
appView.getEngine().getView().dispatchWindowVisibilityChanged(View.VISIBLE);
}
}, 1000); // wait a second to make sure we are in background state
}
/* .. other code .. */
}
where appView is your CordovaWebView in your CordovaActivity.
Hope it helps if you have the same problem. If there is a better solution please let me know!
Answered By - vorwerg-ni
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.