HXSP1947
HXSP1947

Reputation: 1351

Detect if user starts an application, android

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)?

Upvotes: 2

Views: 224

Answers (1)

Oleh Toder
Oleh Toder

Reputation: 422

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);

Upvotes: 2

Related Questions