Opinion Required: Should I use context or activity to start a service from a fragment?
from the CommonsWare Community archivesAt August 4, 2021, 5:13pm, Andr0id asked:
Hi All,
A apologies for a very trivial question.
I want to understand what is difference between the following calls when invoked from a fragment:-
- context?.startService(Intent(context, SomeService::class.java))
- requireActivity().startService(Intent(requireActivity(), SomeService::class.java))
The most obvious difference that I can think about is that if the fragment is not attached to an activity when the Point 2 call is made, then the app would crash.
To avoid such crashes I can use the call mentioned in Point 1.
That being said, is there any reason then that justifies the starting of a service as described in point 2?
Thanks
At August 4, 2021, 6:22pm, mmurphy replied:
If the fragment is not attached to an activity, the second would crash and the first would just not do anything (as context
probably is null
).
Nothing comes to mind.
At August 4, 2021, 8:51pm, Andr0id replied:
Thanks @mmurphy for the quick response.