0

I have some code in my Application class that needs to be run whenever the app is launched. However my app also has some service running and because of that, whenever the service is invoked the code in my Application class also runs.

I want to identify if my app process was started because user launched the app via his app drawer OR if the process was started because my app's service was invoked.

PS: I want some part of my Application class code to be run ONLY when the user opens his app by clicking on the icon and NOT when some service is started. Note that I don't want to make this distinction in my MainActivity, I want to identify this in my Application class itself

Any tips / resources would be very helpful here.

Thanks!

marco
  • 1
  • 1

1 Answers1

0

I'd question whether you actually need this functionality or if there's better ways to get what you want. This doesn't seem like something that would really be a benefit. It also seems like something that would give a lot of false positives if you really mean only when they click on the icon, because there's plenty of other ways an app can be launched (for an easy example, if the app is backgrounded it can be killed and relaunched via Recents, and you'd never know the difference).

But in any case, there's no way to know this in the Application. Instead, you 'd need to put this code in your launcher activity's onCreate, guarded by a static boolean flag to protect you from calling it twice like this:

public static boolean firstTime = true;
public void onCreate(Bundle savedInstanceState) {
    if(firstTime) {
        //do the thing
        firstTime = false;
    }
}
Gabe Sechan
  • 90,003
  • 9
  • 87
  • 127