0

I start a background service from MainActivity and as well as from Fragment.

Will it create duplicate threads? So It will be 2 services running?

MainActivity

protected void onCreate(Bundle savedInstanceState) {
  //...
  context.startService(new Intent(context,gps_service.class));
//...

Fragment

public class FragmentThree extends Fragment {

//... Click method of the button calls
getActivity().startService(new Intent(getActivity(),gps_service.class));
PKlumpp
  • 4,913
  • 8
  • 36
  • 64
NoWar
  • 36,338
  • 80
  • 323
  • 498

3 Answers3

2

Will it create duplicate threads? So It will be 2 services running?

NO only one service will be launched and only one will running

AskNilesh
  • 67,701
  • 16
  • 123
  • 163
2

There will be only one service running. .

Will it create duplicate threads? So It will be 2 services running?

Each time you call startService() There can be two possibilities.

  1. If Service in not started previously then it will start as per its life cycle . onCreate -> onStartCammand and so on.

  2. If Service is previously started then only onStartCammand() will get called with desired intent which you have passed to it .

ADM
  • 20,406
  • 11
  • 52
  • 83
1

Only one instance is exist for each Service. If your service is already running then onStartCommand(Intent, int, int) will be called if you try to start again.

From Android Official site

Caution: A service runs in the main thread of its hosting process; the service does not create its own thread and does not run in a separate process unless you specify otherwise.

So by default Service use Main Thread and IntentService use a background thread. If you want to do some long running task then use IntentService or create a background Thread in Service.

For more check this

Abu Yousuf
  • 5,729
  • 3
  • 31
  • 50