0

Here i am trying to call method of main activity class from Audio Service class. but when i call the method like :-

new HomeActivity().previousChannel();

at that time activity class method get called but it also called oncreate() method automatically.

Please help me.

Saif
  • 723
  • 6
  • 21
shyam
  • 9
  • 3
  • Activity instance can't be created like this way `new HomeActivity()` There are lot of thread here on how to communicate between activity and Service – Abu Yousuf Feb 20 '18 at 10:25
  • sry but i didn't understand how to create activity instance in service class? – shyam Feb 20 '18 at 10:43
  • Check this http://www.vogella.com/tutorials/AndroidServices/article.html and this https://medium.com/@ankit_aggarwal/ways-to-communicate-between-activity-and-service-6a8f07275297 – Abu Yousuf Feb 20 '18 at 10:52
  • ***Never*** instantiate activities yourself – Tim Feb 20 '18 at 12:55

2 Answers2

1

I will prefer you to use EventBus for communication between Classes,Fragments,Services whatever it may be.It is very simple, most reliable and efficient.

It can be achieved in just 3 Steps:

1.Define Events.

public static class MessageEvent { /* Additional fields if needed */ }

2.Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

3.Post Events.

 EventBus.getDefault().post(new MessageEvent());

For more Details You can check here.

Hope it may help you.

Sachin Varma
  • 2,175
  • 4
  • 28
  • 39
0
  1. you can use an interface with name MyCallBack that will be implemented by your activity with any method like do Something();
  2. your activity will implement method of interface.
  3. From your service class you need to call method of interface from variable of that interface type.
  4. For that In your service class take a variable of type Interface like serviceCallBack and pass context of activity class in that variable.
  5. from that variable you can call method of interface that will automatically take you to activity class and you can call your activity methods like update any UI component