Skip to content

Commit 5594c34

Browse files
authored
Merge pull request #19701 from wordpress-mobile/Migrate-GCMRegistrationService-from-JobIntentService-to-WorkManager
Migrate GCM Registration Service from JobIntentService to WorkManager
2 parents c625802 + 086d1b5 commit 5594c34

8 files changed

Lines changed: 146 additions & 115 deletions

File tree

WordPress/src/main/AndroidManifest.xml

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1040,11 +1040,6 @@
10401040
android:name="com.google.android.gms.version"
10411041
android:value="@integer/google_play_services_version" />
10421042

1043-
<service
1044-
android:name=".push.GCMRegistrationIntentService"
1045-
android:permission="android.permission.BIND_JOB_SERVICE"
1046-
android:exported="false" />
1047-
10481043
<service
10491044
android:name=".push.GCMMessageService"
10501045
android:exported="false">

WordPress/src/main/java/org/wordpress/android/AppInitializer.kt

Lines changed: 6 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ import android.app.NotificationManager
1111
import android.app.SyncNotedAppOp
1212
import android.content.ComponentCallbacks2
1313
import android.content.Context
14-
import android.content.Intent
1514
import android.content.IntentFilter
1615
import android.content.res.Configuration
1716
import android.database.SQLException
@@ -76,7 +75,7 @@ import org.wordpress.android.modules.APPLICATION_SCOPE
7675
import org.wordpress.android.networking.ConnectionChangeReceiver
7776
import org.wordpress.android.networking.OAuthAuthenticator
7877
import org.wordpress.android.networking.RestClientUtils
79-
import org.wordpress.android.push.GCMRegistrationIntentService
78+
import org.wordpress.android.push.GCMRegistrationScheduler
8079
import org.wordpress.android.push.NotificationType
8180
import org.wordpress.android.support.ZendeskHelper
8281
import org.wordpress.android.ui.ActivityId
@@ -193,6 +192,9 @@ class AppInitializer @Inject constructor(
193192
@Inject
194193
lateinit var wordPressWorkerFactory: WordPressWorkersFactory
195194

195+
@Inject
196+
lateinit var gcmRegistrationScheduler: GCMRegistrationScheduler
197+
196198
@Inject
197199
lateinit var debugCookieManager: DebugCookieManager
198200

@@ -646,10 +648,7 @@ class AppInitializer @Inject constructor(
646648

647649
if (accountStore.hasAccessToken()) {
648650
// Make sure the Push Notification token is sent to our servers after a successful login
649-
GCMRegistrationIntentService.enqueueWork(
650-
application,
651-
Intent(application, GCMRegistrationIntentService::class.java)
652-
)
651+
gcmRegistrationScheduler.scheduleRegistration()
653652

654653
// Force a refresh if user has logged in. This can be removed once we start using an anonymous ID.
655654
exPlat.forceRefresh()
@@ -815,10 +814,7 @@ class AppInitializer @Inject constructor(
815814
// Sync Push Notifications settings
816815
if (isPushNotificationPingNeeded && accountStore.hasAccessToken()) {
817816
// Register for Cloud messaging
818-
GCMRegistrationIntentService.enqueueWork(
819-
context,
820-
Intent(context, GCMRegistrationIntentService::class.java)
821-
)
817+
gcmRegistrationScheduler.scheduleRegistration()
822818
}
823819
}
824820

WordPress/src/main/java/org/wordpress/android/push/GCMMessageService.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
package org.wordpress.android.push;
22

3-
import android.content.Intent;
43
import android.os.Bundle;
54

65
import androidx.annotation.NonNull;
@@ -40,6 +39,8 @@ public class GCMMessageService extends FirebaseMessagingService {
4039
@Inject GCMMessageHandler mGCMMessageHandler;
4140
@Inject JetpackFeatureRemovalPhaseHelper mJetpackFeatureRemovalPhaseHelper;
4241

42+
@Inject GCMRegistrationScheduler mGCMRegistrationScheduler;
43+
4344
private void synchronizedHandleDefaultPush(@NonNull Map<String, String> data) {
4445
// ACTIVE_NOTIFICATIONS_MAP being static, we can't just synchronize the method
4546
mSystemNotificationsTracker.track(AnalyticsTracker.Stat.NOTIFICATION_RECEIVED_PROCESSING_START);
@@ -98,7 +99,6 @@ public void onMessageReceived(RemoteMessage message) {
9899

99100
@Override public void onNewToken(@NonNull String s) {
100101
super.onNewToken(s);
101-
GCMRegistrationIntentService.enqueueWork(this,
102-
new Intent(this, GCMRegistrationIntentService.class));
102+
mGCMRegistrationScheduler.scheduleRegistration();
103103
}
104104
}

WordPress/src/main/java/org/wordpress/android/push/GCMRegistrationIntentService.java

Lines changed: 0 additions & 89 deletions
This file was deleted.
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package org.wordpress.android.push
2+
3+
import androidx.work.ExistingWorkPolicy
4+
import androidx.work.OneTimeWorkRequestBuilder
5+
import androidx.work.WorkManager
6+
import org.wordpress.android.viewmodel.ContextProvider
7+
import org.wordpress.android.workers.notification.push.GCMRegistrationWorker
8+
import javax.inject.Inject
9+
10+
class GCMRegistrationScheduler @Inject constructor(
11+
val contextProvider: ContextProvider
12+
) {
13+
private val workManager by lazy { WorkManager.getInstance(contextProvider.getContext()) }
14+
15+
fun scheduleRegistration() {
16+
workManager.enqueueUniqueWork(
17+
UNIQUE_WORK_NAME,
18+
ExistingWorkPolicy.KEEP,
19+
buildOneTimeWorkRequest()
20+
)
21+
}
22+
23+
private fun buildOneTimeWorkRequest() =
24+
OneTimeWorkRequestBuilder<GCMRegistrationWorker>()
25+
.addTag(UNIQUE_WORK_NAME)
26+
.build()
27+
28+
companion object {
29+
const val UNIQUE_WORK_NAME = "GCMRegistrationWork"
30+
}
31+
}

WordPress/src/main/java/org/wordpress/android/ui/main/WPMainActivity.java

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,7 @@
6666
import org.wordpress.android.networking.ConnectionChangeReceiver;
6767
import org.wordpress.android.push.GCMMessageHandler;
6868
import org.wordpress.android.push.GCMMessageService;
69-
import org.wordpress.android.push.GCMRegistrationIntentService;
69+
import org.wordpress.android.push.GCMRegistrationScheduler;
7070
import org.wordpress.android.push.NativeNotificationsUtils;
7171
import org.wordpress.android.push.NotificationType;
7272
import org.wordpress.android.push.NotificationsProcessingService;
@@ -276,6 +276,8 @@ public class WPMainActivity extends LocaleAwareActivity implements
276276

277277
@Inject BuildConfigWrapper mBuildConfigWrapper;
278278

279+
@Inject GCMRegistrationScheduler mGCMRegistrationScheduler;
280+
279281
/*
280282
* fragments implement this if their contents can be scrolled, called when user
281283
* requests to scroll to the top
@@ -471,8 +473,7 @@ && getIntent().getExtras().getBoolean(ARG_CONTINUE_JETPACK_CONNECT, false)) {
471473

472474
if (isGooglePlayServicesAvailable(this)) {
473475
// Register for Cloud messaging
474-
GCMRegistrationIntentService.enqueueWork(this,
475-
new Intent(this, GCMRegistrationIntentService.class));
476+
mGCMRegistrationScheduler.scheduleRegistration();
476477
}
477478

478479
if (canShowAppRatingPrompt) {
@@ -1386,8 +1387,7 @@ public void onClick(View v) {
13861387
case RequestCodes.REAUTHENTICATE:
13871388
if (resultCode == RESULT_OK) {
13881389
// Register for Cloud messaging
1389-
GCMRegistrationIntentService.enqueueWork(this,
1390-
new Intent(this, GCMRegistrationIntentService.class));
1390+
mGCMRegistrationScheduler.scheduleRegistration();
13911391
}
13921392
break;
13931393
case RequestCodes.LOGIN_EPILOGUE:
@@ -1448,8 +1448,7 @@ private void appLanguageChanged() {
14481448
}
14491449

14501450
private void startWithNewAccount() {
1451-
GCMRegistrationIntentService.enqueueWork(this,
1452-
new Intent(this, GCMRegistrationIntentService.class));
1451+
mGCMRegistrationScheduler.scheduleRegistration();
14531452
ReaderUpdateServiceStarter.startService(this, EnumSet.of(UpdateTask.TAGS, UpdateTask.FOLLOWED_BLOGS));
14541453
}
14551454

WordPress/src/main/java/org/wordpress/android/workers/WordPressWorkersFactory.kt

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,14 @@
11
package org.wordpress.android.workers
22

33
import androidx.work.DelegatingWorkerFactory
4+
import org.wordpress.android.fluxc.store.AccountStore
45
import org.wordpress.android.fluxc.store.SiteStore
6+
import org.wordpress.android.support.ZendeskHelper
57
import org.wordpress.android.ui.uploads.UploadStarter
68
import org.wordpress.android.util.UploadWorker
79
import org.wordpress.android.workers.notification.local.LocalNotificationHandlerFactory
810
import org.wordpress.android.workers.notification.local.LocalNotificationWorker
11+
import org.wordpress.android.workers.notification.push.GCMRegistrationWorker
912
import org.wordpress.android.workers.reminder.ReminderNotifier
1013
import org.wordpress.android.workers.reminder.ReminderScheduler
1114
import org.wordpress.android.workers.reminder.ReminderWorker
@@ -21,12 +24,15 @@ class WordPressWorkersFactory @Inject constructor(
2124
reminderScheduler: ReminderScheduler,
2225
reminderNotifier: ReminderNotifier,
2326
weeklyRoundupNotifier: WeeklyRoundupNotifier,
24-
promptReminderNotifier: PromptReminderNotifier
27+
promptReminderNotifier: PromptReminderNotifier,
28+
accountStore: AccountStore,
29+
zendeskHelper: ZendeskHelper
2530
) : DelegatingWorkerFactory() {
2631
init {
2732
addFactory(UploadWorker.Factory(uploadStarter, siteStore))
2833
addFactory(LocalNotificationWorker.Factory(localNotificationHandlerFactory))
2934
addFactory(ReminderWorker.Factory(reminderScheduler, reminderNotifier, promptReminderNotifier))
3035
addFactory(WeeklyRoundupWorker.Factory(weeklyRoundupNotifier))
36+
addFactory(GCMRegistrationWorker.Factory(accountStore, zendeskHelper))
3137
}
3238
}
Lines changed: 93 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,93 @@
1+
package org.wordpress.android.workers.notification.push
2+
3+
import android.content.Context
4+
import android.text.TextUtils
5+
import androidx.preference.PreferenceManager
6+
import androidx.work.CoroutineWorker
7+
import androidx.work.ListenableWorker
8+
import androidx.work.WorkerFactory
9+
import androidx.work.WorkerParameters
10+
import com.google.android.gms.tasks.Task
11+
import com.google.firebase.messaging.FirebaseMessaging
12+
import org.wordpress.android.fluxc.store.AccountStore
13+
import org.wordpress.android.support.ZendeskHelper
14+
import org.wordpress.android.ui.notifications.utils.NotificationsUtils
15+
import org.wordpress.android.util.AppLog
16+
import java.util.UUID
17+
18+
class GCMRegistrationWorker(
19+
val appContext: Context,
20+
val accountStore: AccountStore,
21+
val zendeskHelper: ZendeskHelper,
22+
workerParameters: WorkerParameters
23+
) : CoroutineWorker(appContext, workerParameters) {
24+
override suspend fun doWork(): Result {
25+
return try {
26+
FirebaseMessaging
27+
.getInstance()
28+
.token
29+
.addOnCompleteListener { task: Task<String?> ->
30+
if (!task.isSuccessful) {
31+
AppLog.e(
32+
AppLog.T.NOTIFS,
33+
"Fetching FCM registration token failed: ",
34+
task.exception
35+
)
36+
return@addOnCompleteListener
37+
}
38+
val token = task.result
39+
sendRegistrationToken(token)
40+
}
41+
42+
Result.success()
43+
} catch (e: SecurityException) {
44+
// SecurityException can happen on some devices without Google services (these devices probably strip
45+
// the AndroidManifest.xml and remove unsupported permissions).
46+
AppLog.e(AppLog.T.NOTIFS, "Google Play Services unavailable: ", e)
47+
Result.failure()
48+
}
49+
}
50+
51+
class Factory(
52+
private val accountStore: AccountStore,
53+
private val zendeskHelper: ZendeskHelper
54+
) : WorkerFactory() {
55+
override fun createWorker(
56+
appContext: Context,
57+
workerClassName: String,
58+
workerParameters: WorkerParameters
59+
): ListenableWorker? {
60+
return if (workerClassName == GCMRegistrationWorker::class.java.name) {
61+
GCMRegistrationWorker(appContext, accountStore, zendeskHelper, workerParameters)
62+
} else {
63+
null
64+
}
65+
}
66+
}
67+
68+
private fun sendRegistrationToken(gcmToken: String?) {
69+
if (!TextUtils.isEmpty(gcmToken)) {
70+
AppLog.i(
71+
AppLog.T.NOTIFS,
72+
"Sending GCM token to our remote services: $gcmToken"
73+
)
74+
// Register to WordPress.com notifications
75+
if (accountStore.hasAccessToken()) {
76+
val preferences = PreferenceManager.getDefaultSharedPreferences(appContext)
77+
// Get or create UUID for WP.com notes api
78+
var uuid = preferences.getString(NotificationsUtils.WPCOM_PUSH_DEVICE_UUID, null)
79+
if (uuid == null) {
80+
uuid = UUID.randomUUID().toString()
81+
preferences.edit().putString(NotificationsUtils.WPCOM_PUSH_DEVICE_UUID, uuid).apply()
82+
}
83+
preferences.edit().putString(NotificationsUtils.WPCOM_PUSH_DEVICE_TOKEN, gcmToken).apply()
84+
NotificationsUtils.registerDeviceForPushNotifications(appContext, gcmToken)
85+
}
86+
zendeskHelper.enablePushNotifications()
87+
} else {
88+
AppLog.w(AppLog.T.NOTIFS, "Empty GCM token, can't register the id on remote services")
89+
PreferenceManager.getDefaultSharedPreferences(appContext).edit()
90+
.remove(NotificationsUtils.WPCOM_PUSH_DEVICE_TOKEN).apply()
91+
}
92+
}
93+
}

0 commit comments

Comments
 (0)