2

I have a service that I want to behave differently depending on what activity is currently active.

Is there any way of identifying what activity is showing on a device?

If so and If I own the current activity: Is there any way for my service to interact with the activity? What I want is to send a signal telling it to redraw a map.

Einar Sundgren
  • 4,325
  • 9
  • 40
  • 59
  • Questions should be presented with more detail , preferably some code, that shows that "I did XYZ and it failed, this is my error" or "here's where I am after I tried XYZ " ,etc. As much as we'd like to help, we won't really even be able to starting from general situation – Caffeinated Jul 13 '13 at 16:43
  • 1
    possible duplicate of [How to get current foreground activity context in android?](http://stackoverflow.com/questions/11411395/how-to-get-current-foreground-activity-context-in-android) – CodingIntrigue Jul 13 '13 at 16:44
  • @Blade0rz I don´t think it is aduplicate since that question wants to just show an alert. I want the service to interact with the activity in a slightly deeper way. – Einar Sundgren Jul 13 '13 at 18:16

2 Answers2

1

[EDITED]

please ignore what I said earlier - there is much simpler way:

1. create a new Java class in your package Info.java

package com.your.package.name;
import android.app.Activity;

public class Info {
static Class<? extends Activity> active = null;
}


2. add this line to onResume() methods of every Activity you have:

Info.active = this.getClass();


3. add these lines to onStop() methods of every Activity you have:

if(Info.active == this.getClass())
   Info.active = null;


4. now for your service:

if(Info.Active != null){
if (Info.active == MainActivity.class){
  // code that runs when MainActivity is active HERE

} else if (Info.active == SecondActivity.class){
  // code that runs when SecondActivity is active HERE

}
}
Vlad K.
  • 320
  • 3
  • 19
  • That is a smart way of fixing the problem. I was hoping there was an answer built in the Android OS that I had missed, something like getCurrentActivity(). But lacking that this will solve my problems sufficiently. – Einar Sundgren Jul 13 '13 at 22:06
  • I was looking for that built-in method also, and didn't find it. After some thought I think the API is *intentionally* designed that way - exposing such a method would make it easy to write applications with leaking memory. You forget to assign `null` to your Activity reference when you no longer need it and then the whole Activity object (wchich can be quite heavy) can't be GC'd (ouch!). – Vlad K. Jul 14 '13 at 07:40
1

you can save and update a tag say "CURRENT_ACTIVITY" with your activity name in sharedpreferences on oncreate() of each activity and fetch this tag value from your service when you need. this way you can get which activity is currently showing on device and you can do whatever you want to so or show there.

Hope this help you.

user2376920
  • 242
  • 1
  • 7
  • 19