Opinion Required: Should I use context or activity to start a service from a fragment?

from the CommonsWare Community archives

At 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:-

  1. context?.startService(Intent(context, SomeService::class.java))
  2. 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?


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.