I want to execute some code when my android device receives a push notification. I have the following files: MainActivity.java
, MyFirebaseMessagingService.java
.
In MainActivity
, I start the messaging service:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, MyFirebaseMessagingService.class));
}
and in MyFirebaseMessagingService
, I override the onMessageReceived
method as follows:
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = MyFirebaseMessagingService.class.getName();
public MyFirebaseMessagingService() {
super();
Log.d(TAG, "init");
}
@Override
public void onNewToken(String token) {
Log.d(TAG, "app-token: " + token);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.d(TAG, "on-message-received");
}
Also, in my AndroidManifest
, I have the following setup inside <application>
:
<service
android:name=".MyFirebaseMessagingService"
android:stopWithTask="false"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<action android:name=".MyFirebaseMessagingService" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
I then fire the notification, which appears on my device (it vibrates and I see the notification's title):
curl https://fcm.googleapis.com/fcm/send \
-H "Authorization:key=<my-key>" \
-H "Content-Type:application/json" \
-d '{
"to" : "<device token>",
"notification": {
"title": "hello from the server"
},
// or:
"data": {
"title": "hello from the server"
},
"priority": "high"
}'
However, my code inside onMessageReceived
is never executed.
I noticed that the log in onNewToken
is also not called, so I'm assuming that the whole class is being ignored entirely.
The log inside MyFirebaseMessagingService
's init method is called, so I know the class is registered. Just onMessageReceived
isn't called – neither in fore-, nor in background; tried with both "data"
and "notification"
payloads.
I did a lot of research and there are tons of similar questions, but all fixes I found, like regarding the manifest, or the gradle configurations did not help me.
What am I doing wrong?
[Disclaimer: I'm an absolute beginner to Android development.]