How to call an Activity's non-static method from inside a service onStart()?
Asked
Active
Viewed 1.2k times
6
-
check this link. http://stackoverflow.com/questions/2463175/how-to-have-android-service-communicate-with-activity – Raghu Nagaraju May 28 '12 at 11:47
2 Answers
5
How to call an Activity's non-static method from inside a service onStart()?
You can't.
However, there are many ways to have a service communicate with a running activity, and I outline some of them here: How can I update information in an Android Activity from a background Service

Community
- 1
- 1

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
I know this is an old post, but I have a question, I need to start activity within a service and get result of that activity. Is this possible? Any workaround? – Saber Amani Apr 06 '16 at 12:58
-
@saber: "Is this possible?" -- yes, though I recommend that you have good life insurance, if you will be popping up activities from the background that the user does not appreciate. Your service can call `startActivity()`. Your activity can then call `startService()` to send the results, or call `bindService()` and talk to your service via a binder, or use an event bus implementation (`LocalBroadcastManager`, greenrobot's EventBus, Square's Otto) to raise an event that the service picks up. – CommonsWare Apr 06 '16 at 13:04
-
Thanks for your reply, "though I recommend that you have good life insurance", :D ;) Since I don't have good one, I think have to hook up with `LocalBroadcastManager`. – Saber Amani Apr 06 '16 at 13:13
-2
This could help ..
In activity define
static MyActivity instance;
then set value MyActivity.OnCreate
instance = this;
In your service
MyActivity activity = MyActivity.instance;
if (activity != null) {
// we are calling here activity's method
}

Hussein mahyoub
- 335
- 4
- 6
-
2nooo, god. no, god, please, no! no no! Never do that. Never. Never retain a static instance of your `Activity`. Just don't. – Bartek Lipinski Jun 16 '19 at 10:04