Shark107 Shark107 - 1 year ago 57
Android Question

What's the best way to create items programmatically inside a Service?

So, I have to create few items, like Buttons and TextViews, from a service.

Since I need to pass along a Context when I create a new one, and since my service doesn't have one, I thought about doing it like this

Button button = new Button(getApplicationContext());

It works, but is it the best solution? I read a lot about how you have to be extra careful when using application context, so I'm not sure if it's the proper way to achieve what I need

Thanks in advance

Answer Source

I never used Service instances for that so, this is new for me. However, I stumbled upon this question about overlay service which gives quite cool solutions. As per your question I guess the following should work within the scope of your Service and is safer:

Button myButton = new Button(this);