Delayed output from Cordova plugin

I wrote a Cordova plugin to upload a file and save it in a data folder. Everything is working fine except for the return value. I would like to display a progress bar and get the current progress. Here is the relevant part from my code:

while ((readed = is.read(buffer)) > 0) { fos.write(buffer, 0, readed); totalReaded += readed; int newProgress = (int) (totalReaded*100/fileSize); if (newProgress != progress) { progress = newProgress; PluginResult res = new PluginResult(PluginResult.Status.OK, progress); res.setKeepCallback(true); callbackContext.sendPluginResult(res); } } 

My JavaScript:

 downloader.prototype.writeFile = function (downloaderSuccess, downloaderFailure, options) { cordova.exec(downloaderSuccess, downloaderFailure, "downloader", "writeFile", options); }; function downloaderSuccess(progress) { WL.Logger.debug("Result: "+progress) } function downloaderFailure(error) { WL.Logger.error("Error: "+error); } 

It happens that the progress will be displayed only after downloading the file. If I set PluginResult.Status to NO_RESULT, it does not output anything.

+6
source share
1 answer

do you use

  cordova.getThreadPool().execute(new Runnable() { public void run() { // while loop goes here } }); 

at the beginning of your download code?

Take a look at src / org / apache / cordova / FileTransfer.java . These files do pretty much what you do, and you can see how they can send updates in real time, because they are in a separate stream.

I think the problem is that both JavaScript and Java code work in the same WebCore thread , so what happens is that the download blocks the connection between Java and the user interface (for example, sending the result) until the download is complete.

If you follow the recommendations in this guide to not block the WebCore thread (so use: cordova.getThreadPool().execute()) , you can receive progress updates.

To check this, I took this plugin: https://github.com/phonegap/phonegap-plugins/blob/master/Android/Downloader/Downloader.java which makes downloading files. Be that as it may, this code behaves the same as yours - an update of the progress is sent only after the file is downloaded. However, as soon as I wrapped the downloadUrl () method in runnable, it worked fine, sending progress updates as they occurred, rather than waiting for the end.

Please let me know if this helps, or if you want me to come up with a better explanation.

+4
source

All Articles