Adding cancellation to uploads (WIP)
[pub/Android/ownCloud.git] / src / com / owncloud / android / files / services / FileDownloader.java
index 50a8c49..7343644 100644 (file)
@@ -40,6 +40,7 @@ import com.owncloud.android.R;
 import eu.alefzero.webdav.WebdavClient;\r
 \r
 public class FileDownloader extends Service implements OnDatatransferProgressListener {\r
+    \r
     public static final String EXTRA_ACCOUNT = "ACCOUNT";\r
     public static final String EXTRA_FILE = "FILE";\r
     \r
@@ -60,13 +61,16 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
     private ConcurrentMap<String, DownloadFileOperation> mPendingDownloads = new ConcurrentHashMap<String, DownloadFileOperation>();\r
     private DownloadFileOperation mCurrentDownload = null;\r
     \r
-    private NotificationManager mNotificationMngr;\r
+    private NotificationManager mNotificationManager;\r
     private Notification mNotification;\r
     private int mLastPercent;\r
     \r
     \r
     /**\r
-     * Builds a key for mDownloadsInProgress from the accountName and remotePath\r
+     * Builds a key for mPendingDownloads from the account and file to download\r
+     * \r
+     * @param account   Account where the file to download is stored\r
+     * @param file      File to download\r
      */\r
     private String buildRemoteName(Account account, OCFile file) {\r
         return account.name + file.getRemotePath();\r
@@ -91,12 +95,12 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
     @Override\r
     public void onCreate() {\r
         super.onCreate();\r
-        mNotificationMngr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\r
-        HandlerThread thread = new HandlerThread("FileDownladerThread",\r
+        mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);\r
+        HandlerThread thread = new HandlerThread("FileDownloaderThread",\r
                 Process.THREAD_PRIORITY_BACKGROUND);\r
         thread.start();\r
         mServiceLooper = thread.getLooper();\r
-        mServiceHandler = new ServiceHandler(mServiceLooper);\r
+        mServiceHandler = new ServiceHandler(mServiceLooper, this);\r
         mBinder = new FileDownloaderBinder();\r
     }\r
 \r
@@ -180,10 +184,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         \r
         \r
         /**\r
-         * Returns True when the file referred by 'remotePath' in the ownCloud account 'account' is downloading\r
+         * Returns True when the file described by 'file' in the ownCloud account 'account' is downloading or waiting to download\r
          * \r
          * @param account       Owncloud account where the remote file is stored.\r
-         * @param file          A file in the queue of downloads.\r
+         * @param file          A file that could be in the queue of downloads.\r
          */\r
         public boolean isDownloading(Account account, OCFile file) {\r
             synchronized (mPendingDownloads) {\r
@@ -198,9 +202,14 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
      * \r
      * Created with the Looper of a new thread, started in {@link FileUploader#onCreate()}. \r
      */\r
-    private final class ServiceHandler extends Handler {\r
-        public ServiceHandler(Looper looper) {\r
+    private static class ServiceHandler extends Handler {\r
+        // don't make it a final class, and don't remove the static ; lint will warn about a possible memory leak\r
+        FileDownloader mService;\r
+        public ServiceHandler(Looper looper, FileDownloader service) {\r
             super(looper);\r
+            if (service == null)\r
+                throw new IllegalArgumentException("Received invalid NULL in parameter 'service'");\r
+            mService = service;\r
         }\r
 \r
         @Override\r
@@ -210,10 +219,10 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             if (msg.obj != null) {\r
                 Iterator<String> it = requestedDownloads.iterator();\r
                 while (it.hasNext()) {\r
-                    downloadFile(it.next());\r
+                    mService.downloadFile(it.next());\r
                 }\r
             }\r
-            stopSelf(msg.arg1);\r
+            mService.stopSelf(msg.arg1);\r
         }\r
     }\r
     \r
@@ -235,7 +244,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             notifyDownloadStart(mCurrentDownload);\r
 \r
             /// prepare client object to send the request to the ownCloud server\r
-            if (mDownloadClient == null || mLastAccount != mCurrentDownload.getAccount()) {\r
+            if (mDownloadClient == null || !mLastAccount.equals(mCurrentDownload.getAccount())) {\r
                 mLastAccount = mCurrentDownload.getAccount();\r
                 mDownloadClient = OwnCloudClientUtils.createOwnCloudClient(mLastAccount, getApplicationContext());\r
             }\r
@@ -258,7 +267,9 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
                 }\r
             \r
             } finally {\r
-                mPendingDownloads.remove(downloadKey);\r
+                synchronized(mPendingDownloads) {\r
+                    mPendingDownloads.remove(downloadKey);\r
+                }\r
             }\r
 \r
             \r
@@ -271,41 +282,17 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
 \r
     \r
     /**\r
-     * Callback method to update the progress bar in the status notification.\r
-     */\r
-    @Override\r
-    public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {\r
-        int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));\r
-        if (percent != mLastPercent) {\r
-          mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer == -1);\r
-          mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName));\r
-          mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
-        }\r
-        mLastPercent = percent;\r
-    }\r
-    \r
-    \r
-    /**\r
-     * Callback method to update the progress bar in the status notification (old version)\r
-     */\r
-    @Override\r
-    public void onTransferProgress(long progressRate) {\r
-        // NOTHING TO DO HERE ANYMORE\r
-    }\r
-    \r
-\r
-    /**\r
      * Creates a status notification to show the download progress\r
      * \r
      * @param download  Download operation starting.\r
      */\r
     private void notifyDownloadStart(DownloadFileOperation download) {\r
-        /// create status notification to show the download progress\r
+        /// create status notification with a progress bar\r
         mLastPercent = 0;\r
         mNotification = new Notification(R.drawable.icon, getString(R.string.downloader_download_in_progress_ticker), System.currentTimeMillis());\r
         mNotification.flags |= Notification.FLAG_ONGOING_EVENT;\r
         mNotification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.progressbar_layout);\r
-        mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() == -1);\r
+        mNotification.contentView.setProgressBar(R.id.status_progress, 100, 0, download.getSize() < 0);\r
         mNotification.contentView.setTextViewText(R.id.status_text, String.format(getString(R.string.downloader_download_in_progress_content), 0, new File(download.getSavePath()).getName()));\r
         mNotification.contentView.setImageViewResource(R.id.status_icon, R.drawable.icon);\r
         \r
@@ -316,18 +303,43 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
         showDetailsIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);\r
         mNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, showDetailsIntent, PendingIntent.FLAG_UPDATE_CURRENT);\r
         \r
-        mNotificationMngr.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
+        mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
     }\r
 \r
     \r
     /**\r
+     * Callback method to update the progress bar in the status notification.\r
+     */\r
+    @Override\r
+    public void onTransferProgress(long progressRate, long totalTransferredSoFar, long totalToTransfer, String fileName) {\r
+        int percent = (int)(100.0*((double)totalTransferredSoFar)/((double)totalToTransfer));\r
+        if (percent != mLastPercent) {\r
+          mNotification.contentView.setProgressBar(R.id.status_progress, 100, percent, totalToTransfer < 0);\r
+          String text = String.format(getString(R.string.downloader_download_in_progress_content), percent, fileName);\r
+          mNotification.contentView.setTextViewText(R.id.status_text, text);\r
+          mNotificationManager.notify(R.string.downloader_download_in_progress_ticker, mNotification);\r
+        }\r
+        mLastPercent = percent;\r
+    }\r
+    \r
+    \r
+    /**\r
+     * Callback method to update the progress bar in the status notification (old version)\r
+     */\r
+    @Override\r
+    public void onTransferProgress(long progressRate) {\r
+        // NOTHING TO DO HERE ANYMORE\r
+    }\r
+    \r
+\r
+    /**\r
      * Updates the status notification with the result of a download operation.\r
      * \r
      * @param downloadResult    Result of the download operation.\r
      * @param download          Finished download operation\r
      */\r
     private void notifyDownloadResult(DownloadFileOperation download, RemoteOperationResult downloadResult) {\r
-        mNotificationMngr.cancel(R.string.downloader_download_in_progress_ticker);\r
+        mNotificationManager.cancel(R.string.downloader_download_in_progress_ticker);\r
         if (!downloadResult.isCancelled()) {\r
             int tickerId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_ticker : R.string.downloader_download_failed_ticker;\r
             int contentId = (downloadResult.isSuccess()) ? R.string.downloader_download_succeeded_content : R.string.downloader_download_failed_content;\r
@@ -336,7 +348,7 @@ public class FileDownloader extends Service implements OnDatatransferProgressLis
             // TODO put something smart in the contentIntent below\r
             finalNotification.contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), PendingIntent.FLAG_UPDATE_CURRENT);\r
             finalNotification.setLatestEventInfo(getApplicationContext(), getString(tickerId), String.format(getString(contentId), new File(download.getSavePath()).getName()), finalNotification.contentIntent);\r
-            mNotificationMngr.notify(tickerId, finalNotification);\r
+            mNotificationManager.notify(tickerId, finalNotification);\r
         }\r
     }\r
     \r