Stopping and starting a Service based on application state

后端 未结 8 1559
北海茫月
北海茫月 2021-01-05 16:45

I have a Service which tracks the location of the user. Currently, the Service boots when the application starts and stops when the application terminates. Unfortunately,

8条回答
  •  迷失自我
    2021-01-05 17:02

    Reading all the above answers I would suggest Simply add a boolean global flag for each activity & put it in your onResume & onPause & also while launching an Activity Something like this

    public void onPause()
    {
    super.onPause();
    activity1IsResumed = true;
    }
    

    &same for onResume

    & similarly when launching a new Activity

    startActivityForResult(myintent ,0);
    activity2IsResumed = true;
    activity1IsResumed = false;
    

    then in your Service simply check

    if(activity1IsResumed || activity2IsResumed || activity3IsResumed)
    {
    //your logic
    }
    else
    {
    //another logic
    //or dont run location tracker
    }
    

    & you are done!

提交回复
热议问题