2

Thanks in advance for the help.

I have an app that can be started by either the user physically starting the app (like you would any normal app) or by a repeating service. Depending on what starts the app (the user or the service) I want to preform different initialization actions. How might I be able to detect if an user starts the app without doing anything custom (I imagine that there has to be some kind of built in setting in android for me to determine this)?

HXSP1947
  • 1,311
  • 1
  • 16
  • 39

1 Answers1

2

If service, that starts your Activity, is yours service, you can put some custom information (using Intent#putExtra for example) in Intent you use to start Activity from Service.
In Activity you can use Activity#getIntent(), that returns the intent that started this activity.
If you started Activity from Service, that Intent will be the one you passed in Service#startActivity, and will have your custom information. Otherwise, that was not your Service, that started your Activity.

That could look somehow like that, for example:

//in Activity
public static final String EXTRA_STARTED_FROM_MY_SERVICE = "com.example.extra_started_from_sevice";

private boolean wasActivityStartedFromService() {
    Intent startingIntent = getIntent();
    //assuming you will use Intent#putExtra in your service when starting activity
    return startingIntent.getBooleanExtra(EXTRA_STARTED_FROM_MY_SERVICE, false);
}

//...

//in Service

    //...    
    Intent startingIntent = new Intent(this, MainActivity.class);
    startingIntent.putExtra(MainActivity.EXTRA_STARTED_FROM_MY_SERVICE, true);
    startActivity(startingIntent);
Kane O'Riley
  • 2,482
  • 2
  • 18
  • 27
Oleh Toder
  • 422
  • 3
  • 9
  • That was what I was thinking of doing, but I'd imagine that Android has some built in api to allow this to be determined without explicitly programming for it. Could be wrong though. – HXSP1947 Sep 10 '15 at 05:40
  • The "programming" you mention is intent extras, which are exactly designed to allowed different initialisation states based on the caller. – Kane O'Riley Sep 10 '15 at 08:18
  • Fixed the coding sample to actually check the value of the extra, not just that it exists. Otherwise `putExtra(EXTRA_STARTED_FROM_MY_SERVICE, false)` would be interpreted as true. – Kane O'Riley Sep 10 '15 at 08:22