1

The foreground service use a class with a timer to do a periodic work. I would like to pass this timer as parameter in the constructor, to can use dependency injection, or at least, pass the isntance of this class as parameter.

Until know, the way that I see how to create the foreground service is this:

Android.Content.Intent intent = new Android.Content.Intent(Android.App.Application.Context,typeof(MyForegroundService));
Android.App.Application.Context.StartForegroundService(intent);

The problem is that how I am passing the type to create the intent, I can't set the parameters.

I don't know if it is possible to create a foreground passing parameters to the constructor or not.

If not, another solution it could be to add the logic of the class with the timer directly in the foreground, but I think it is better to separate the logic of the timer from the foreground, and leave the foreground only for notifications.

So in sumary, I would like to know if it is possible to create the foreground with parameters and if it is possible, how.

Thanks.

Álvaro García
  • 18,114
  • 30
  • 102
  • 193

1 Answers1

0

is it possible to create a Foreground service in Android using a constructor with parameters?

No, it is impossible. According to this case about How to instantiate android service with a constructor, the service's instance is created by the android system with the no parameter constructor.

So you should use the intent to pass data to the foreground service and deal with the data in the OnStartCommand of the foreground service. And if the data is an model class, you can refer to this case which is about passing Data Model to Foreground Service.

But the Time class is not Serializable. So you can pass the value of the timer class's properties and create a new timer in the foreground service to copy these values.

Liyun Zhang - MSFT
  • 8,271
  • 1
  • 2
  • 14