Browse Source

Implement WorkManager

Signed-off-by: Mario Danic <mario@lovelyhq.com>
Mario Danic 6 years ago
parent
commit
bd11873eef

+ 1 - 3
app/build.gradle

@@ -148,9 +148,7 @@ dependencies {
     implementation 'com.github.bumptech.glide:okhttp3-integration:4.7.1@aar'
     implementation 'org.webrtc:google-webrtc:1.0.23295'
     implementation "org.jetbrains.kotlin:kotlin-stdlib:${kotlinVersion}"
-
-    implementation 'com.evernote:android-job:1.2.6'
-
+    
     implementation 'com.yarolegovich:lovely-dialog:1.1.0'
     implementation 'com.yarolegovich:lovelyinput:1.0.9'
     implementation 'com.yarolegovich:mp:1.0.9'

+ 5 - 3
app/src/gplay/java/com/nextcloud/talk/services/firebase/MagicFirebaseInstanceIDService.java

@@ -20,15 +20,16 @@
 
 package com.nextcloud.talk.services.firebase;
 
-import com.evernote.android.job.JobRequest;
 import com.google.firebase.iid.FirebaseInstanceId;
 import com.google.firebase.iid.FirebaseInstanceIdService;
 import com.nextcloud.talk.application.NextcloudTalkApplication;
-import com.nextcloud.talk.jobs.PushRegistrationJob;
+import com.nextcloud.talk.jobs.PushRegistrationWorker;
 import com.nextcloud.talk.utils.preferences.AppPreferences;
 
 import javax.inject.Inject;
 
+import androidx.work.OneTimeWorkRequest;
+import androidx.work.WorkManager;
 import autodagger.AutoInjector;
 
 @AutoInjector(NextcloudTalkApplication.class)
@@ -46,6 +47,7 @@ public class MagicFirebaseInstanceIDService extends FirebaseInstanceIdService {
     @Override
     public void onTokenRefresh() {
         appPreferences.setPushToken(FirebaseInstanceId.getInstance().getToken());
-        new JobRequest.Builder(PushRegistrationJob.TAG).setUpdateCurrent(true).startNow().build().schedule();
+        OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
+        WorkManager.getInstance().enqueue(pushRegistrationWork);
     }
 }

+ 2 - 2
app/src/gplay/java/com/nextcloud/talk/services/firebase/MagicFirebaseMessagingService.java

@@ -46,10 +46,10 @@ public class MagicFirebaseMessagingService extends FirebaseMessagingService {
                     .putString(BundleKeys.KEY_NOTIFICATION_SIGNATURE, remoteMessage.getData().get("signature"))
                     .build();
 
-            OneTimeWorkRequest mathWork = new OneTimeWorkRequest.Builder(NotificationWorker.class)
+            OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(NotificationWorker.class)
                     .setInputData(messageData)
                     .build();
-            WorkManager.getInstance().enqueue(mathWork);
+            WorkManager.getInstance().enqueue(pushNotificationWork);
         }
     }
 }

+ 20 - 27
app/src/main/java/com/nextcloud/talk/application/NextcloudTalkApplication.java

@@ -30,17 +30,14 @@ import android.support.multidex.MultiDex;
 import android.support.multidex.MultiDexApplication;
 import android.util.Log;
 
-import com.evernote.android.job.JobManager;
-import com.evernote.android.job.JobRequest;
 import com.nextcloud.talk.BuildConfig;
 import com.nextcloud.talk.dagger.modules.BusModule;
 import com.nextcloud.talk.dagger.modules.ContextModule;
 import com.nextcloud.talk.dagger.modules.DatabaseModule;
 import com.nextcloud.talk.dagger.modules.RestModule;
-import com.nextcloud.talk.jobs.AccountRemovalJob;
-import com.nextcloud.talk.jobs.CapabilitiesJob;
-import com.nextcloud.talk.jobs.PushRegistrationJob;
-import com.nextcloud.talk.jobs.creator.MagicJobCreator;
+import com.nextcloud.talk.jobs.AccountRemovalWorker;
+import com.nextcloud.talk.jobs.CapabilitiesWorker;
+import com.nextcloud.talk.jobs.PushRegistrationWorker;
 import com.nextcloud.talk.utils.ClosedInterfaceImpl;
 import com.nextcloud.talk.utils.DeviceUtils;
 import com.nextcloud.talk.utils.DisplayUtils;
@@ -55,10 +52,16 @@ import org.webrtc.voiceengine.WebRtcAudioManager;
 import org.webrtc.voiceengine.WebRtcAudioUtils;
 
 import java.security.GeneralSecurityException;
+import java.util.ArrayList;
+import java.util.List;
 import java.util.concurrent.TimeUnit;
 
 import javax.inject.Singleton;
 
+import androidx.work.OneTimeWorkRequest;
+import androidx.work.PeriodicWorkRequest;
+import androidx.work.WorkManager;
+import androidx.work.WorkRequest;
 import autodagger.AutoComponent;
 import autodagger.AutoInjector;
 
@@ -119,8 +122,6 @@ public class NextcloudTalkApplication extends MultiDexApplication implements Lif
         super.onCreate();
         ProcessLifecycleOwner.get().getLifecycle().addObserver(this);
 
-        JobManager.create(this).addJobCreator(new MagicJobCreator());
-
         sharedApplication = this;
 
         initializeWebRtc();
@@ -140,27 +141,19 @@ public class NextcloudTalkApplication extends MultiDexApplication implements Lif
         new ClosedInterfaceImpl().providerInstallerInstallIfNeededAsync();
         DeviceUtils.ignoreSpecialBatteryFeatures();
 
-        new JobRequest.Builder(PushRegistrationJob.TAG).setUpdateCurrent(true).startNow().build().scheduleAsync();
-        new JobRequest.Builder(AccountRemovalJob.TAG).setUpdateCurrent(true).startNow().build().scheduleAsync();
-
-        schedulePeriodCapabilitiesJob();
-        new JobRequest.Builder(CapabilitiesJob.TAG).setUpdateCurrent(false).startNow().build().scheduleAsync();
-    }
+        OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
+        OneTimeWorkRequest accountRemovalWork = new OneTimeWorkRequest.Builder(AccountRemovalWorker.class).build();
+        OneTimeWorkRequest capabilitiesUpdateWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class).build();
+        PeriodicWorkRequest periodicCapabilitiesWork = new PeriodicWorkRequest.Builder(CapabilitiesWorker.class, 1,
+                        TimeUnit.DAYS).build();
 
-    private void schedulePeriodCapabilitiesJob() {
-        boolean periodicJobFound = false;
-        for (JobRequest jobRequest : JobManager.instance().getAllJobRequestsForTag(CapabilitiesJob.TAG)) {
-            if (jobRequest.isPeriodic()) {
-                periodicJobFound = true;
-                break;
-            }
-        }
+        List<WorkRequest> workRequests = new ArrayList<>();
+        workRequests.add(pushRegistrationWork);
+        workRequests.add(accountRemovalWork);
+        workRequests.add(capabilitiesUpdateWork);
+        workRequests.add(periodicCapabilitiesWork);
 
-        if (!periodicJobFound) {
-            new JobRequest.Builder(CapabilitiesJob.TAG).setUpdateCurrent(true)
-                    .setPeriodic(TimeUnit.DAYS.toMillis(1), TimeUnit.HOURS.toMillis(1))
-                    .build().scheduleAsync();
-        }
+        WorkManager.getInstance().enqueue(workRequests);
     }
 
     @Override

+ 15 - 14
app/src/main/java/com/nextcloud/talk/controllers/AccountVerificationController.java

@@ -32,15 +32,13 @@ import android.widget.TextView;
 
 import com.bluelinelabs.conductor.RouterTransaction;
 import com.bluelinelabs.conductor.changehandler.HorizontalChangeHandler;
-import com.evernote.android.job.JobRequest;
-import com.evernote.android.job.util.support.PersistableBundleCompat;
 import com.nextcloud.talk.R;
 import com.nextcloud.talk.api.NcApi;
 import com.nextcloud.talk.application.NextcloudTalkApplication;
 import com.nextcloud.talk.controllers.base.BaseController;
 import com.nextcloud.talk.events.EventStatus;
-import com.nextcloud.talk.jobs.CapabilitiesJob;
-import com.nextcloud.talk.jobs.PushRegistrationJob;
+import com.nextcloud.talk.jobs.CapabilitiesWorker;
+import com.nextcloud.talk.jobs.PushRegistrationWorker;
 import com.nextcloud.talk.models.database.UserEntity;
 import com.nextcloud.talk.models.json.generic.Status;
 import com.nextcloud.talk.models.json.rooms.RoomsOverall;
@@ -62,6 +60,9 @@ import java.util.List;
 
 import javax.inject.Inject;
 
+import androidx.work.Data;
+import androidx.work.OneTimeWorkRequest;
+import androidx.work.WorkManager;
 import autodagger.AutoInjector;
 import butterknife.BindView;
 import io.reactivex.CompletableObserver;
@@ -340,8 +341,8 @@ public class AccountVerificationController extends BaseController {
     }
 
     private void registerForPush() {
-        new JobRequest.Builder(PushRegistrationJob.TAG).
-                setUpdateCurrent(true).startNow().build().schedule();
+        OneTimeWorkRequest pushRegistrationWork = new OneTimeWorkRequest.Builder(PushRegistrationWorker.class).build();
+        WorkManager.getInstance().enqueue(pushRegistrationWork);
     }
 
     @Subscribe(threadMode = ThreadMode.BACKGROUND)
@@ -367,14 +368,14 @@ public class AccountVerificationController extends BaseController {
     }
 
     private void fetchAndStoreCapabilities() {
-        PersistableBundleCompat persistableBundleCompat = new
-                PersistableBundleCompat();
-        persistableBundleCompat.putLong(BundleKeys
-                .KEY_INTERNAL_USER_ID, internalAccountId);
-
-        new JobRequest.Builder(CapabilitiesJob.TAG).setUpdateCurrent
-                (false).addExtras(persistableBundleCompat).startNow()
-                .build().scheduleAsync();
+        Data userData = new Data.Builder()
+                .putLong(BundleKeys.KEY_INTERNAL_USER_ID, internalAccountId)
+                .build();
+
+        OneTimeWorkRequest pushNotificationWork = new OneTimeWorkRequest.Builder(CapabilitiesWorker.class)
+                .setInputData(userData)
+                .build();
+        WorkManager.getInstance().enqueue(pushNotificationWork);
     }
 
     private void proceedWithLogin() {

+ 6 - 4
app/src/main/java/com/nextcloud/talk/controllers/SettingsController.java

@@ -44,13 +44,12 @@ import com.bumptech.glide.load.model.GlideUrl;
 import com.bumptech.glide.load.model.LazyHeaders;
 import com.bumptech.glide.load.resource.bitmap.CircleCrop;
 import com.bumptech.glide.request.RequestOptions;
-import com.evernote.android.job.JobRequest;
 import com.nextcloud.talk.BuildConfig;
 import com.nextcloud.talk.R;
 import com.nextcloud.talk.api.NcApi;
 import com.nextcloud.talk.application.NextcloudTalkApplication;
 import com.nextcloud.talk.controllers.base.BaseController;
-import com.nextcloud.talk.jobs.AccountRemovalJob;
+import com.nextcloud.talk.jobs.AccountRemovalWorker;
 import com.nextcloud.talk.models.RingtoneSettings;
 import com.nextcloud.talk.models.database.UserEntity;
 import com.nextcloud.talk.utils.ApiUtils;
@@ -83,6 +82,8 @@ import java.util.Objects;
 
 import javax.inject.Inject;
 
+import androidx.work.OneTimeWorkRequest;
+import androidx.work.WorkManager;
 import autodagger.AutoInjector;
 import butterknife.BindView;
 import io.reactivex.android.schedulers.AndroidSchedulers;
@@ -419,8 +420,9 @@ public class SettingsController extends BaseController {
             removeAccountButton.addPreferenceClickListener(view1 -> {
                 cookieManager.getCookieStore().removeAll();
                 boolean otherUserExists = userUtils.scheduleUserForDeletionWithId(userEntity.getId());
-                new JobRequest.Builder(AccountRemovalJob.TAG).setUpdateCurrent(true)
-                        .startNow().build().scheduleAsync();
+
+                OneTimeWorkRequest accountRemovalWork = new OneTimeWorkRequest.Builder(AccountRemovalWorker.class).build();
+                WorkManager.getInstance().enqueue(accountRemovalWork);
 
                 if (otherUserExists && getView() != null) {
                     onViewBound(getView());

+ 9 - 8
app/src/main/java/com/nextcloud/talk/jobs/AccountRemovalJob.java → app/src/main/java/com/nextcloud/talk/jobs/AccountRemovalWorker.java

@@ -29,7 +29,6 @@ import android.text.TextUtils;
 import android.util.Log;
 
 import com.bluelinelabs.logansquare.LoganSquare;
-import com.evernote.android.job.Job;
 import com.nextcloud.talk.R;
 import com.nextcloud.talk.api.NcApi;
 import com.nextcloud.talk.application.NextcloudTalkApplication;
@@ -46,6 +45,7 @@ import java.util.zip.CRC32;
 
 import javax.inject.Inject;
 
+import androidx.work.Worker;
 import autodagger.AutoInjector;
 import io.reactivex.CompletableObserver;
 import io.reactivex.Observer;
@@ -56,8 +56,8 @@ import okhttp3.OkHttpClient;
 import retrofit2.Retrofit;
 
 @AutoInjector(NextcloudTalkApplication.class)
-public class AccountRemovalJob extends Job {
-    public static final String TAG = "AccountRemovalJob";
+public class AccountRemovalWorker extends Worker {
+    public static final String TAG = "AccountRemovalWorker";
 
     @Inject
     UserUtils userUtils;
@@ -72,7 +72,7 @@ public class AccountRemovalJob extends Job {
 
     @NonNull
     @Override
-    protected Result onRunJob(Params params) {
+    public Result doWork() {
         NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
 
         PushConfigurationState pushConfigurationState;
@@ -119,13 +119,14 @@ public class AccountRemovalJob extends Job {
                                                     @Override
                                                     public void onNext(Void aVoid) {
                                                         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
-                                                            String groupName = String.format(getContext().getResources().getString(R.string
-                                                                    .nc_notification_channel), userEntity.getUserId(), userEntity.getBaseUrl());
+                                                            String groupName = String.format(getApplicationContext().getResources()
+                                                                    .getString(R.string
+                                                                            .nc_notification_channel), userEntity.getUserId(), userEntity.getBaseUrl());
                                                             CRC32 crc32 = new CRC32();
                                                             crc32.update(groupName.getBytes());
                                                             NotificationManager notificationManager =
-                                                                    (NotificationManager) getContext().getSystemService(Context
-                                                                            .NOTIFICATION_SERVICE);
+                                                                    (NotificationManager) getApplicationContext().getSystemService
+                                                                            (Context.NOTIFICATION_SERVICE);
 
                                                             if (notificationManager != null) {
                                                                 notificationManager.deleteNotificationChannelGroup(Long

+ 44 - 41
app/src/main/java/com/nextcloud/talk/jobs/CapabilitiesJob.java → app/src/main/java/com/nextcloud/talk/jobs/CapabilitiesWorker.java

@@ -24,7 +24,6 @@ import android.support.annotation.NonNull;
 import android.util.Log;
 
 import com.bluelinelabs.logansquare.LoganSquare;
-import com.evernote.android.job.Job;
 import com.nextcloud.talk.api.NcApi;
 import com.nextcloud.talk.application.NextcloudTalkApplication;
 import com.nextcloud.talk.events.EventStatus;
@@ -42,6 +41,8 @@ import java.util.List;
 
 import javax.inject.Inject;
 
+import androidx.work.Data;
+import androidx.work.Worker;
 import autodagger.AutoInjector;
 import io.reactivex.Observer;
 import io.reactivex.disposables.Disposable;
@@ -51,8 +52,8 @@ import okhttp3.OkHttpClient;
 import retrofit2.Retrofit;
 
 @AutoInjector(NextcloudTalkApplication.class)
-public class CapabilitiesJob extends Job {
-    public static final String TAG = "CapabilitiesJob";
+public class CapabilitiesWorker extends Worker {
+    public static final String TAG = "CapabilitiesWorker";
 
     @Inject
     UserUtils userUtils;
@@ -68,12 +69,50 @@ public class CapabilitiesJob extends Job {
 
     NcApi ncApi;
 
+    private void updateUser(CapabilitiesOverall capabilitiesOverall, UserEntity internalUserEntity) {
+        try {
+            userUtils.createOrUpdateUser(null, null,
+                    null, null,
+                    null, null, null, internalUserEntity.getId(),
+                    LoganSquare.serialize(capabilitiesOverall.getOcs().getData().getCapabilities()), null)
+                    .subscribeOn(Schedulers.newThread())
+                    .subscribe(new Observer<UserEntity>() {
+                        @Override
+                        public void onSubscribe(Disposable d) {
+
+                        }
+
+                        @Override
+                        public void onNext(UserEntity userEntity) {
+                            eventBus.post(new EventStatus(userEntity.getId(),
+                                    EventStatus.EventType.CAPABILITIES_FETCH, true));
+                        }
+
+                        @Override
+                        public void onError(Throwable e) {
+                            eventBus.post(new EventStatus(internalUserEntity.getId(),
+                                    EventStatus.EventType.CAPABILITIES_FETCH, false));
+                        }
+
+                        @Override
+                        public void onComplete() {
+
+                        }
+                    });
+        } catch (IOException e) {
+            Log.e(TAG, "Failed to create or update user");
+        }
+
+    }
+
     @NonNull
     @Override
-    protected Result onRunJob(Params params) {
+    public Result doWork() {
         NextcloudTalkApplication.getSharedApplication().getComponentApplication().inject(this);
 
-        long internalUserId = getParams().getExtras().getLong(BundleKeys.KEY_INTERNAL_USER_ID, -1);
+        Data data = getInputData();
+
+        long internalUserId = data.getLong(BundleKeys.KEY_INTERNAL_USER_ID, -1);
 
         UserEntity userEntity;
         List userEntityObjectList = new ArrayList();
@@ -121,40 +160,4 @@ public class CapabilitiesJob extends Job {
 
         return Result.SUCCESS;
     }
-
-    private void updateUser(CapabilitiesOverall capabilitiesOverall, UserEntity internalUserEntity) {
-        try {
-            userUtils.createOrUpdateUser(null, null,
-                    null, null,
-                    null, null, null, internalUserEntity.getId(),
-                    LoganSquare.serialize(capabilitiesOverall.getOcs().getData().getCapabilities()), null)
-                    .subscribeOn(Schedulers.newThread())
-                    .subscribe(new Observer<UserEntity>() {
-                        @Override
-                        public void onSubscribe(Disposable d) {
-
-                        }
-
-                        @Override
-                        public void onNext(UserEntity userEntity) {
-                            eventBus.post(new EventStatus(userEntity.getId(),
-                                    EventStatus.EventType.CAPABILITIES_FETCH, true));
-                        }
-
-                        @Override
-                        public void onError(Throwable e) {
-                            eventBus.post(new EventStatus(internalUserEntity.getId(),
-                                    EventStatus.EventType.CAPABILITIES_FETCH, false));
-                        }
-
-                        @Override
-                        public void onComplete() {
-
-                        }
-                    });
-        } catch (IOException e) {
-            Log.e(TAG, "Failed to create or update user");
-        }
-
-    }
 }

+ 5 - 4
app/src/main/java/com/nextcloud/talk/jobs/PushRegistrationJob.java → app/src/main/java/com/nextcloud/talk/jobs/PushRegistrationWorker.java

@@ -22,15 +22,16 @@ package com.nextcloud.talk.jobs;
 
 import android.support.annotation.NonNull;
 
-import com.evernote.android.job.Job;
 import com.nextcloud.talk.utils.PushUtils;
 
-public class PushRegistrationJob extends Job {
-    public static final String TAG = "PushRegistrationJob";
+import androidx.work.Worker;
+
+public class PushRegistrationWorker extends Worker {
+    public static final String TAG = "PushRegistrationWorker";
 
     @NonNull
     @Override
-    protected Result onRunJob(Params params) {
+    public Result doWork() {
         PushUtils pushUtils = new PushUtils();
         pushUtils.generateRsa2048KeyPair();
         pushUtils.pushRegistrationToServer();

+ 0 - 51
app/src/main/java/com/nextcloud/talk/jobs/creator/MagicJobCreator.java

@@ -1,51 +0,0 @@
-/*
- * Nextcloud Talk application
- *
- * @author Mario Danic
- * Copyright (C) 2017-2018 Mario Danic <mario@lovelyhq.com>
- *
- * This program is free software: you can redistribute it and/or modify
- * it under the terms of the GNU General Public License as published by
- * the Free Software Foundation, either version 3 of the License, or
- * at your option) any later version.
- *
- * This program is distributed in the hope that it will be useful,
- * but WITHOUT ANY WARRANTY; without even the implied warranty of
- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
- * GNU General Public License for more details.
- *
- * You should have received a copy of the GNU General Public License
- * along with this program.  If not, see <http://www.gnu.org/licenses/>.
- */
-
-package com.nextcloud.talk.jobs.creator;
-
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-
-import com.evernote.android.job.Job;
-import com.evernote.android.job.JobCreator;
-import com.nextcloud.talk.jobs.AccountRemovalJob;
-import com.nextcloud.talk.jobs.CapabilitiesJob;
-import com.nextcloud.talk.jobs.NotificationWorker;
-import com.nextcloud.talk.jobs.PushRegistrationJob;
-
-public class MagicJobCreator implements JobCreator {
-
-    @Nullable
-    @Override
-    public Job create(@NonNull String tag) {
-        switch (tag) {
-            case PushRegistrationJob.TAG:
-                return new PushRegistrationJob();
-            case AccountRemovalJob.TAG:
-                return new AccountRemovalJob();
-            case NotificationWorker.TAG:
-                return new NotificationWorker();
-            case CapabilitiesJob.TAG:
-                return new CapabilitiesJob();
-            default:
-                return null;
-        }
-    }
-}

+ 1 - 1
build.gradle

@@ -13,7 +13,7 @@ buildscript {
         }
     }
     dependencies {
-        classpath 'com.android.tools.build:gradle:3.1.3'
+        classpath 'com.android.tools.build:gradle:3.1.4'
         classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:${kotlinVersion}"
 
         // NOTE: Do not place your application dependencies here; they belong