1 /* 2 * Copyright (C) 2021 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.imsserviceentitlement.fcm; 18 19 import static java.util.concurrent.TimeUnit.SECONDS; 20 21 import android.content.Context; 22 import android.content.SharedPreferences; 23 import android.util.Log; 24 25 import androidx.annotation.WorkerThread; 26 27 import com.android.imsserviceentitlement.utils.TelephonyUtils; 28 29 import java.util.concurrent.CountDownLatch; 30 31 /** Convenience methods for FCM. */ 32 public final class FcmUtils { 33 public static final String LOG_TAG = "IMSSE-FcmUtils"; 34 35 private static final long TOKEN_UPDATE_WAITING_SECONDS = 25L; 36 FcmUtils()37 private FcmUtils() {} 38 39 /** Fetches FCM token, if it's not available via {@link FcmTokenStore#getToken}. */ 40 @WorkerThread fetchFcmToken(Context context, int subId)41 public static void fetchFcmToken(Context context, int subId) { 42 if (TelephonyUtils.getFcmSenderId(context, subId).isEmpty()) { 43 return; 44 } 45 46 if (FcmTokenStore.hasToken(context, subId)) { 47 Log.d(LOG_TAG, "FCM token available."); 48 return; 49 } 50 51 Log.d(LOG_TAG, "FCM token unavailable. Try to update..."); 52 final CountDownLatch tokenUpdated = new CountDownLatch(1); 53 final SharedPreferences.OnSharedPreferenceChangeListener listener = 54 (s, k) -> { 55 Log.d(LOG_TAG, "FCM preference changed."); 56 if (FcmTokenStore.hasToken(context, subId)) { 57 tokenUpdated.countDown(); 58 } 59 }; 60 FcmTokenStore.registerTokenUpdateListener(context, listener); 61 62 // Starts a JobIntentService to update FCM token by calling FCM API on a worker thread. 63 FcmRegistrationService.enqueueJob(context); 64 65 try { 66 // Wait for 25s. If FCM token update failed/timeout, we will let user see 67 // the error message returned by server. Then user can manually retry. 68 if (tokenUpdated.await(TOKEN_UPDATE_WAITING_SECONDS, SECONDS)) { 69 Log.d(LOG_TAG, "FCM token updated."); 70 } else { 71 Log.d(LOG_TAG, "FCM token update failed."); 72 } 73 } catch (InterruptedException e) { 74 // Do nothing 75 Log.d(LOG_TAG, "FCM token update interrupted."); 76 } 77 FcmTokenStore.unregisterTokenUpdateListener(context, listener); 78 } 79 } 80