Complete guide to implementing Firebase Cloud Messaging (FCM) and Baidu push notifications in Android social.plus SDK
Integrate real-time push notifications into your Android app using Firebase Cloud Messaging (FCM) or Baidu Push (for China market) to ensure users never miss important updates.
Push notifications require proper FCM setup and valid server configuration. Test thoroughly before production deployment.
FCM tokens can change during the app lifecycle. Implement token monitoring:
Copy
Ask AI
import com.google.firebase.messaging.FirebaseMessagingServiceclass AmityFirebaseMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) { super.onNewToken(token) Log.d(TAG, "Refreshed token: $token") // Send token to your server if needed sendTokenToServer(token) // Update Amity SDK with new token updateAmityFcmToken(token) } private fun updateAmityFcmToken(token: String) { AmityFcm.create() .setup(token) .subscribe( onSuccess = { Log.d(TAG, "FCM token updated successfully") }, onError = { error -> Log.e(TAG, "FCM token update failed", error) } ) } private fun sendTokenToServer(token: String) { // Implement your server communication logic here // This is useful for sending targeted notifications from your backend } companion object { private const val TAG = "AmityFCMService" }}
Don’t forget to register the service in your AndroidManifest.xml:
class PushErrorHandler { fun handlePushError(error: Throwable) { when (error) { is FirebaseMessagingException -> handleFCMError(error) is SecurityException -> handlePermissionError() is NetworkException -> handleNetworkError() else -> handleGenericError(error) } } private fun handleFCMError(error: FirebaseMessagingException) { Log.e(TAG, "FCM Error: ${error.message}") // Implement retry logic } private fun handlePermissionError() { // Request notification permissions } private fun handleNetworkError() { // Retry when network is available }}
Performance Optimization
Efficient Processing: Optimize notification handling for better performance.
Copy
Ask AI
class OptimizedNotificationHandler { private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob()) fun processNotification(data: Map<String, String>) { scope.launch { try { // Process in background thread val processedData = processNotificationData(data) // Switch to main thread for UI updates withContext(Dispatchers.Main) { updateUI(processedData) } } catch (e: Exception) { Log.e(TAG, "Notification processing failed", e) } } }}
Testing & Debugging
Comprehensive Testing: Test push notifications thoroughly across different scenarios.
Copy
Ask AI
class PushNotificationTester { fun testPushNotification() { // Test with Firebase Console // Test with server-side sending // Test token refresh scenarios // Test offline/online scenarios } fun enableDebugLogging() { if (BuildConfig.DEBUG) { FirebaseMessaging.getInstance().isAutoInitEnabled = true // Enable verbose logging } }}