Search code examples
androiddartflutteralarmmanagerandroid-workmanager

Alarm service with flutter callback


I am trying to create an alarmservice with callback to flutter. I tried the existing alarm_manager for flutter and it doesnt compile. I need to check the location of the user in the background in a periodic time and alert the user if certain conditions are met. The alert is on Flutter(Dart callback method).

I used MethodChannel to create a callback to the flutter dart code. But when I try to pass the methodchannel to the alarm service, I am not sure how I should pass the FlutterAcitvity with it.

public class MainActivity extends FlutterActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    GeneratedPluginRegistrant.registerWith(this);
    MethodChannel trigger = new MethodChannel(getFlutterView(), "service:BackgroundTrigger");
    trigger.setMethodCallHandler(new CallBackWorker(getFlutterView()));
}

class CallBackWorker implements MethodCallHandler {
    FlutterView view;

    CallBackWorker(FlutterView view) {
        this.view = view;
    }

    @Override
    public void onMethodCall(MethodCall methodCall, MethodChannel.Result result) {
        AlarmManager mgr=(AlarmManager)getApplicationContext().getSystemService(Context.ALARM_SERVICE);
        Intent i=new Intent(getApplicationContext(), MyService.class);
        i.putExtra("FlutterView",getFlutterView()); //This is the problem.
        PendingIntent alarmIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, i, 0);

        mgr.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                SystemClock.elapsedRealtime() +
                        60 * 1000, alarmIntent);
    }
}

}

In the above code when the user clicks on a button, the service:BackgroundTrigger is triggered which will register him to the alarm service by invoking the CallBackWorker.

Now to invoke the Dart callback method, I need access to the flutter view in the alarm service. I am not sure how to pass it there.

If there is a way to invoke a dart callback from a WorkManager it would be better.

Any help would be much appreciated.


Solution

  • android_alarm_manager has been deprecated and developers are recommended to use android_alarm_manager_plus. The former is no longer being updated. On the current version of the android_alarm_manager_plus plugin, there's no need to set up MethodChannel for a simple callback. You can just call AndroidAlarmManager.periodic()

    final int alarmId = 0;
    await AndroidAlarmManager.periodic(const Duration(minutes: 1), 
        alarmId, 
        () {
          // Do something
        });