Push Notifications for WebView Apps: Complete OneSignal & Firebase Integration

A practical developer guide to setting up Firebase Cloud Messaging (FCM) and OneSignal push alerts in converted Android WebView applications.

1. The Power of Native Push Notifications

Push notifications represent the direct communication superpower of mobile applications. When implemented with strategic segmentation and timely triggers, push notifications deliver click-through rates up to 10x higher than traditional email campaigns and drive immediate spikes in active user sessions.

In a converted Android WebView application, push notifications bridge the gap between your server-side content updates and the user’s physical device hardware, waking up the app, displaying custom branded icons in the notification shade, and deep-linking directly to target URLs.

2. OneSignal vs Firebase Cloud Messaging (FCM): Which to Choose?

Both platforms provide enterprise-grade delivery infrastructure, but they serve different developer workflows:

Criteria OneSignal Firebase Cloud Messaging (FCM)
Setup Complexity Low (Turnkey REST API & Plugins) Medium (Requires custom backend bridge)
Automated Segments Built-in UI (Inactive users, tags, geography) Requires BigQuery / Custom analytics
Pricing Free tier up to 10,000 subscribers 100% Free with unlimited volume

3. OneSignal Integration Walkthrough

Setting up OneSignal in your FreeWebAPK project requires just three steps:

  1. Create a OneSignal Account: Register at OneSignal.com and add a new app configured for “Google Android (FCM)”.
  2. Link Firebase Server Key: Generate your google-services.json configuration file from the Firebase Console and upload your Server API Key to OneSignal.
  3. Configure FreeWebAPK Generator: In the FreeWebAPK Advanced Options panel, paste your OneSignal App ID. The cloud compiler automatically injects the OneSignal Android SDK into your application binary during build time.

4. Deep-Linking: Routing Clicks Directly to Target Pages

Nothing frustrates a mobile user more than tapping a notification about a specific article or product, only to have the app open to the generic homepage. Deep linking ensures that the user is routed directly to the exact target content.

When dispatching your notification payload via the OneSignal REST API, supply the target URL in the data.url parameter:

{
  "app_id": "YOUR-ONESIGNAL-APP-ID",
  "headings": {"en": "Flash Sale: 30% Off Today Only!"},
  "contents": {"en": "Tap to claim your exclusive discount on premium items."},
  "url": "https://yourwebsite.com/flash-sale-collection",
  "big_picture": "https://yourwebsite.com/images/sale-banner.jpg",
  "android_channel_id": "promotions-channel"
}

5. Android 13+ Notification Channels & Permissions

Starting with Android 13 (API Level 33), Google introduced the runtime POST_NOTIFICATIONS permission. Apps can no longer send notifications silently; users must explicitly grant permission via a system dialog.

Best practices for maximizing opt-in rates:

  • Do Not Prompt on First Launch: Allow users to explore your app first. Trigger the permission dialog after the user reads an article or adds an item to cart.
  • Use an In-App Pre-Permission Prompt: Show a branded modal explaining the value: “Enable alerts to receive breaking updates and order tracking.”
  • Implement Notification Channels: Categorize notifications into distinct channels (e.g. “Order Updates”, “Breaking News”, “Promotions”) so users can customize alert preferences rather than muting all app notifications.

6. Summary: Automated Engagement on Autopilot

Integrating push notifications into your Android WebView application transforms a passive website into an active, high-retention customer engine. Set up automated triggers once, and watch your daily active users and conversion rates scale automatically.

6. Android Notification Channels & POST_NOTIFICATIONS Permissions

Beginning with Android 13 (API level 33), Google introduced the runtime POST_NOTIFICATIONS permission. Applications cannot send push notifications without explicit user consent. Furthermore, Android requires notifications to be categorized into distinct Notification Channels, empowering users to customize alert behaviors (sound, vibration, badge indicators) per category.

In your native Android wrapper, configure notification channels upon startup:

import android.app.NotificationChannel
import android.app.NotificationManager
import android.os.Build

fun createNotificationChannels(context: Context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        val manager = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        
        // Channel 1: High-Priority Breaking News & Flash Alerts
        val breakingChannel = NotificationChannel(
            "channel_breaking",
            "Breaking News & Alerts",
            NotificationManager.IMPORTANCE_HIGH
        ).apply {
            description = "Crucial updates and urgent account notifications"
            enableVibration(true)
        }
        
        // Channel 2: Marketing & Promotions
        val promoChannel = NotificationChannel(
            "channel_promotions",
            "Promotions & Deals",
            NotificationManager.IMPORTANCE_DEFAULT
        ).apply {
            description = "Special discounts, product drops, and weekly roundups"
        }
        
        manager.createNotificationChannel(breakingChannel)
        manager.createNotificationChannel(promoChannel)
    }
}

7. Designing High-Converting Rich Push Notification Payloads

Plain text notifications achieve mediocre click-through rates (~4%). By enhancing your notifications with rich media thumbnails, action buttons, and direct deep link URLs, click-through rates routinely surge past 18%:

{
  "to": "/topics/all_users",
  "notification": {
    "title": "⚡ 50% Flash Sale Activated!",
    "body": "Your saved summer collection is now half price. Claim before midnight.",
    "image": "https://yourdomain.com/assets/images/flash-sale-banner.jpg",
    "android_channel_id": "channel_promotions"
  },
  "data": {
    "click_action": "FLASHSALE_INTENT",
    "target_url": "https://yourdomain.com/collections/flash-sale",
    "badge_count": "1"
  }
}

8. Push Timing & Frequency: Avoiding Opt-Out Fatigue

Never bombard users with multiple daily generic blasts. Follow the golden rules of push cadence: deliver notifications timed to the user’s local timezone (between 10:00 AM and 8:00 PM), cap general marketing alerts to 2-3 per week, and reserve immediate real-time alerts exclusively for critical transactional events (order dispatched, password reset, security alert).

9. Production Diagnostics: Resolving Push Delivery Failures

If users report not receiving push notifications, investigate these root causes:

  • Battery Optimization & App Standby: Aggressive manufacturer battery savers (Samsung, Xiaomi, Huawei) kill background tasks. Prompt users who require critical alerts to exempt your app from battery optimization via ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS.
  • FCM Token Invalidation: Firebase tokens expire periodically or change upon app reinstalls. Always listen for onNewToken() and immediately update the token in your backend database.
  • Notification Permission Denials: If a user denies the Android 13+ permission dialog, you cannot prompt them again programmatically. Provide an in-app banner explaining why notifications matter with a direct button leading to Android App Settings.

10. Advanced Push Automation: Behavior-Driven Triggers

Elevate your push messaging beyond generic broadcast alerts by implementing automated behavior-driven workflows: send automated welcome tips 24 hours after install, re-engage users who haven’t opened the app in 7 days with personalized recommendations, and trigger immediate celebratory alerts upon milestone completions.

11. Push Notification Architecture Validation Checklist

Push Delivery & Lifecycle Checklist

  • Android 13+ POST_NOTIFICATIONS: Verified runtime permission request triggers at contextually relevant moments.
  • Deep Link Routing: Confirmed background and killed-state notification taps navigate to target URLs.
  • Notification Icon Asset: Provided transparent silhouette icon (drawable/ic_stat_notification) for status bar display.
  • Token Refresh Endpoint: Tested server database update when FCM issues an onNewToken callback.

12. Real-World Case Study: Flash Sale Push Notification Blitz

Case Study: Kora Footwear Flash Campaign

Kora Footwear tested targeted push notifications against email marketing for a 4-hour sneaker restock:

Open Rate (First 15m)
38.4%
vs 6.2% for email blast
Click-to-Purchase
14.1%
deep link direct to cart
Revenue per Recipient
$4.82
5.1x higher than email

The high delivery speed of Firebase Cloud Messaging ensured inventory sold out in under 90 minutes with zero advertising cost.

13. Production Kotlin Code: Custom FirebaseMessagingService Handler

Configure your native push notification listener to handle incoming messages and build rich notifications:

import com.google.firebase.messaging.FirebaseMessagingService
import com.google.firebase.messaging.RemoteMessage
import androidx.core.app.NotificationCompat
import android.app.PendingIntent

class PushService : FirebaseMessagingService() {
    override fun onMessageReceived(remoteMessage: RemoteMessage) {
        val title = remoteMessage.notification?.title ?: "New Update"
        val body = remoteMessage.notification?.body ?: "Tap to view details"
        val targetUrl = remoteMessage.data["target_url"] ?: "https://yourdomain.com"
        
        val intent = Intent(this, MainActivity::class.java).apply {
            putExtra("OPEN_URL", targetUrl)
            flags = Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP
        }
        val pendingIntent = PendingIntent.getActivity(
            this, 0, intent, 
            PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
        )
        
        val notification = NotificationCompat.Builder(this, "channel_breaking")
            .setSmallIcon(R.drawable.ic_stat_notification)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setContentIntent(pendingIntent)
            .setPriority(NotificationCompat.PRIORITY_HIGH)
            .build()
            
        val manager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        manager.notify(System.currentTimeMillis().toInt(), notification)
    }
}

This ensures tapping an alert cold-launches your application directly into the specific article or promotion.

14. Key Takeaways & Push Strategy Playbook

Push Messaging Best Practices

  • Segment by Intent: Deliver messages based on user browsing history and favorite categories rather than universal blasts.
  • Respect Local Timezones: Never schedule marketing notifications between 9:00 PM and 9:00 AM in the recipient’s local timezone.
  • A/B Test Headlines: Test emojis, urgency phrasing, and direct discount codes to lift open rates past 25%.

Frequently Asked Questions

Do push notifications work when the app is completely closed?

Yes. Both Firebase Cloud Messaging and OneSignal utilize native Android background services that receive and display notifications even when the app is fully swiped away from recent apps.

Can I send rich media notifications with images?

Yes. Android notifications support ‘Big Picture’ styles with wide 16:9 images, branded notification icons, and action buttons (e.g. ‘View Order’ or ‘Dismiss’).

How many push notifications should I send per week?

For content and news publishers, 1-2 breaking news alerts per day is optimal. For eCommerce stores, 2-3 targeted messages per week (flash sales, abandoned cart recovery, order updates) delivers the highest ROI without driving uninstalls.

Is there any cost for Firebase Cloud Messaging?

No. Firebase Cloud Messaging (FCM) is 100% free with no limits on the number of messages or devices.

Does FreeWebAPK handle the native Android permission code?

Yes. FreeWebAPK includes the native POST_NOTIFICATIONS permission declaration and runtime prompt handling automatically in Target SDK 34 builds.

Can I send push notifications for free?

Yes! Firebase Cloud Messaging (FCM) is completely free with no message limits. OneSignal also provides a generous free tier supporting up to 10,000 subscribers with zero monthly fees.

What happens if a user taps a notification while the app is closed?

FreeWebAPK’s native manifest intent filters catch the notification click intent, launch the app cold, and immediately navigate the WebView directly to the targeted article or product page.

Why do notification icons appear as white squares on modern Android?

Android requires notification status bar icons to be monochrome white silhouettes with transparent backgrounds. Any colored square icons are rendered as solid white blocks by the system.

Can I schedule automated push notifications in advance?

Yes! Both OneSignal and Firebase Cloud Messaging permit scheduling notifications for specific dates, times, and user local timezones.

Can push notifications wake an Android device from Doze mode?

Yes, messages marked with ‘priority: high’ in Firebase Cloud Messaging bypass Android’s Doze mode and ring immediately on the user’s screen.

Leave a Comment