Browse Source

Use WorkerState for handling download state

Signed-off-by: alperozturk <alper_ozturk@proton.me>
alperozturk 1 năm trước cách đây
mục cha
commit
14cb1d436b

+ 3 - 3
app/src/androidTest/java/com/owncloud/android/files/FileMenuFilterIT.kt

@@ -62,7 +62,7 @@ class FileMenuFilterIT : AbstractIT() {
     private lateinit var mockFileUploaderBinder: FileUploader.FileUploaderBinder
 
     @MockK
-    private lateinit var mockFileDownloaderBinder: FileDownloadWorker.FileDownloaderBinder
+    private lateinit var mockFileDownloadProgressListener: FileDownloadWorker.FileDownloadProgressListener
 
     @MockK
     private lateinit var mockOperationsServiceBinder: OperationsService.OperationsServiceBinder
@@ -77,8 +77,8 @@ class FileMenuFilterIT : AbstractIT() {
         MockKAnnotations.init(this)
         every { mockFileUploaderBinder.isUploading(any(), any()) } returns false
         every { mockComponentsGetter.fileUploaderBinder } returns mockFileUploaderBinder
-        every { mockFileDownloaderBinder.isDownloading(any(), any()) } returns false
-        every { mockComponentsGetter.fileDownloaderBinder } returns mockFileDownloaderBinder
+        every { mockFileDownloadProgressListener.isDownloading(any(), any()) } returns false
+        every { mockComponentsGetter.fileDownloadProgressListener } returns mockFileDownloadProgressListener
         every { mockOperationsServiceBinder.isSynchronizing(any(), any()) } returns false
         every { mockComponentsGetter.operationsServiceBinder } returns mockOperationsServiceBinder
         every { mockStorageManager.getFileById(any()) } returns OCFile("/")

+ 1 - 1
app/src/debug/java/com/nextcloud/test/TestActivity.kt

@@ -130,7 +130,7 @@ class TestActivity :
         return null
     }
 
-    override fun getFileDownloaderBinder(): FileDownloadWorker.FileDownloaderBinder? {
+    override fun getFileDownloadProgressListener(): FileDownloadWorker.FileDownloadProgressListener? {
         return null
     }
 

+ 60 - 1
app/src/main/java/com/nextcloud/client/files/downloader/FileDownloadHelper.kt

@@ -27,13 +27,14 @@ import com.owncloud.android.MainApp
 import com.owncloud.android.datamodel.FileDataStorageManager
 import com.owncloud.android.datamodel.OCFile
 import com.owncloud.android.datamodel.UploadsStorageManager
+import com.owncloud.android.lib.common.network.OnDatatransferProgressListener
 import com.owncloud.android.operations.DownloadFileOperation
 import com.owncloud.android.operations.DownloadType
 import com.owncloud.android.utils.MimeTypeUtil
 import java.io.File
 import javax.inject.Inject
 
-class FileDownloadHelper {
+class FileDownloadHelper : OnDatatransferProgressListener {
 
     @Inject
     lateinit var backgroundJobManager: BackgroundJobManager
@@ -41,10 +42,51 @@ class FileDownloadHelper {
     @Inject
     lateinit var uploadsStorageManager: UploadsStorageManager
 
+    private val boundListeners: MutableMap<Long, OnDatatransferProgressListener> = HashMap()
+    private var currentDownload: DownloadFileOperation? = null
+
     init {
         MainApp.getAppComponent().inject(this)
     }
 
+    fun addDataTransferProgressListener(listener: OnDatatransferProgressListener?, file: OCFile?) {
+        if (file == null || listener == null) {
+            return
+        }
+
+        boundListeners[file.fileId] = listener
+    }
+
+    fun removeDataTransferProgressListener(listener: OnDatatransferProgressListener?, file: OCFile?) {
+        if (file == null || listener == null) {
+            return
+        }
+
+        val fileId = file.fileId
+        if (boundListeners[fileId] === listener) {
+            boundListeners.remove(fileId)
+        }
+    }
+
+    override fun onTransferProgress(
+        progressRate: Long,
+        totalTransferredSoFar: Long,
+        totalToTransfer: Long,
+        fileName: String
+    ) {
+        val listener = boundListeners[currentDownload?.file?.fileId]
+        listener?.onTransferProgress(
+            progressRate,
+            totalTransferredSoFar,
+            totalToTransfer,
+            fileName
+        )
+    }
+
+    fun setCurrentDownload(operation: DownloadFileOperation) {
+        currentDownload = operation
+    }
+
     fun isDownloading(user: User?, file: OCFile?): Boolean {
         return user != null && file != null && backgroundJobManager.isStartFileDownloadJobScheduled(
             user,
@@ -52,6 +94,23 @@ class FileDownloadHelper {
         )
     }
 
+    fun cancelPendingOrCurrentDownloads(user: User?, file: OCFile?) {
+        if (user == null || file == null) return
+        backgroundJobManager.cancelFilesDownloadJob(user, file)
+    }
+
+    fun cancelAllDownloadsForAccount(accountName: String?, currentDownload: DownloadFileOperation) {
+        if (currentDownload.user.nameEquals(accountName)) {
+            currentDownload.file?.let { file ->
+                backgroundJobManager.cancelFilesDownloadJob(currentDownload.user, file)
+            }
+
+            currentDownload.cancel()
+        }
+
+        // removePendingDownload(accountName)
+    }
+
     fun saveFile(
         file: OCFile,
         currentDownload: DownloadFileOperation?,

+ 17 - 32
app/src/main/java/com/nextcloud/client/files/downloader/FileDownloadWorker.kt

@@ -26,8 +26,6 @@ import android.accounts.AccountManager
 import android.accounts.OnAccountsUpdateListener
 import android.app.PendingIntent
 import android.content.Context
-import android.os.Binder
-import android.os.IBinder
 import androidx.localbroadcastmanager.content.LocalBroadcastManager
 import androidx.work.Worker
 import androidx.work.WorkerParameters
@@ -97,12 +95,13 @@ class FileDownloadWorker(
     private val intents = FileDownloadIntents(context)
     private val notificationManager = DownloadNotificationManager(context, viewThemeUtils)
     private val pendingDownloads = IndexedForest<DownloadFileOperation>()
-    private var downloadBinder: IBinder = FileDownloaderBinder()
+    private var downloadProgressListener = FileDownloadProgressListener()
     private var currentUser = Optional.empty<User>()
     private val helper = FileDownloadHelper()
     private var startedDownload = false
     private var storageManager: FileDataStorageManager? = null
     private var downloadClient: OwnCloudClient? = null
+    private var user: User? = null
     private val gson = Gson()
 
     @Suppress("TooGenericExceptionCaught")
@@ -122,11 +121,16 @@ class FileDownloadWorker(
         }
     }
 
+    override fun onStopped() {
+        super.onStopped()
+        setIdleWorkerState()
+    }
+
     private fun getRequestDownloads(): AbstractList<String> {
         conflictUploadId = inputData.keyValueMap[CONFLICT_UPLOAD_ID] as Long?
         val file = gson.fromJson(inputData.keyValueMap[FILE] as String, OCFile::class.java)
         val accountName = inputData.keyValueMap[USER_NAME] as String
-        val user = accountManager.getUser(accountName).get()
+        user = accountManager.getUser(accountName).get()
         val downloadTypeAsString = inputData.keyValueMap[DOWNLOAD_TYPE] as String?
         val downloadType = if (downloadTypeAsString != null) {
             if (downloadTypeAsString == DownloadType.DOWNLOAD.toString()) {
@@ -140,7 +144,6 @@ class FileDownloadWorker(
         val behaviour = inputData.keyValueMap[BEHAVIOUR] as String
         val activityName = inputData.keyValueMap[ACTIVITY_NAME] as String
         val packageName = inputData.keyValueMap[PACKAGE_NAME] as String
-        setWorkerState(user, file)
 
         val requestedDownloads: AbstractList<String> = Vector()
 
@@ -156,7 +159,7 @@ class FileDownloadWorker(
             )
 
             operation.addDownloadDataTransferProgressListener(this)
-            operation.addDownloadDataTransferProgressListener(downloadBinder as FileDownloaderBinder)
+            operation.addDownloadDataTransferProgressListener(downloadProgressListener)
             val putResult = pendingDownloads.putIfAbsent(
                 user?.accountName,
                 file.remotePath,
@@ -176,10 +179,14 @@ class FileDownloadWorker(
         }
     }
 
-    private fun setWorkerState(user: User, file: OCFile) {
+    private fun setWorkerState(user: User?, file: DownloadFileOperation?) {
         WorkerStateLiveData.instance?.setWorkState(WorkerState.Download(user, file))
     }
 
+    private fun setIdleWorkerState() {
+        WorkerStateLiveData.instance?.setWorkState(WorkerState.Idle)
+    }
+
     private fun addAccountUpdateListener() {
         val am = AccountManager.get(context)
         am.addOnAccountsUpdatedListener(this, null, false)
@@ -205,6 +212,7 @@ class FileDownloadWorker(
         if (currentDownload == null) {
             return
         }
+        setWorkerState(user, currentDownload)
 
         val isAccountExist = accountManager.exists(currentDownload?.user?.toPlatformAccount())
         if (!isAccountExist) {
@@ -354,34 +362,11 @@ class FileDownloadWorker(
         lastPercent = percent
     }
 
-    inner class FileDownloaderBinder : Binder(), OnDatatransferProgressListener {
+    inner class FileDownloadProgressListener : OnDatatransferProgressListener {
         private val boundListeners: MutableMap<Long, OnDatatransferProgressListener> = HashMap()
 
-        fun cancelPendingOrCurrentDownloads() {
-            currentDownload?.file?.let { file ->
-                helper.backgroundJobManager.cancelFilesDownloadJob(currentUser.get(), file)
-            }
-        }
-
-        fun cancelAllDownloadsForAccount(accountName: String?) {
-            currentDownload?.user?.let {
-                if (it.nameEquals(accountName)) {
-                    currentDownload?.file?.let { file ->
-                        helper.backgroundJobManager.cancelFilesDownloadJob(it, file)
-                    }
-
-                    currentDownload?.cancel()
-                }
-            }
-
-            removePendingDownload(accountName)
-        }
-
         fun isDownloading(user: User?, file: OCFile?): Boolean {
-            return user != null && file != null && helper.backgroundJobManager.isStartFileDownloadJobScheduled(
-                user,
-                file
-            )
+            return helper.isDownloading(user, file)
         }
 
         fun addDataTransferProgressListener(listener: OnDatatransferProgressListener?, file: OCFile?) {

+ 1 - 1
app/src/main/java/com/nextcloud/client/notifications/download/DownloadNotificationManager.kt

@@ -89,7 +89,7 @@ class DownloadNotificationManager(private val context: Context, private val view
         val notifyId = SecureRandom().nextInt()
 
         val contentText = if (result.isSuccess) {
-            download.file.fileName + " " + context.getString(R.string.downloader_download_succeeded_ticker)
+            download.file.fileName
         } else {
             ErrorMessageAdapter.getErrorCauseMessage(
                 result,

+ 3 - 3
app/src/main/java/com/nextcloud/model/WorkerState.kt

@@ -22,9 +22,9 @@
 package com.nextcloud.model
 
 import com.nextcloud.client.account.User
-import com.owncloud.android.datamodel.OCFile
+import com.owncloud.android.operations.DownloadFileOperation
 
 sealed class WorkerState {
-    object Idle
-    class Download(var user: User, var file: OCFile): WorkerState()
+    object Idle : WorkerState()
+    class Download(var user: User?, var currentDownload: DownloadFileOperation?) : WorkerState()
 }

+ 0 - 1
app/src/main/java/com/owncloud/android/files/FileMenuFilter.java

@@ -32,7 +32,6 @@ import com.nextcloud.android.files.FileLockingHelper;
 import com.nextcloud.client.account.User;
 import com.nextcloud.client.editimage.EditImageActivity;
 import com.nextcloud.client.files.downloader.FileDownloadHelper;
-import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.utils.EditorUtils;
 import com.owncloud.android.R;
 import com.owncloud.android.datamodel.FileDataStorageManager;

+ 2 - 2
app/src/main/java/com/owncloud/android/ui/activity/ComponentsGetter.java

@@ -32,9 +32,9 @@ public interface ComponentsGetter {
      * To be invoked when the parent activity is fully created to get a reference
      * to the FileDownloadWorker.
      */
-    public FileDownloadWorker.FileDownloaderBinder getFileDownloaderBinder();
+    public FileDownloadWorker.FileDownloadProgressListener getFileDownloadProgressListener();
+
 
-    
     /**
      * To be invoked when the parent activity is fully created to get a reference
      * to the FileUploader service API.

+ 3 - 3
app/src/main/java/com/owncloud/android/ui/activity/FileActivity.java

@@ -167,7 +167,7 @@ public abstract class FileActivity extends DrawerActivity
     private boolean mResumed;
 
     protected FileDownloadHelper fileDownloadHelper = new FileDownloadHelper();
-    protected FileDownloadWorker.FileDownloaderBinder mDownloaderBinder;
+    protected FileDownloadWorker.FileDownloadProgressListener fileDownloadProgressListener;
     protected FileUploaderBinder mUploaderBinder;
     private ServiceConnection mUploadServiceConnection;
 
@@ -613,8 +613,8 @@ public abstract class FileActivity extends DrawerActivity
     }
 
     @Override
-    public FileDownloadWorker.FileDownloaderBinder getFileDownloaderBinder() {
-        return mDownloaderBinder;
+    public FileDownloadWorker.FileDownloadProgressListener getFileDownloadProgressListener() {
+        return fileDownloadProgressListener;
     }
 
     @Override

+ 1 - 3
app/src/main/java/com/owncloud/android/ui/activity/FileDisplayActivity.java

@@ -65,7 +65,6 @@ import com.nextcloud.client.core.AsyncRunner;
 import com.nextcloud.client.di.Injectable;
 import com.nextcloud.client.editimage.EditImageActivity;
 import com.nextcloud.client.files.DeepLinkHandler;
-import com.nextcloud.client.files.downloader.FileDownloadHelper;
 import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.client.media.PlayerServiceConnection;
 import com.nextcloud.client.network.ClientFactory;
@@ -162,7 +161,6 @@ import androidx.core.view.MenuItemCompat;
 import androidx.fragment.app.Fragment;
 import androidx.fragment.app.FragmentManager;
 import androidx.fragment.app.FragmentTransaction;
-import androidx.lifecycle.Observer;
 import androidx.localbroadcastmanager.content.LocalBroadcastManager;
 import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
 import kotlin.Unit;
@@ -1620,7 +1618,7 @@ public class FileDisplayActivity extends FileActivity
         public void onServiceDisconnected(ComponentName component) {
             if (component.equals(new ComponentName(FileDisplayActivity.this, FileDownloadWorker.class))) {
                 Log_OC.d(TAG, "Download service disconnected");
-                mDownloaderBinder = null;
+                fileDownloadProgressListener = null;
             } else if (component.equals(new ComponentName(FileDisplayActivity.this, FileUploader.class))) {
                 Log_OC.d(TAG, "Upload service disconnected");
                 mUploaderBinder = null;

+ 23 - 16
app/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java

@@ -41,10 +41,11 @@ import android.view.View;
 import com.google.common.collect.Sets;
 import com.nextcloud.client.account.User;
 import com.nextcloud.client.account.UserAccountManager;
-import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.client.jobs.BackgroundJobManager;
 import com.nextcloud.client.onboarding.FirstRunActivity;
 import com.nextcloud.java.util.Optional;
+import com.nextcloud.model.WorkerState;
+import com.nextcloud.model.WorkerStateLiveData;
 import com.nextcloud.utils.extensions.BundleExtensionsKt;
 import com.owncloud.android.MainApp;
 import com.owncloud.android.R;
@@ -56,6 +57,7 @@ import com.owncloud.android.files.services.FileUploader;
 import com.owncloud.android.lib.common.OwnCloudAccount;
 import com.owncloud.android.lib.common.UserInfo;
 import com.owncloud.android.lib.common.utils.Log_OC;
+import com.owncloud.android.operations.DownloadFileOperation;
 import com.owncloud.android.services.OperationsService;
 import com.owncloud.android.ui.adapter.UserListAdapter;
 import com.owncloud.android.ui.adapter.UserListItem;
@@ -112,6 +114,9 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
     private ArbitraryDataProvider arbitraryDataProvider;
     private boolean multipleAccountsSupported;
 
+    private String workerAccountName;
+    private DownloadFileOperation workerCurrentDownload;
+
     @Inject BackgroundJobManager backgroundJobManager;
     @Inject UserAccountManager accountManager;
 
@@ -159,6 +164,7 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
         recyclerView.setAdapter(userListAdapter);
         recyclerView.setLayoutManager(new LinearLayoutManager(this));
         initializeComponentGetters();
+        observeWorkerState();
     }
 
 
@@ -334,9 +340,8 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
                 if (mUploaderBinder != null) {
                     mUploaderBinder.cancel(accountName);
                 }
-                if (mDownloaderBinder != null) {
-                    mDownloaderBinder.cancelAllDownloadsForAccount(accountName);
-                }
+
+                fileDownloadHelper.cancelAllDownloadsForAccount(workerAccountName, workerCurrentDownload);
             }
 
             User currentUser = getUserAccountManager().getUser();
@@ -425,9 +430,8 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
         if (mUploaderBinder != null) {
             mUploaderBinder.cancel(user);
         }
-        if (mDownloaderBinder != null) {
-            mDownloaderBinder.cancelAllDownloadsForAccount(user.getAccountName());
-        }
+
+        fileDownloadHelper.cancelAllDownloadsForAccount(workerAccountName, workerCurrentDownload);
 
         backgroundJobManager.startAccountRemovalJob(user.getAccountName(), false);
 
@@ -512,6 +516,16 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
         }
     }
 
+    private void observeWorkerState() {
+        WorkerStateLiveData.Companion.getInstance().observe(this, state -> {
+            if (state instanceof WorkerState.Download) {
+                Log_OC.d(TAG, "Download worker started");
+                workerAccountName = ((WorkerState.Download) state).getUser().getAccountName();
+                workerCurrentDownload = ((WorkerState.Download) state).getCurrentDownload();
+            }
+        });
+    }
+
     @Override
     public void onAccountClicked(User user) {
         openAccount(user);
@@ -524,11 +538,7 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
 
         @Override
         public void onServiceConnected(ComponentName component, IBinder service) {
-
-            if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloadWorker.class))) {
-                mDownloaderBinder = (FileDownloadWorker.FileDownloaderBinder) service;
-
-            } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
+            if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
                 Log_OC.d(TAG, "Upload service connected");
                 mUploaderBinder = (FileUploader.FileUploaderBinder) service;
             }
@@ -536,10 +546,7 @@ public class ManageAccountsActivity extends FileActivity implements UserListAdap
 
         @Override
         public void onServiceDisconnected(ComponentName component) {
-            if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloadWorker.class))) {
-                Log_OC.d(TAG, "Download service suddenly disconnected");
-                mDownloaderBinder = null;
-            } else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
+            if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
                 Log_OC.d(TAG, "Upload service suddenly disconnected");
                 mUploaderBinder = null;
             }

+ 4 - 5
app/src/main/java/com/owncloud/android/ui/fragment/FileDetailFragment.java

@@ -45,7 +45,6 @@ import com.nextcloud.client.account.User;
 import com.nextcloud.client.account.UserAccountManager;
 import com.nextcloud.client.di.Injectable;
 import com.nextcloud.client.files.downloader.FileDownloadHelper;
-import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.client.jobs.BackgroundJobManager;
 import com.nextcloud.client.network.ClientFactory;
 import com.nextcloud.client.network.ConnectivityService;
@@ -694,8 +693,8 @@ public class FileDetailFragment extends FileFragment implements OnClickListener,
 
     public void listenForTransferProgress() {
         if (progressListener != null) {
-            if (containerActivity.getFileDownloaderBinder() != null) {
-                containerActivity.getFileDownloaderBinder().
+            if (containerActivity.getFileDownloadProgressListener() != null) {
+                containerActivity.getFileDownloadProgressListener().
                     addDataTransferProgressListener(progressListener, getFile());
             }
             if (containerActivity.getFileUploaderBinder() != null) {
@@ -709,8 +708,8 @@ public class FileDetailFragment extends FileFragment implements OnClickListener,
 
     private void leaveTransferProgress() {
         if (progressListener != null) {
-            if (containerActivity.getFileDownloaderBinder() != null) {
-                containerActivity.getFileDownloaderBinder().
+            if (containerActivity.getFileDownloadProgressListener() != null) {
+                containerActivity.getFileDownloadProgressListener().
                     removeDataTransferProgressListener(progressListener, getFile());
             }
             if (containerActivity.getFileUploaderBinder() != null) {

+ 3 - 4
app/src/main/java/com/owncloud/android/ui/helpers/FileOperationsHelper.java

@@ -48,7 +48,6 @@ import android.webkit.MimeTypeMap;
 import com.nextcloud.client.account.CurrentAccountProvider;
 import com.nextcloud.client.account.User;
 import com.nextcloud.client.files.downloader.FileDownloadHelper;
-import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.client.jobs.BackgroundJobManager;
 import com.nextcloud.client.network.ConnectivityService;
 import com.nextcloud.java.util.Optional;
@@ -998,9 +997,9 @@ public class FileOperationsHelper {
         }
 
         // for both files and folders
-        FileDownloadWorker.FileDownloaderBinder downloaderBinder = fileActivity.getFileDownloaderBinder();
-        if (downloaderBinder != null && downloaderBinder.isDownloading(currentUser, file)) {
-            downloaderBinder.cancelPendingOrCurrentDownloads();
+        FileDownloadHelper fileDownloadHelper = new FileDownloadHelper();
+        if (fileDownloadHelper.isDownloading(currentUser, file)) {
+            fileDownloadHelper.cancelPendingOrCurrentDownloads(currentUser, file);
         }
         FileUploaderBinder uploaderBinder = fileActivity.getFileUploaderBinder();
         if (uploaderBinder != null && uploaderBinder.isUploading(currentUser, file)) {

+ 4 - 4
app/src/main/java/com/owncloud/android/ui/preview/FileDownloadFragment.java

@@ -261,8 +261,8 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
 
 
     public void listenForTransferProgress() {
-        if (mProgressListener != null && !mListening && containerActivity.getFileDownloaderBinder() != null) {
-            containerActivity.getFileDownloaderBinder().addDataTransferProgressListener(mProgressListener, getFile());
+        if (mProgressListener != null && !mListening && containerActivity.getFileDownloadProgressListener() != null) {
+            containerActivity.getFileDownloadProgressListener().addDataTransferProgressListener(mProgressListener, getFile());
             mListening = true;
             setButtonsForTransferring();
         }
@@ -270,8 +270,8 @@ public class FileDownloadFragment extends FileFragment implements OnClickListene
 
 
     public void leaveTransferProgress() {
-        if (mProgressListener != null && containerActivity.getFileDownloaderBinder() != null) {
-            containerActivity.getFileDownloaderBinder()
+        if (mProgressListener != null && containerActivity.getFileDownloadProgressListener() != null) {
+            containerActivity.getFileDownloadProgressListener()
                 .removeDataTransferProgressListener(mProgressListener, getFile());
             mListening = false;
         }

+ 26 - 17
app/src/main/java/com/owncloud/android/ui/preview/PreviewImageActivity.java

@@ -37,10 +37,11 @@ import android.view.View;
 import com.nextcloud.client.account.User;
 import com.nextcloud.client.di.Injectable;
 import com.nextcloud.client.editimage.EditImageActivity;
-import com.nextcloud.client.files.downloader.FileDownloadHelper;
 import com.nextcloud.client.files.downloader.FileDownloadWorker;
 import com.nextcloud.client.preferences.AppPreferences;
 import com.nextcloud.java.util.Optional;
+import com.nextcloud.model.WorkerState;
+import com.nextcloud.model.WorkerStateLiveData;
 import com.nextcloud.utils.extensions.IntentExtensionsKt;
 import com.owncloud.android.MainApp;
 import com.owncloud.android.R;
@@ -99,6 +100,8 @@ public class PreviewImageActivity extends FileActivity implements
     private DownloadFinishReceiver mDownloadFinishReceiver;
     private UploadFinishReceiver mUploadFinishReceiver;
     private View mFullScreenAnchorView;
+    private boolean isDownloadWorkStarted = false;
+
     @Inject AppPreferences preferences;
     @Inject LocalBroadcastManager localBroadcastManager;
 
@@ -146,6 +149,8 @@ public class PreviewImageActivity extends FileActivity implements
         } else {
             mRequestWaitingForBinder = false;
         }
+
+        observeWorkerState();
     }
 
     public void toggleActionBarVisibility(boolean hide) {
@@ -299,6 +304,25 @@ public class PreviewImageActivity extends FileActivity implements
         }
     }
 
+    private void observeWorkerState() {
+        WorkerStateLiveData.Companion.getInstance().observe(this, state -> {
+            if (state instanceof WorkerState.Download) {
+                Log_OC.d(TAG, "Download worker started");
+                isDownloadWorkStarted = true;
+
+                if (mRequestWaitingForBinder) {
+                    mRequestWaitingForBinder = false;
+                    Log_OC.d(TAG, "Simulating reselection of current page after connection " +
+                        "of download binder");
+                    onPageSelected(mViewPager.getCurrentItem());
+                }
+            } else {
+                Log_OC.d(TAG, "Download worker stopped");
+                isDownloadWorkStarted = false;
+            }
+        });
+    }
+
     @Override
     protected ServiceConnection newTransferenceServiceConnection() {
         return new PreviewImageServiceConnection();
@@ -309,18 +333,7 @@ public class PreviewImageActivity extends FileActivity implements
 
         @Override
         public void onServiceConnected(ComponentName component, IBinder service) {
-
             if (component.equals(new ComponentName(PreviewImageActivity.this,
-                                                   FileDownloadWorker.class))) {
-                mDownloaderBinder = (FileDownloadWorker.FileDownloaderBinder) service;
-                if (mRequestWaitingForBinder) {
-                    mRequestWaitingForBinder = false;
-                    Log_OC.d(TAG, "Simulating reselection of current page after connection " +
-                            "of download binder");
-                    onPageSelected(mViewPager.getCurrentItem());
-                }
-
-            } else if (component.equals(new ComponentName(PreviewImageActivity.this,
                     FileUploader.class))) {
                 Log_OC.d(TAG, "Upload service connected");
                 mUploaderBinder = (FileUploaderBinder) service;
@@ -331,10 +344,6 @@ public class PreviewImageActivity extends FileActivity implements
         @Override
         public void onServiceDisconnected(ComponentName component) {
             if (component.equals(new ComponentName(PreviewImageActivity.this,
-                                                   FileDownloadWorker.class))) {
-                Log_OC.d(TAG, "Download service suddenly disconnected");
-                mDownloaderBinder = null;
-            } else if (component.equals(new ComponentName(PreviewImageActivity.this,
                     FileUploader.class))) {
                 Log_OC.d(TAG, "Upload service suddenly disconnected");
                 mUploaderBinder = null;
@@ -425,7 +434,7 @@ public class PreviewImageActivity extends FileActivity implements
     public void onPageSelected(int position) {
         mSavedPosition = position;
         mHasSavedPosition = true;
-        if (mDownloaderBinder == null) {
+        if (!isDownloadWorkStarted) {
             mRequestWaitingForBinder = true;
         } else {
             OCFile currentFile = mPreviewImagePagerAdapter.getFileAt(position);

+ 0 - 1
app/src/main/java/com/owncloud/android/ui/preview/PreviewImagePagerAdapter.java

@@ -19,7 +19,6 @@
  */
 package com.owncloud.android.ui.preview;
 
-import android.content.Intent;
 import android.util.SparseArray;
 import android.view.ViewGroup;
 

+ 0 - 26
app/src/main/java/com/owncloud/android/ui/preview/PreviewMediaActivity.kt

@@ -27,9 +27,7 @@
 package com.owncloud.android.ui.preview
 
 import android.app.Activity
-import android.content.ComponentName
 import android.content.Intent
-import android.content.ServiceConnection
 import android.content.res.Configuration
 import android.graphics.Bitmap
 import android.graphics.BitmapFactory
@@ -39,7 +37,6 @@ import android.net.Uri
 import android.os.AsyncTask
 import android.os.Bundle
 import android.os.Handler
-import android.os.IBinder
 import android.os.Looper
 import android.view.Menu
 import android.view.MenuItem
@@ -65,8 +62,6 @@ import androidx.media3.ui.PlayerView
 import com.nextcloud.client.account.User
 import com.nextcloud.client.account.UserAccountManager
 import com.nextcloud.client.di.Injectable
-import com.nextcloud.client.files.downloader.FileDownloadHelper
-import com.nextcloud.client.files.downloader.FileDownloadWorker
 import com.nextcloud.client.jobs.BackgroundJobManager
 import com.nextcloud.client.media.ExoplayerListener
 import com.nextcloud.client.media.NextcloudExoPlayer.createNextcloudExoplayer
@@ -563,33 +558,12 @@ class PreviewMediaActivity :
         }
     }
 
-    override fun newTransferenceServiceConnection(): ServiceConnection {
-        return PreviewMediaServiceConnection()
-    }
-
     private fun onSynchronizeFileOperationFinish(result: RemoteOperationResult<*>?) {
         result?.let {
             invalidateOptionsMenu()
         }
     }
 
-    private inner class PreviewMediaServiceConnection : ServiceConnection {
-        override fun onServiceConnected(componentName: ComponentName?, service: IBinder?) {
-            componentName?.let {
-                if (it == ComponentName(this@PreviewMediaActivity, FileDownloadWorker::class.java)) {
-                    mDownloaderBinder = service as FileDownloadWorker.FileDownloaderBinder
-                }
-            }
-        }
-
-        override fun onServiceDisconnected(componentName: ComponentName?) {
-            if (componentName == ComponentName(this@PreviewMediaActivity, FileDownloadWorker::class.java)) {
-                Log_OC.d(PreviewImageActivity.TAG, "Download service suddenly disconnected")
-                mDownloaderBinder = null
-            }
-        }
-    }
-
     override fun downloadFile(file: OCFile?, packageName: String?, activityName: String?) {
         requestForDownload(file, OCFileListFragment.DOWNLOAD_SEND, packageName, activityName)
     }