Search code examples
androidfirebaseandroid-vibrationandroid-binder

Call methods of Firebase Messaging Service from main activity


TL;DR: How can I turn off the vibration, which is turned on in the Firebase Messaging Service, in the main activity?

I'm creating an app which gets push notifications from Firebase. Those push notifications are generated by a PIR motion sensor connected to my raspberry pi.

The aim of this app is, that when the PIR detects motions an alarm should start on my phone. (Right now this alarm realized by the vibration of my phone).

So far the vibration alarm starts (which is done within my Firebase Messaging Service) and I want to be able to end the alarm by clicking a button in the app.

From my understanding of "classical" java programming I have to access the Vibrator object that is used in my Firebase service from the main activity. But how can I do this? I tried to do it with binders but that dosen't work because the onBind() method in FirebaseMessagingService is final and can't be overridden.

My current code can be seen here:

public class FcmMessagingService extends FirebaseMessagingService {
Vibrator alarmVibrator;

@Override
public void onCreate() {
    super.onCreate();
    alarmVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
}

@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
    if (remoteMessage.getData().get("Alarm").equals("1")){
        Log.d("alarm","on");
        alarmVibrator.vibrate(10000);
    }else{
        Log.d("alarm","off");
        alarmVibrator.cancel();
    }
}

This code works to turn on the vibration (for some reason the turning off part dosen't work, but thats a problem I might look into later)


Solution

  • I think if you define alarmVibrator just one time in a base Activtiy, you will be able to turning on or off in FcmMessagingService class.

    for example you can define it in AppController class as below:

    public static Vibrator alarmVibrator;

    then you could handle like this:

       @Override
        public void onMessageReceived(RemoteMessage remoteMessage) {
           if (remoteMessage.getData().get("Alarm").equals("1")){
            Log.d("alarm","on");
            AppController.alarmVibrator.vibrate(10000);
           }else{
            Log.d("alarm","off");
            AppController.alarmVibrator.cancel();
           }
        }