Hi everyone.
I’m trying to figure out how to use the Capacitor Android bridge in a class, not in a plugin. Specifically, I’ve created a native NotificationServiceExtension
class per OneSignal docs so the app can receive background/data notifications. The notifications are received correctly in the class, so now I want to inform the JS layer of the received notification. Per Capacitor docs, we should be able to achieve this by calling bridge.triggerJSEvent("myCustomEvent", "document", "{ 'dataKey': 'dataValue' }");
.
However when this line is executed, I get an error:
Attempt to invoke virtual method 'void com.getcapacitor.Bridge.triggerJSEvent(java.lang.String, java.lang.String, java.lang.String)' on a null object reference
.
android/app/src/main/java/com/mycompany/myapp/NotificationServiceExtension.java:
package com.mycompany.myapp;
// Import bridge
import com.getcapacitor.Bridge;
import com.onesignal.notifications.IDisplayableMutableNotification;
import com.onesignal.notifications.INotificationReceivedEvent;
import com.onesignal.notifications.INotificationServiceExtension;
import com.onesignal.debug.internal.logging.Logging;
public class NotificationServiceExtension implements INotificationServiceExtension {
// TODO: Initialize bridge
@Override
public void onNotificationReceived(INotificationReceivedEvent event) {
IDisplayableMutableNotification notification = event.getNotification();
Logging.info(String.format("NotificationServiceExtension::onNotificationReceived: notificationId=%s, additionalData=%s", notification.getNotificationId(), notification.getAdditionalData()), null);
// TODO: Use bridge
// bridge.triggerJSEvent("myCustomEvent", "document", "{ 'dataKey': 'dataValue' }");
}
}
android/app/src/main/AndroidManifest.xml
<?xml version='1.0' encoding='utf-8'?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme" android:usesCleartextTraffic="true">
<activity android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|smallestScreenSize|screenLayout|uiMode" android:exported="true" android:label="@string/title_activity_main" android:launchMode="singleTask" android:name=".MainActivity" android:theme="@style/AppTheme.NoActionBarLaunch">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data android:name="com.onesignal.NotificationServiceExtension" android:value="com.skoop.terminal2.NotificationServiceExtension" />
</application>
<uses-permission android:name="android.permission.INTERNET" />
</manifest>
Thanks for your help!