1 /* ownCloud Android client application
2 * Copyright (C) 2012 Bartek Przybylski
3 * Copyright (C) 2012-2015 ownCloud Inc.
5 * This program is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License version 2,
7 * as published by the Free Software Foundation.
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
14 * You should have received a copy of the GNU General Public License
15 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19 package com
.owncloud
.android
.files
.services
;
22 import java
.io
.IOException
;
23 import java
.util
.AbstractList
;
24 import java
.util
.HashMap
;
25 import java
.util
.Iterator
;
27 import java
.util
.Vector
;
29 import com
.owncloud
.android
.R
;
30 import com
.owncloud
.android
.authentication
.AccountUtils
;
31 import com
.owncloud
.android
.authentication
.AuthenticatorActivity
;
32 import com
.owncloud
.android
.datamodel
.FileDataStorageManager
;
33 import com
.owncloud
.android
.datamodel
.OCFile
;
35 import com
.owncloud
.android
.lib
.common
.network
.OnDatatransferProgressListener
;
36 import com
.owncloud
.android
.lib
.common
.OwnCloudAccount
;
37 import com
.owncloud
.android
.lib
.common
.OwnCloudClient
;
38 import com
.owncloud
.android
.lib
.common
.OwnCloudClientManagerFactory
;
39 import com
.owncloud
.android
.notifications
.NotificationBuilderWithProgressBar
;
40 import com
.owncloud
.android
.notifications
.NotificationDelayer
;
41 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
;
42 import com
.owncloud
.android
.lib
.common
.operations
.RemoteOperationResult
.ResultCode
;
43 import com
.owncloud
.android
.lib
.common
.utils
.Log_OC
;
44 import com
.owncloud
.android
.lib
.resources
.files
.FileUtils
;
45 import com
.owncloud
.android
.operations
.DownloadFileOperation
;
46 import com
.owncloud
.android
.ui
.activity
.FileActivity
;
47 import com
.owncloud
.android
.ui
.activity
.FileDisplayActivity
;
48 import com
.owncloud
.android
.ui
.preview
.PreviewImageActivity
;
49 import com
.owncloud
.android
.ui
.preview
.PreviewImageFragment
;
50 import com
.owncloud
.android
.utils
.ErrorMessageAdapter
;
52 import android
.accounts
.Account
;
53 import android
.accounts
.AccountManager
;
54 import android
.accounts
.AccountsException
;
55 import android
.accounts
.OnAccountsUpdateListener
;
56 import android
.app
.NotificationManager
;
57 import android
.app
.PendingIntent
;
58 import android
.app
.Service
;
59 import android
.content
.Intent
;
60 import android
.os
.Binder
;
61 import android
.os
.Handler
;
62 import android
.os
.HandlerThread
;
63 import android
.os
.IBinder
;
64 import android
.os
.Looper
;
65 import android
.os
.Message
;
66 import android
.os
.Process
;
67 import android
.support
.v4
.app
.NotificationCompat
;
68 import android
.util
.Pair
;
70 public class FileDownloader
extends Service
71 implements OnDatatransferProgressListener
, OnAccountsUpdateListener
{
73 public static final String EXTRA_ACCOUNT
= "ACCOUNT";
74 public static final String EXTRA_FILE
= "FILE";
76 private static final String DOWNLOAD_ADDED_MESSAGE
= "DOWNLOAD_ADDED";
77 private static final String DOWNLOAD_FINISH_MESSAGE
= "DOWNLOAD_FINISH";
78 public static final String EXTRA_DOWNLOAD_RESULT
= "RESULT";
79 public static final String EXTRA_FILE_PATH
= "FILE_PATH";
80 public static final String EXTRA_REMOTE_PATH
= "REMOTE_PATH";
81 public static final String EXTRA_LINKED_TO_PATH
= "LINKED_TO";
82 public static final String ACCOUNT_NAME
= "ACCOUNT_NAME";
84 private static final String TAG
= "FileDownloader";
86 private Looper mServiceLooper
;
87 private ServiceHandler mServiceHandler
;
88 private IBinder mBinder
;
89 private OwnCloudClient mDownloadClient
= null
;
90 private Account mCurrentAccount
= null
;
91 private FileDataStorageManager mStorageManager
;
93 private IndexedForest
<DownloadFileOperation
> mPendingDownloads
= new IndexedForest
<DownloadFileOperation
>();
95 private DownloadFileOperation mCurrentDownload
= null
;
97 private NotificationManager mNotificationManager
;
98 private NotificationCompat
.Builder mNotificationBuilder
;
99 private int mLastPercent
;
102 public static String
getDownloadAddedMessage() {
103 return FileDownloader
.class.getName() + DOWNLOAD_ADDED_MESSAGE
;
106 public static String
getDownloadFinishMessage() {
107 return FileDownloader
.class.getName() + DOWNLOAD_FINISH_MESSAGE
;
111 * Service initialization
114 public void onCreate() {
116 Log_OC
.d(TAG
, "Creating service");
117 mNotificationManager
= (NotificationManager
) getSystemService(NOTIFICATION_SERVICE
);
118 HandlerThread thread
= new HandlerThread("FileDownloaderThread", Process
.THREAD_PRIORITY_BACKGROUND
);
120 mServiceLooper
= thread
.getLooper();
121 mServiceHandler
= new ServiceHandler(mServiceLooper
, this);
122 mBinder
= new FileDownloaderBinder();
124 // add AccountsUpdatedListener
125 AccountManager am
= AccountManager
.get(getApplicationContext());
126 am
.addOnAccountsUpdatedListener(this, null
, false
);
134 public void onDestroy() {
135 Log_OC
.v(TAG
, "Destroying service");
137 mServiceHandler
= null
;
138 mServiceLooper
.quit();
139 mServiceLooper
= null
;
140 mNotificationManager
= null
;
142 // remove AccountsUpdatedListener
143 AccountManager am
= AccountManager
.get(getApplicationContext());
144 am
.removeOnAccountsUpdatedListener(this);
151 * Entry point to add one or several files to the queue of downloads.
153 * New downloads are added calling to startService(), resulting in a call to this method.
154 * This ensures the service will keep on working although the caller activity goes away.
157 public int onStartCommand(Intent intent
, int flags
, int startId
) {
158 Log_OC
.d(TAG
, "Starting command with id " + startId
);
160 if (!intent
.hasExtra(EXTRA_ACCOUNT
) ||
161 !intent
.hasExtra(EXTRA_FILE
)
163 Log_OC
.e(TAG
, "Not enough information provided in intent");
164 return START_NOT_STICKY
;
166 final Account account
= intent
.getParcelableExtra(EXTRA_ACCOUNT
);
167 final OCFile file
= intent
.getParcelableExtra(EXTRA_FILE
);
170 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
171 "Received request to download file"
174 AbstractList
<String
> requestedDownloads
= new Vector
<String
>();
176 DownloadFileOperation newDownload
= new DownloadFileOperation(account
, file
);
177 newDownload
.addDatatransferProgressListener(this);
178 newDownload
.addDatatransferProgressListener((FileDownloaderBinder
) mBinder
);
179 Pair
<String
, String
> putResult
= mPendingDownloads
.putIfAbsent(
180 account
, file
.getRemotePath(), newDownload
182 String downloadKey
= putResult
.first
;
183 requestedDownloads
.add(downloadKey
);
185 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
186 "Download on " + file.getRemotePath() + " added to queue"
189 // Store file on db with state 'downloading'
191 TODO - check if helps with UI responsiveness, letting only folders use FileDownloaderBinder to check
192 FileDataStorageManager storageManager = new FileDataStorageManager(account, getContentResolver());
193 file.setDownloading(true);
194 storageManager.saveFile(file);
197 sendBroadcastNewDownload(newDownload
, putResult
.second
);
199 } catch (IllegalArgumentException e
) {
200 Log_OC
.e(TAG
, "Not enough information provided in intent: " + e
.getMessage());
201 return START_NOT_STICKY
;
204 if (requestedDownloads
.size() > 0) {
205 Message msg
= mServiceHandler
.obtainMessage();
207 msg
.obj
= requestedDownloads
;
208 mServiceHandler
.sendMessage(msg
);
213 return START_NOT_STICKY
;
218 * Provides a binder object that clients can use to perform operations on the queue of downloads,
219 * excepting the addition of new files.
221 * Implemented to perform cancellation, pause and resume of existing downloads.
224 public IBinder
onBind(Intent arg0
) {
230 * Called when ALL the bound clients were onbound.
233 public boolean onUnbind(Intent intent
) {
234 ((FileDownloaderBinder
) mBinder
).clearListeners();
235 return false
; // not accepting rebinding (default behaviour)
239 public void onAccountsUpdated(Account
[] accounts
) {
240 //review the current download and cancel it if its account doesn't exist
241 if (mCurrentDownload
!= null
&&
242 !AccountUtils
.exists(mCurrentDownload
.getAccount(), getApplicationContext())) {
243 mCurrentDownload
.cancel();
245 // The rest of downloads are cancelled when they try to start
250 * Binder to let client components to perform operations on the queue of downloads.
252 * It provides by itself the available operations.
254 public class FileDownloaderBinder
extends Binder
implements OnDatatransferProgressListener
{
257 * Map of listeners that will be reported about progress of downloads from a {@link FileDownloaderBinder}
260 private Map
<Long
, OnDatatransferProgressListener
> mBoundListeners
=
261 new HashMap
<Long
, OnDatatransferProgressListener
>();
265 * Cancels a pending or current download of a remote file.
267 * @param account ownCloud account where the remote file is stored.
268 * @param file A file in the queue of pending downloads
270 public void cancel(Account account
, OCFile file
) {
272 "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
273 "Received request to cancel download of " + file.getRemotePath()
275 Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
276 "Removing download of " + file.getRemotePath());*/
277 Pair
<DownloadFileOperation
, String
> removeResult
=
278 mPendingDownloads
.remove(account
, file
.getRemotePath());
279 DownloadFileOperation download
= removeResult
.first
;
280 if (download
!= null
) {
281 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
282 "Canceling returned download of " + file.getRemotePath());*/
285 if (mCurrentDownload
!= null
&& mCurrentAccount
!= null
&&
286 mCurrentDownload
.getRemotePath().startsWith(file
.getRemotePath()) &&
287 account
.name
.equals(mCurrentAccount
.name
)) {
288 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
289 "Canceling current sync as descendant: " + mCurrentDownload.getRemotePath());*/
290 mCurrentDownload
.cancel();
296 * Cancels a pending or current upload for an account
298 * @param account Owncloud accountName where the remote file will be stored.
300 public void cancel(Account account
) {
301 Log_OC
.d(TAG
, "Account= " + account
.name
);
303 if (mCurrentDownload
!= null
) {
304 Log_OC
.d(TAG
, "Current Download Account= " + mCurrentDownload
.getAccount().name
);
305 if (mCurrentDownload
.getAccount().name
.equals(account
.name
)) {
306 mCurrentDownload
.cancel();
309 // Cancel pending downloads
310 cancelDownloadsForAccount(account
);
313 public void clearListeners() {
314 mBoundListeners
.clear();
319 * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or
320 * waiting to download.
322 * If 'file' is a directory, returns 'true' if any of its descendant files is downloading or
323 * waiting to download.
325 * @param account ownCloud account where the remote file is stored.
326 * @param file A file that could be in the queue of downloads.
328 public boolean isDownloading(Account account
, OCFile file
) {
329 if (account
== null
|| file
== null
) return false
;
330 return (mPendingDownloads
.contains(account
, file
.getRemotePath()));
335 * Adds a listener interested in the progress of the download for a concrete file.
337 * @param listener Object to notify about progress of transfer.
338 * @param account ownCloud account holding the file of interest.
339 * @param file {@link OCFile} of interest for listener.
341 public void addDatatransferProgressListener(
342 OnDatatransferProgressListener listener
, Account account
, OCFile file
344 if (account
== null
|| file
== null
|| listener
== null
) return;
345 //String targetKey = buildKey(account, file.getRemotePath());
346 mBoundListeners
.put(file
.getFileId(), listener
);
351 * Removes a listener interested in the progress of the download for a concrete file.
353 * @param listener Object to notify about progress of transfer.
354 * @param account ownCloud account holding the file of interest.
355 * @param file {@link OCFile} of interest for listener.
357 public void removeDatatransferProgressListener(
358 OnDatatransferProgressListener listener
, Account account
, OCFile file
360 if (account
== null
|| file
== null
|| listener
== null
) return;
361 //String targetKey = buildKey(account, file.getRemotePath());
362 Long fileId
= file
.getFileId();
363 if (mBoundListeners
.get(fileId
) == listener
) {
364 mBoundListeners
.remove(fileId
);
369 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
,
371 //String key = buildKey(mCurrentDownload.getAccount(), mCurrentDownload.getFile().getRemotePath());
372 OnDatatransferProgressListener boundListener
= mBoundListeners
.get(mCurrentDownload
.getFile().getFileId());
373 if (boundListener
!= null
) {
374 boundListener
.onTransferProgress(progressRate
, totalTransferredSoFar
, totalToTransfer
, fileName
);
379 * Review downloads and cancel it if its account doesn't exist
381 public void checkAccountOfCurrentDownload() {
382 if (mCurrentDownload
!= null
&&
383 !AccountUtils
.exists(mCurrentDownload
.getAccount(), getApplicationContext())) {
384 mCurrentDownload
.cancel();
386 // The rest of downloads are cancelled when they try to start
393 * Download worker. Performs the pending downloads in the order they were requested.
395 * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}.
397 private static class ServiceHandler
extends Handler
{
398 // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak
399 FileDownloader mService
;
401 public ServiceHandler(Looper looper
, FileDownloader service
) {
404 throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");
409 public void handleMessage(Message msg
) {
410 @SuppressWarnings("unchecked")
411 AbstractList
<String
> requestedDownloads
= (AbstractList
<String
>) msg
.obj
;
412 if (msg
.obj
!= null
) {
413 Iterator
<String
> it
= requestedDownloads
.iterator();
414 while (it
.hasNext()) {
415 String next
= it
.next();
416 mService
.downloadFile(next
);
419 Log_OC
.d(TAG
, "Stopping after command with id " + msg
.arg1
);
420 mService
.stopSelf(msg
.arg1
);
426 * Core download method: requests a file to download and stores it.
428 * @param downloadKey Key to access the download to perform, contained in mPendingDownloads
430 private void downloadFile(String downloadKey
) {
432 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
433 "Getting download of " + downloadKey);*/
434 mCurrentDownload
= mPendingDownloads
.get(downloadKey
);
436 if (mCurrentDownload
!= null
) {
437 // Detect if the account exists
438 if (AccountUtils
.exists(mCurrentDownload
.getAccount(), getApplicationContext())) {
439 Log_OC
.d(TAG
, "Account " + mCurrentDownload
.getAccount().name
+ " exists");
440 notifyDownloadStart(mCurrentDownload
);
442 RemoteOperationResult downloadResult
= null
;
444 /// prepare client object to send the request to the ownCloud server
445 if (mCurrentAccount
== null
|| !mCurrentAccount
.equals(mCurrentDownload
.getAccount())) {
446 mCurrentAccount
= mCurrentDownload
.getAccount();
447 mStorageManager
= new FileDataStorageManager(
451 } // else, reuse storage manager from previous operation
453 // always get client from client manager, to get fresh credentials in case of update
454 OwnCloudAccount ocAccount
= new OwnCloudAccount(mCurrentAccount
, this);
455 mDownloadClient
= OwnCloudClientManagerFactory
.getDefaultSingleton().
456 getClientFor(ocAccount
, this);
459 /// perform the download
460 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
461 "Executing download of " + mCurrentDownload.getRemotePath());*/
462 downloadResult
= mCurrentDownload
.execute(mDownloadClient
);
463 if (downloadResult
.isSuccess()) {
464 saveDownloadedFile();
467 } catch (AccountsException e
) {
468 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
469 downloadResult
= new RemoteOperationResult(e
);
470 } catch (IOException e
) {
471 Log_OC
.e(TAG
, "Error while trying to get authorization for " + mCurrentAccount
.name
, e
);
472 downloadResult
= new RemoteOperationResult(e
);
475 /*Log_OC.v( "NOW " + TAG + ", thread " + Thread.currentThread().getName(),
476 "Removing payload " + mCurrentDownload.getRemotePath());*/
478 Pair
<DownloadFileOperation
, String
> removeResult
=
479 mPendingDownloads
.removePayload(mCurrentAccount
, mCurrentDownload
.getRemotePath());
482 notifyDownloadResult(mCurrentDownload
, downloadResult
);
484 sendBroadcastDownloadFinished(mCurrentDownload
, downloadResult
, removeResult
.second
);
487 // Cancel the transfer
488 Log_OC
.d(TAG
, "Account " + mCurrentDownload
.getAccount().toString() + " doesn't exist");
489 cancelDownloadsForAccount(mCurrentDownload
.getAccount());
497 * Updates the OC File after a successful download.
499 private void saveDownloadedFile() {
500 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
501 long syncDate
= System
.currentTimeMillis();
502 file
.setLastSyncDateForProperties(syncDate
);
503 file
.setLastSyncDateForData(syncDate
);
504 file
.setNeedsUpdateThumbnail(true
);
505 file
.setModificationTimestamp(mCurrentDownload
.getModificationTimestamp());
506 file
.setModificationTimestampAtLastSyncForData(mCurrentDownload
.getModificationTimestamp());
507 // file.setEtag(mCurrentDownload.getEtag()); // TODO Etag, where available
508 file
.setMimetype(mCurrentDownload
.getMimeType());
509 file
.setStoragePath(mCurrentDownload
.getSavePath());
510 file
.setFileLength((new File(mCurrentDownload
.getSavePath()).length()));
511 file
.setRemoteId(mCurrentDownload
.getFile().getRemoteId());
512 mStorageManager
.saveFile(file
);
513 mStorageManager
.triggerMediaScan(file
.getStoragePath());
517 * Update the OC File after a unsuccessful download
519 private void updateUnsuccessfulDownloadedFile() {
520 OCFile file
= mStorageManager
.getFileById(mCurrentDownload
.getFile().getFileId());
521 file
.setDownloading(false
);
522 mStorageManager
.saveFile(file
);
527 * Creates a status notification to show the download progress
529 * @param download Download operation starting.
531 private void notifyDownloadStart(DownloadFileOperation download
) {
532 /// create status notification with a progress bar
534 mNotificationBuilder
=
535 NotificationBuilderWithProgressBar
.newNotificationBuilderWithProgressBar(this);
537 .setSmallIcon(R
.drawable
.notification_icon
)
538 .setTicker(getString(R
.string
.downloader_download_in_progress_ticker
))
539 .setContentTitle(getString(R
.string
.downloader_download_in_progress_ticker
))
541 .setProgress(100, 0, download
.getSize() < 0)
543 String
.format(getString(R
.string
.downloader_download_in_progress_content
), 0,
544 new File(download
.getSavePath()).getName())
547 /// includes a pending intent in the notification showing the details view of the file
548 Intent showDetailsIntent
= null
;
549 if (PreviewImageFragment
.canBePreviewed(download
.getFile())) {
550 showDetailsIntent
= new Intent(this, PreviewImageActivity
.class);
552 showDetailsIntent
= new Intent(this, FileDisplayActivity
.class);
554 showDetailsIntent
.putExtra(FileActivity
.EXTRA_FILE
, download
.getFile());
555 showDetailsIntent
.putExtra(FileActivity
.EXTRA_ACCOUNT
, download
.getAccount());
556 showDetailsIntent
.setFlags(Intent
.FLAG_ACTIVITY_CLEAR_TOP
);
558 mNotificationBuilder
.setContentIntent(PendingIntent
.getActivity(
559 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0
562 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
567 * Callback method to update the progress bar in the status notification.
570 public void onTransferProgress(long progressRate
, long totalTransferredSoFar
, long totalToTransfer
, String filePath
) {
571 int percent
= (int) (100.0 * ((double) totalTransferredSoFar
) / ((double) totalToTransfer
));
572 if (percent
!= mLastPercent
) {
573 mNotificationBuilder
.setProgress(100, percent
, totalToTransfer
< 0);
574 String fileName
= filePath
.substring(filePath
.lastIndexOf(FileUtils
.PATH_SEPARATOR
) + 1);
575 String text
= String
.format(getString(R
.string
.downloader_download_in_progress_content
), percent
, fileName
);
576 mNotificationBuilder
.setContentText(text
);
577 mNotificationManager
.notify(R
.string
.downloader_download_in_progress_ticker
, mNotificationBuilder
.build());
579 mLastPercent
= percent
;
584 * Updates the status notification with the result of a download operation.
586 * @param downloadResult Result of the download operation.
587 * @param download Finished download operation
589 private void notifyDownloadResult(DownloadFileOperation download
, RemoteOperationResult downloadResult
) {
590 mNotificationManager
.cancel(R
.string
.downloader_download_in_progress_ticker
);
591 if (!downloadResult
.isCancelled()) {
592 int tickerId
= (downloadResult
.isSuccess()) ? R
.string
.downloader_download_succeeded_ticker
:
593 R
.string
.downloader_download_failed_ticker
;
595 boolean needsToUpdateCredentials
= (
596 downloadResult
.getCode() == ResultCode
.UNAUTHORIZED
||
597 downloadResult
.isIdPRedirection()
599 tickerId
= (needsToUpdateCredentials
) ?
600 R
.string
.downloader_download_failed_credentials_error
: tickerId
;
603 .setTicker(getString(tickerId
))
604 .setContentTitle(getString(tickerId
))
607 .setProgress(0, 0, false
);
609 if (needsToUpdateCredentials
) {
611 // let the user update credentials with one click
612 Intent updateAccountCredentials
= new Intent(this, AuthenticatorActivity
.class);
613 updateAccountCredentials
.putExtra(AuthenticatorActivity
.EXTRA_ACCOUNT
, download
.getAccount());
614 updateAccountCredentials
.putExtra(
615 AuthenticatorActivity
.EXTRA_ACTION
, AuthenticatorActivity
.ACTION_UPDATE_EXPIRED_TOKEN
617 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_NEW_TASK
);
618 updateAccountCredentials
.addFlags(Intent
.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS
);
619 updateAccountCredentials
.addFlags(Intent
.FLAG_FROM_BACKGROUND
);
621 .setContentIntent(PendingIntent
.getActivity(
622 this, (int) System
.currentTimeMillis(), updateAccountCredentials
, PendingIntent
.FLAG_ONE_SHOT
));
625 // TODO put something smart in showDetailsIntent
626 Intent showDetailsIntent
= new Intent();
628 .setContentIntent(PendingIntent
.getActivity(
629 this, (int) System
.currentTimeMillis(), showDetailsIntent
, 0));
632 mNotificationBuilder
.setContentText(
633 ErrorMessageAdapter
.getErrorCauseMessage(downloadResult
, download
, getResources())
635 mNotificationManager
.notify(tickerId
, mNotificationBuilder
.build());
637 // Remove success notification
638 if (downloadResult
.isSuccess()) {
639 // Sleep 2 seconds, so show the notification before remove it
640 NotificationDelayer
.cancelWithDelay(
641 mNotificationManager
,
642 R
.string
.downloader_download_succeeded_ticker
,
651 * Sends a broadcast when a download finishes in order to the interested activities can update their view
653 * @param download Finished download operation
654 * @param downloadResult Result of the download operation
655 * @param unlinkedFromRemotePath Path in the downloads tree where the download was unlinked from
657 private void sendBroadcastDownloadFinished(
658 DownloadFileOperation download
,
659 RemoteOperationResult downloadResult
,
660 String unlinkedFromRemotePath
) {
661 Intent end
= new Intent(getDownloadFinishMessage());
662 end
.putExtra(EXTRA_DOWNLOAD_RESULT
, downloadResult
.isSuccess());
663 end
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
664 end
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
665 end
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
666 if (unlinkedFromRemotePath
!= null
) {
667 end
.putExtra(EXTRA_LINKED_TO_PATH
, unlinkedFromRemotePath
);
669 sendStickyBroadcast(end
);
674 * Sends a broadcast when a new download is added to the queue.
676 * @param download Added download operation
677 * @param linkedToRemotePath Path in the downloads tree where the download was linked to
679 private void sendBroadcastNewDownload(DownloadFileOperation download
, String linkedToRemotePath
) {
680 Intent added
= new Intent(getDownloadAddedMessage());
681 added
.putExtra(ACCOUNT_NAME
, download
.getAccount().name
);
682 added
.putExtra(EXTRA_REMOTE_PATH
, download
.getRemotePath());
683 added
.putExtra(EXTRA_FILE_PATH
, download
.getSavePath());
684 added
.putExtra(EXTRA_LINKED_TO_PATH
, linkedToRemotePath
);
685 sendStickyBroadcast(added
);
689 * Remove downloads of an account
691 * @param account Downloads account to remove
693 private void cancelDownloadsForAccount(Account account
) {
694 // Cancel pending downloads
695 mPendingDownloads
.remove(account
);