1

I'd like to get a running activity of my application and call one of its method (I'm inside of a service). I have found that I need something like this, but i can't resolve my problem. Is it possible?

ActivityManager am = (ActivityManager) context.getSystemService(context.ACTIVITY_SERVICE);
List<RunningAppProcessInfo> procInfos = am.getRunningAppProcesses();
for (int j = 0; j < procInfos.size(); j++) {
    if (procInfos.get(j).processName.equals("com.android.pm")) {
        ...
    }
}
anthonymonori
  • 1,754
  • 14
  • 36
As As
  • 2,049
  • 4
  • 17
  • 33
  • 1
    you can't communicate with Activity like this. if you need a communication between Service and Activity, bind that Service to the Activity... – Gopal Gopi Nov 08 '13 at 11:58
  • The problem is that the service is not called from the activity that i want to close. I have activity A that calls Activity B that calls service S, and i want S to call a method of A. – As As Nov 08 '13 at 12:06
  • means do you want to finish Activbity A from Service S? – Gopal Gopi Nov 08 '13 at 12:09
  • I want to call a method and then finish it – As As Nov 08 '13 at 12:10

1 Answers1

0

Based on your comment:

The problem is that the service is not called from the activity that i want to close. I have activity A that calls Activity B that calls service S, and i want S to close A.

this is the wrong approach. The better thing to do would be to have Activity A register a broadcast receiver that listens for a particular Intent. When the service wants A to finish, it can broadcast a specific Intent. In this way, your service is communicating implicitly with the activity without having to have a reference to it, or know if it is running.

David Wasser
  • 93,459
  • 16
  • 209
  • 274
  • Do you have a link, an example or something else? I understand what you are saying, but i'm new to android. – As As Nov 08 '13 at 12:13
  • Here are a couple of tutorials for using broadcast receivers: http://www.grokkingandroid.com/android-tutorial-broadcastreceiver/ http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html – David Wasser Nov 08 '13 at 13:41
  • You don't need to declare the receiver in the manifest. In your activity,probably at the end of `onCreate()`, create an instance of `BroadcastReceiver` and implement the `onReceive()` method to call your activity method and then call `finish()` on the activity. You then need to "register" the receiver so that it gets triggered using a specific intent filter. The intent filter only needs to contain a specific ACTION, that you define (this is exactly the ACTION that your service will put in the broadcast intent that it sends). In your service, call `sendBroadcast()` to send it. – David Wasser Nov 08 '13 at 13:47
  • and don't forget to unregister the receiver in `onDestroy()` of your activity. – David Wasser Nov 08 '13 at 13:48