Coder Social home page Coder Social logo

cordova-plugin-background-download's Introduction

Background Download plugin for Apache Cordova

API provides an advanced file download functionality that persists beyond app termination, runs in the background and continues even when the user closed/suspended the application. The plugin includes progress updates and primarily designed for long-term transfer operations for resources like video, music, and large images.

Sample usage

    var fileName = "PointerEventsCordovaPlugin.wmv",
        uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv";
    
    // open target file for download
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
        fileSystem.root.getFile(fileName, { create: true }, function (targetFile) {
            
            var onSuccess, onError, onProgress; // plugin callbacks to track operation execution status and progress
    
            var downloader = new BackgroundTransfer.BackgroundDownloader();
            // Create a new download operation.
            var download = downloader.createDownload(uriString, targetFile);
            // Start the download and persist the promise to be able to cancel the download.
            app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress);
        });
    });

Internal vs External (SD card) storage on Android

  • External Storage

    resolve cordova.file.externalDataDirectory directory in runtime

    window.resolveLocalFileSystemURL(cordova.file.externalDataDirectory, function(dirEntry) {
            dirEntry.getFile(fileName, { create: true }, function (targetFile) {
                ...
            })
        }, function(error) {...})
    

    Note, that device can be without external storage. In this case cordova.file.externalDataDirectory will be null so it should be checked before usage.

  • Internal Storage

    resolve cordova.file.dataDirectory directory in runtime

    window.resolveLocalFileSystemURL(cordova.file.dataDirectory, function(dirEntry) {
            dirEntry.getFile(fileName, { create: true }, function (targetFile) {
                ...
            })
        }, function(error) {...})
    

Read File Plugin quirks for more details:

Supported platforms

  • Windows8
  • Windows Phone8
  • iOS 7.0 or later
  • Android

Quirks

  • If a download operation was completed when the application was in the background, onSuccess callback is called when the application become active.
  • If a download operation was completed when the application was closed, onSuccess callback is called right after the first startAsync() is called for the same uri, as if the file has been downloaded immediately.
  • A new download operation for the same uri resumes a pending download instead of triggering a new one. If no pending downloads found for the uri specified, a new download is started, the target file will be automatically overwritten once donwload is completed.
  • On Android temporary downloading file is created on external storage (limitation of DownloadManager), so if there is no external storage the downloading will fail.

cordova-plugin-background-download's People

Contributors

eiriksm avatar itsravenous avatar mzealey avatar nicktoropov avatar sgrebnov avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cordova-plugin-background-download's Issues

Error Installing cordova-plugin-background-download

I`m gettting the error below when I try to install this plugin on Mac:

0 info it worked if it ends with ok
1 verbose cli [ '/usr/local/bin/node',
1 verbose cli   '/usr/local/bin/npm',
1 verbose cli   'install',
1 verbose cli   'https://github.com/sgrebnov/cordova-plugin-background-download.git',
1 verbose cli   '--production',
1 verbose cli   '--save' ]
2 info using [email protected]
3 info using [email protected]
4 verbose npm-session 540257cedfdee7e8
5 silly install loadCurrentTree
6 silly install readLocalPackageData
7 silly fetchPackageMetaData error for git+https://github.com/sgrebnov/cordova-plugin-background-download.git Non-registry package missing package.json: git+https://github.com/sgrebnov/cordova-plugin-background-download.git.
8 verbose stack Error: Non-registry package missing package.json: git+https://github.com/sgrebnov/cordova-plugin-background-download.git.
8 verbose stack     at BB.join (/usr/local/lib/node_modules/npm/node_modules/pacote/lib/finalize-manifest.js:160:23)
8 verbose stack     at tryCatcher (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/util.js:16:23)
8 verbose stack     at Holder$5._callFunction (eval at generateHolderClass (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:92:16), <anonymous>:14:44)
8 verbose stack     at Holder$5.checkFulfillment (eval at generateHolderClass (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:92:16), <anonymous>:29:30)
8 verbose stack     at Promise.eval (eval at thenCallback (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/join.js:14:16), <anonymous>:6:20)
8 verbose stack     at Promise._settlePromise (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:566:21)
8 verbose stack     at Promise._settlePromise0 (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:614:10)
8 verbose stack     at Promise._settlePromises (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/promise.js:693:18)
8 verbose stack     at Async._drainQueue (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:133:16)
8 verbose stack     at Async._drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:143:10)
8 verbose stack     at Immediate.Async.drainQueues (/usr/local/lib/node_modules/npm/node_modules/bluebird/js/release/async.js:17:14)
8 verbose stack     at runCallback (timers.js:789:20)
8 verbose stack     at tryOnImmediate (timers.js:751:5)
8 verbose stack     at processImmediate [as _immediateCallback] (timers.js:722:5)
9 verbose cwd /Users/ulyssesalves/Desktop/Dev/Projetos/playervozdosetimoanjo/player-voz-do-ceu-cordova
10 verbose Darwin 17.0.0
11 verbose argv "/usr/local/bin/node" "/usr/local/bin/npm" "install" "https://github.com/sgrebnov/cordova-plugin-background-download.git" "--production" "--save"
12 verbose node v8.9.0
13 verbose npm  v5.5.1
14 error code ENOPACKAGEJSON
15 error package.json Non-registry package missing package.json: git+https://github.com/sgrebnov/cordova-plugin-background-download.git.
16 error package.json npm can't find a package.json file in your current directory.
17 verbose exit [ 1, true ]

Empty file for multiple downloads

Hi!

I'm trying to get multiple files in iOS, I have something like this:

//save multiple files within the same directory, event is fired after directory creation
$scope.$on( "createDir", function() {
      toDownload.forEach(function( value, index ) { //iterate through an array of urls

        var fileName = URI(value).filename(), //extracting the filename from the original file
        uriString = value; // the url value from the current array index

        // open target file for download
        window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {

        fileSystem.root.getFile( directoryName + '/' + fileName, { create: true }, function (targetFile) {
            var downloader = new BackgroundTransfer.BackgroundDownloader();
            // Create a new download operation.
            var download = downloader.createDownload( uriString, targetFile );
            // Start the download and persist the promise to be able to cancel the download.
            promises.push( download.startAsync() ); //added to an array since we'll use angular's $q.all(promises).then [...]
          });

        });

      });

      $q.all(promises).then(function(res) {
         // etc...
      });
    });

Checking the downloaded files it seems that only the last file is been written and the others are 0 bytes.
I tried to live check the directory and I noticed that the last file changes size up and down during download, so I'm pretty sure that the download of all the files works but they are written sequentially on the same file (the last one).

Any hint? Thank you in advance! :)

ps what about porting https://github.com/thibaultCha/TCBlobDownload ?

--- UPDATE ---
I solved for now by downloading a zip and unzipping onSuccess. I was wondering if I can notify the user somehow when the download ends and the app is in background mode. Ideas?

Works only on first app run

Hi there!

First of all, thank you for great plugin. It's almost fine, but... works only on first app run.

I use it to download some zip files to local storage after app is installed (to make it more lightweight). So, after one file is downloaded, the other download starts. Everything is working fine, even if I suspend app or turn on airplane mode. But if I exit app (totally exit) - on next run my code tries to download unfinished file one more time - and nothing happens. No error from your functions, simply nothing happens...

Please, help... Maybe, problem is caused by your magical solution, that allows download process to run even when app is closed (you've written this in description)?

window.downloadTopic = function(topic,version){ var fileName = topic + ".zip", uriString = "https://storage.googleapis.com/myappdownload/" + topic + "_" + version + ".zip"; window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) { fileSystem.root.getFile(fileName, { create: true, exclusive: false }, function (targetFile) { var downloader = new BackgroundTransfer.BackgroundDownloader(); var download = downloader.createDownload(uriString, targetFile); app.downloadPromise = download.startAsync().then( function(){ zip.unzip(targetFile.nativeURL, targetFile.nativeURL.slice(0, -4), function(result){ if(result === -1) { window.current_topic_downloading = false; window.addStatEvent('Download: error while unzip'); } else { window.localStorage.setItem(window.current_topic_downloading+"_downloaded", 1); window.localStorage.setItem(window.current_topic_downloading+"_version", window.current_topic_downloading_version); window.current_topic_downloading = false; window.downloadNextTopic(); } }); }, function(){ window.current_topic_downloading = false; window.downloadNextTopic(); window.addStatEvent('Download: error while downloading'); }); }, function(){ window.current_topic_downloading = false; window.downloadNextTopic(); window.addStatEvent('Download: error creating local zip file'); }); }); }; window.downloadNextTopic = function(){ if(!window.current_topic_downloading && (typeof window.topics_to_download !== "undefined")) { for (let topic_cur_name in window.topics_to_download) { if(!parseInt(window.localStorage.getItem(topic_cur_name+"_downloaded")) || (parseInt(window.localStorage.getItem(topic_cur_name+"_version")) !== parseInt(window.topics_to_download[topic_cur_name]))) { window.localStorage.setItem(topic_cur_name+"_downloaded", 0); window.current_topic_downloading = topic_cur_name; window.current_topic_downloading_version = window.topics_to_download[topic_cur_name]; window.downloadTopic(topic_cur_name,window.topics_to_download[topic_cur_name]); break; } } } }; $.getJSON("downloads.json", function(result) { window.topics_to_download = result; window.current_topic_downloading = false; for (let topic_cur_name in window.topics_to_download) { if(window.localStorage.getItem(topic_cur_name+"_downloaded") == null) { window.localStorage.setItem(topic_cur_name+"_downloaded", 0); } if(window.localStorage.getItem(topic_cur_name+"_version") == null) { window.localStorage.setItem(topic_cur_name+"_version", 0); } } window.downloadNextTopic(); });

Cannot download to the internal storage

I am using this plugin to download files to Android device's /data/data/myAppName, which is the path where the app is installed.

var downloader = new BackgroundTransfer.BackgroundDownloader();
var download = downloader.createDownload(uriString, targetFile);

download = download.startAsync().then(onSuccess, onError, onProgress);
...

However I get an exception:

Destination must be on external storage

Any suggestions?

Can't supply headers to download request

I'd love to try out this plugin but it seems that you can't supply a list of headers to the plugin to be associated with the download request?

Given cases where the download might be behind some kind of security wall this seems like a potentially useful addition?

Any plans on adding this in?

Identify Download Error Reason

Is there any means by which I could check a download failure reason? For example, Apache Cordova's official FileTransfer plugin has a FileTransferError which says us if the error was because of a network connection failure or because the file was not found.

I need this information because sometimes the network info plugin is giving wrong information about the network status. Specifically, it says the current network type is "wi-fi" for a short period after the device has been disconnected. That is, it looks like to be a delay before the network info plugin to change from "wi-fi" to "none" after the device has been disconnected.

Agreed, I can always set a timeout in javascript before I check the network status, but I just don't feel this would be the most appropriate solution for this issue, and I think an "download failure reason" info would be very great.

Issues with downloads from Akamai servers

I am running into some issues when I attempt to download videos from Akamai servers, and I was hoping to get some insight;

For example, for the following two urls, the first video downloads as expected, but the second video fails.

  1. Served via Varnish: https://cdn.jwplayer.com/videos/x3tmUfxs.mp4 -> Works
  2. Served via AmazonS3: https://cdn.jwplayer.com/videos/TYW5TJBi.mp4 -> Fails
    Downloads what appears to be a webpage, but the contents are;
<HTML><HEAD>
<TITLE>Access Denied</TITLE>
</HEAD><BODY>
<H1>Access Denied</H1>
</BODY>
</HTML>

I spoke with the engineers that manage the server setup and hosting for our content, here is what they had to say;

Their request to videos-a is being made with a cookie that wasn't set by anything and is an invalid signing cookie, so Akamai is rejecting their request. hdntl is an Akamai cookie. I have no idea what is setting it, nothing in that chain of requests/responses sets it so it must be something they are doing in their application.

if android hasn't Sd card,can't download!

can make sub-directory in /data/data ,but can't create file. error code like this:
Writing exception to parcel
java.lang.SecurityException: Unsupported path /data/user/0/***/files/22940/001_mj.mp3.temp
at com.android.providers.downloads.DownloadProvider.checkFileUriDestination(DownloadProvider.java:735)
at com.android.providers.downloads.DownloadProvider.insert(DownloadProvider.java:558)
at android.content.ContentProvider$Transport.insert(ContentProvider.java:263)
at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:163)
at android.os.Binder.execTransact(Binder.java:453)

WindowsPhone 8.1: BackgroundTransferRequest TransferPreferences

Hi,
I've just found a issue on WP 8.1
According to
https://msdn.microsoft.com/en-us/library/windows/apps/microsoft.phone.backgroundtransfer.transferpreferences%28v=vs.105%29.aspx?cs-save-lang=1&cs-lang=csharp&f=255&MSPPError=-2147217396#code-snippet-1

BackgroundTransferRequest has TransferPreferences value set to None by default, which means it allow file transfer only (!) if you are connected to external power and WiFi.
In other case "transfer.TransferStatus" will have value "TransferStatus.WaitingForExternalPower" and script will not begin dowloading until you connect your phone to charger or computer.

I've done a workaround in src/wp/BackgroundDowload.cs @ line 74

transfer = new BackgroundTransferRequest(requestUri, downloadLocation);
transfer.TransferPreferences = TransferPreferences.AllowCellularAndBattery;

But maybe you should consider to set this value as function optional parameter?

For android, method CleanUp should be called in stop method

For android, method CleanUp should be called in stop method to remove activDownloads keys via activDownloads.remove(curDownload.getUriString());
otherwise, re-downloading the same url would not execute since activDownloads keys existence would be checked in startAsync method.

Error: Unsupported path

When I try to download a file then I'm getting the error:

Unsupported path /data/data/com.my.App/files/files/PointerEventsCordovaPlugin.wmv.temp

Android: 6.0.1

Any ideas?

This is my code (Video is still available @ channel 9):

var fileName = "PointerEventsCordovaPlugin.wmv",
        uriString = "http://media.ch9.ms/ch9/8c03/f4fe2512-59e5-4a07-bded-124b06ac8c03/PointerEventsCordovaPlugin.wmv";

    // open target file for download
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSystem) {
        fileSystem.root.getFile(fileName, { create: true }, function (targetFile) {

            var onSuccess, onError, onProgress; // plugin callbacks to track operation execution status and progress

            onSuccess = function() {
                console.log("Ready!!!");
            };

            onError = function(err) {
                console.log('Error: ' + err);
            };

            var downloader = new BackgroundTransfer.BackgroundDownloader();
            // Create a new download operation.
            var download = downloader.createDownload(uriString, targetFile);
            // Start the download and persist the promise to be able to cancel the download.
            app.downloadPromise = download.startAsync().then(onSuccess, onError, onProgress);
        });
    });   

App crash with S3 urls

Hi!
When I try to download a file from s3 with temporary access parameters the app close itself.

The url is like this one: https:/bucketName.s3.eu-central-1.amazonaws.com/path/to/file.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKRTUJFHHDSS2A%2F20150914%2Feu-central-1%2Fs3%2Faws4_request&X-Amz-Date=20150914T095952Z&X-Amz-SignedHeaders=Host&X-Amz-Expires=3600&X-Amz-Signature=i3a4ol3n0tewpe7xvgay7kxui6znkphx

Any ideas?

Set sessionSendsLaunchEvents to YES

Hi, I'm trying to use your plugin to allow my app to continue to download files when the app is in teh background. In my case, I'm downloading a large file chunked into small pieces, so I potentially have to dlownload 100-200 files. I'd like the app to be woken up after each download is complete. It seems that this could be achieved by setting the sessionSendsLaunchEvents property to YES, as specified here:

https://developer.apple.com/library/content/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html

Is there any reason that this is not done by this plugin?

Crash upon download completion

Hey there.

For some reason on Android once a download finishes the plugin (and consequently my app) crashes. Using adb logcat I was able to pull together a stack trace (and find that it's because of a NullPointerException), but unfortunately I'm not super familiar with the Android API and so I was hoping you'd be able to provide some help?

E/AndroidRuntime(18302): Process: com.ionicframework.myapp201347, PID: 18302

E/AndroidRuntime(18302): java.lang.RuntimeException: Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=com.ionicframework.myapp201347 (has extras) } in org.apache.cordova.backgroundDownload.BackgroundDownload$2@42b63d10

E/AndroidRuntime(18302):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:782)

E/AndroidRuntime(18302):    at android.os.Handler.handleCallback(Handler.java:733)

E/AndroidRuntime(18302):    at android.os.Handler.dispatchMessage(Handler.java:95)

E/AndroidRuntime(18302):    at android.os.Looper.loop(Looper.java:157)

E/AndroidRuntime(18302):    at android.app.ActivityThread.main(ActivityThread.java:5293)

E/AndroidRuntime(18302):    at java.lang.reflect.Method.invokeNative(Native Method)

E/AndroidRuntime(18302):    at java.lang.reflect.Method.invoke(Method.java:515)

E/AndroidRuntime(18302):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)

E/AndroidRuntime(18302):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)

E/AndroidRuntime(18302):    at de.robv.android.xposed.XposedBridge.main(XposedBridge.java:132)

E/AndroidRuntime(18302):    at dalvik.system.NativeStart.main(Native Method)

E/AndroidRuntime(18302): Caused by: java.lang.NullPointerException

E/AndroidRuntime(18302):    at org.apache.cordova.backgroundDownload.BackgroundDownload.CleanUp(BackgroundDownload.java:236)

E/AndroidRuntime(18302):    at org.apache.cordova.backgroundDownload.BackgroundDownload.access$100(BackgroundDownload.java:46)

E/AndroidRuntime(18302):    at org.apache.cordova.backgroundDownload.BackgroundDownload$2.onReceive(BackgroundDownload.java:385)

E/AndroidRuntime(18302):    at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:772)

Download fails on Android 13

All downloads fail with error message

Unsupported path /storage/emulated/0/ ......

Work with file system needs update.

Download does not terminate on Android 6

On Android 6, some downloads never terminate. I think our custom BroadcastReceiver is not properly registered for some reason.

In the console, I get Progress Object {bytesReceived: 559, totalBytesToReceive: 559} indefinitely every second. Any ideas?

Problem with progress when downloading large file

I am downloading a multi megabyte file from google drive on iOS and the value totalBytesExpectedToWrite is -1, presumably because the HTTP connection is chunked. This results in the most interesting progress percentages. I guess with chunking you will never know the length of the file up front. So either the progress should just stick at 50% or use some kind of geometric progression to 100%.

Either way the current int overflow is not a good result.

Occasional crash on android

Seeing occasional crash on android for some users:

java.lang.RuntimeException: 
  at android.app.LoadedApk$ReceiverDispatcher$Args.run (LoadedApk.java:1003)
  at android.os.Handler.handleCallback (Handler.java:739)
  at android.os.Handler.dispatchMessage (Handler.java:95)
  at android.os.Looper.loop (Looper.java:158)
  at android.app.ActivityThread.main (ActivityThread.java:7229)
  at java.lang.reflect.Method.invoke (Native Method)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
  at com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)

Caused by: java.lang.NullPointerException: 
  at org.apache.cordova.backgroundDownload.BackgroundDownload.CleanUp (BackgroundDownload.java:237)
  at org.apache.cordova.backgroundDownload.BackgroundDownload.access$100 (BackgroundDownload.java:46)
  at org.apache.cordova.backgroundDownload.BackgroundDownload$2.onReceive (BackgroundDownload.java:386)
  at android.app.LoadedApk$ReceiverDispatcher$Args.run (LoadedApk.java:993)

From the trace it appears that the

            } finally {
                CleanUp(curDownload);
            }

can sometimes be called with a null curDownload which is presumably why the exception happens.

Perhaps:

            Download curDownload = activDownloads.get(uri);
            if( !curDownload ) return;

would be a good fix.

Is this an NMP plugin active?

Hi! is active this plugin? because when i try to compile it , phonegap says
Error - The following plugin, plugin version or a dependancy of this plugin is not on npm: cordova-plugin-background-download

iOS: File downloads ok but file writes empty file.

Cordova 3.5
OSX 10.9

Using iPhone simulator running iOS 7.1. Using the test files included in the repo.

The download file gets written to the temporary directory fine (monitored it with watch ls) but the written file in the app's Documents folder is empty.

Did a little debugging; the data passed into fileManager createFileAtPath is the correct length. The create file call returns false, but I'm not very familiar at all with Objective C so not sure how to investigate further.

Going to try on a real device tomorrow.

Unsupported path android

Hey!

I'm trying to download a jpg file.

  • it works on IOS
  • on andoid I have an error: "Unsupported path /data/data/{app}/files/files/{id}.jpg.temp"

This is my code:

window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, (fileSystem) => {
   fileSystem.root.getFile("${id}.jpg", {create: true, exclusive: true}, (targetFile) => {
     const url = "https://${process.env.API_ENDPOINT}/Preview/${id}";
      var downloader = new BackgroundTransfer.BackgroundDownloader();
      // Create a new download operation.
      var download = downloader.createDownload(url, targetFile);
      // Start the download and persist the promise to be able to cancel the download.
      download.startAsync().then(() => {
        //succes
      }, (error) => {
        console.log('onError', id, error);
      }, (progress) => {
        console.log('onProgress', id, progress);
      });
   });
});

The solution in #28 is not a good solution for me since it has to be stored on the internal storage of the application itself.

Change appearance of the 'Download Manager' when download is processing

I have the background downloading process working and it appears to work well (on Android not tried iOS yet) however is it possible to alter the notification bar that appears?

Currently it has the title 'Download Manager' with `org.apache.cordova.backgroundDownload plugin' - is it possible to alter this easily?

why my app for ios download complete the size is 0 byte

const fileTransfer = new BackgroundTransfer.BackgroundDownloader();
console.log(item.fileUrl+"===="+targetPath)
File.createFile(targetPath,filename,false).then(entry=>{

      let download = fileTransfer.createDownload(item.fileUrl, entry);
      download.startAsync().then((entry) => {
        self.addToDownloaded(item);
        resolve(item);
        item['filePath'] = targetPath;
        // VideoUtils.playVideo(targetPath);
        // self.events.publish('download:done');
      }, (error) => {
        reject(error);
        // self.events.publish('download:error');
      }, (progressEvent) => {
        this.ngZone.run(() => {
          if (!!progressEvent) {
            onProgress(progressEvent);
          }
        });
      });

Error: ReferenceError: BackgroundTransfer is not defined

I have installed the cordova-file-plugin however I am always getting the error Error: ReferenceError: BackgroundTransfer is not defined when I open the app on my device and view the Chrome console logs.

What am I doing wrong? Note I am using cordova android 6.4.0 as I know newer version have some issues

Problem cancelling the download promise

My app crashes when I try to cancel my download promise. It seems that when the download process is completed, the BroadcastReceiver tries to manage the download and throw some exception.

Here's what I got:
Error receiving broadcast Intent { act=android.intent.action.DOWNLOAD_COMPLETE flg=0x10 pkg=com.teste.download (has extras) } in org.apache.cordova.backgroundDownload.BackgroundDownload at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:737) at android.os.Handler.handleCallback(Handler.java:605) at android.os.Handler.dispatchMessage(Handler.java:92) at android.os.Looper.loop(Looper.java:137) at android.app.ActivityThread.main(ActivityThread.java:4514) at java.lang.reflect.Method.invokeNative(Native Method) at java.lang.reflect.Method.invoke(Method.java:511) at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557) at dalvik.system.NativeStart.main(Native Method) Caused by: android.database.CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0

Background failing on Android 12

On Android 12, when the app is minimised the downloading stops. On reopening the app, the download continues.

Steps to replicate
Case 1:

  1. start a download
  2. put the app on background, don’t kill it
  3. come back 5 mins later
  4. download will be stuck

Case 2:

  1. start a download
  2. lock the phone
  3. come back 5 mins later
  4. download will be stuck

Issue is only present on Android 12. Tested the above cases on Android 6, 9, 11 and have passed.

For windows phone 8.1 and windows phone 10 big sized file is not working

Hi,

I used your plugin and it's working good with android with 4 - 5 MB ( i tested only this sized only don't know about more then it ) but same file i am going to download in windows phone 8.1 and windows phone 10 app is crashing , because app crashed can't able to get logs also, can you help me in this, it's quite urgent.

try to download less then 1 MB it's working like charm in windows phones.

Thank you

Download very slow on Android 6

The plugin worked fine in KitKat. But when I test my app in Android 6 device, it takes ~2 minutes to download a simple image file that took a second to download in KitKat device.

Any suggestions on what might be wrong? Is it a bug?

edit

The downloads are not slow; they are not starting on time.

The downloads get stuck at STATUS_PAUSED status, with the reason PAUSED_WAITING_TO_RETRY. They eventually start. I don't have any network issues, and tested this across multiple Android 6 devices and networks, but still have the same issue.

Android permissions not specified in plugin.xml

I think according to the Cordova plugin spec plugin.xml is supposed to indicate which Android permissions the plugin requires.

I didn't have time to investigate exactly how they should be specified, so I just added the permissions directly to my AndroidManifest.xml, but for reference the permissions I needed were INTERNET and WRITE_EXTERNAL_STORAGE.

BTW, thanks for the fantastic plugin. I was very excited to see that on Android I get a progress bar in the notifications area :)

Get a 403 if I use request.setVisibleInDownloadsUi(true);

Hi @sgrebnov,

I was trying to use your plugin and I was wondering, why you need to use this line:
request.setVisibleInDownloadsUi(false);
https://github.com/sgrebnov/cordova-plugin-background-download/blob/master/src/android/BackgroundDownload.java#L175

I want to make the downloaded file visible in the Downloads UI, so I set that to true (which is the default value):
request.setVisibleInDownloadsUi(true);

and I also tried commenting that line.

Both times the downloads failed and the reason is 403 (Forbidden).

Do you know if there is a way to make the downloads visible in Downloads UI?

Thanks in advance and congrats for this excellent plugin.

Not converting temp files after successful download

There are two situations when this is happening:

  • I get an error saying "Cannot copy from temporary path to actual path"
  • No errors at all are shown. However, the file shows 0 MB. When checked in the filemanager, we see that there are two files, eg, abc.mp3 and abc.mp3.temp. The abc.mp3 file has 0 MB, while the actual download has happened to the temp file. For some reason, we feel the function copyTempFileToActualFile is not called. Wanted to know what scenarios can this happen.

We need to handle both these scenarios as our mobile app on android is not able to play the music file that it downloaded. This issue is not consistently happening. We feel there is a possibility of network speed or something causing it to happen sometimes. Please advise on help to handle these issues.

Thanks & Regards,
Naresh.

Question or Feature-Request: Pause/Resume download in case of network events

Hello,
i use this great plugin for downloading bigger content from my server in background. Works nice so far for me.
But there is one thing:
Because download-costs are higher when downlading in public networks with 3G or even LTE it would be great if the plugin could pause downloading and resume if in wlan.

any ideas are welcome

kind regards
Matthias

iOS background download stops on app close

When app goes to background, the content is still downloading. but when the app is closed in middle of download, the download also stops.

Is that bug in iOS or I am missing something?

Concurrent downloads in iOS

Hello,

We are using this plugin for iOS app, but the One-File-at-a-time limitation is a really bother one.

Are there any chances of removing this limitation. It would be of great help.

Thanks!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.