6

How to call an Activity's non-static method from inside a service onStart()?

Bob
  • 22,810
  • 38
  • 143
  • 225
Mahmoud Abou-Eita
  • 933
  • 1
  • 8
  • 17

2 Answers2

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