0

I would like to automatically insert some crafted code to any possible parts of the target app code. This crafted code includes a "context.startService()" to contact with a remote service from another app. How can I automatically get this context instance so that I can call startService() from anywhere within the app code?

Thanks a lot in advance. Any inputs are highly appreciated.

user3361508
  • 815
  • 3
  • 10
  • 11
  • Your activity or service is a context. You need to pass it as a parameter to whatever other class wants to start the service. – Gabe Sechan Mar 29 '14 at 18:49
  • Thanks Gabe. But the problem is I want to do this automatically and the location to start service is unpredictable. It is unfeasible to add context parameter to the arguments of ALL functions calls within an app. – user3361508 Mar 29 '14 at 18:57
  • Add it to your constructor, save it in a variable, and use it when you need it. – Gabe Sechan Mar 29 '14 at 19:17
  • You still need to pass the context instance across several class constructors. For example Activity -> class A -> class B -> class C, to get the context of Activity in class C, I need to modify all constructors of classes A,B,C. Any easier ways? – user3361508 Mar 29 '14 at 19:45
  • Other than changing your structure to be more android friendly, no. In some cases I'd consider singleton or globals, but not for contexts- too easy to cause massive memory leaks. – Gabe Sechan Mar 29 '14 at 19:50

2 Answers2

1

If I understand correctly, you want to start a service from anywhere within your codebase without passing around context objects. The solution below is a way to do this but look at this post to get a better understanding of why this isn't always the best solution.

Create a class that extends from Application:

import android.app.Application;

public class MyApplication extends Application {

  private static Application sInstance;

  public MyApplication() {
      sInstance = this;
  }

  public static Application getInstance() {
      return sInstance;
  }
}

This will give you access to your application's context so you can start a service from anywhere.

Now in some part of your code:

void foo() {
    MyApplication.getInstance().startService(new Intent(MY_SERVICE));
}
Community
  • 1
  • 1
WindsurferOak
  • 4,861
  • 1
  • 31
  • 36
0

create a new method, that gets your context, and then calls your service with said context, then call that method instead.

shouldnt change your code much....

Technivorous
  • 1,682
  • 2
  • 16
  • 22
  • Thanks for your comments. How to get the context instance from a new method? Could you please provide any hints/code examples?? Thanks! – user3361508 Mar 29 '14 at 19:46