Activity interceptor

Is there a way in android to intercept activity method calls (only standard ones, for example, onStart. OnCreate)? I have many functions that should be present in every action in my application, and (since it uses different types of actions (List, Preferences)), the only way to do this is to create my custom extensions for each activity class that sucks: (

PS I use roboguice, but since Dalvik does not support code generation at runtime, I think it helps a little.

PSS I thought about using AspectJ, but this is too much trouble, as it requires a lot of complications (ant build.xml and all this reluctance)

+4
source share
3 answers

You can delegate all repetitive work to another class that will be embedded in your other actions. Thus, you limit the repetitive work of creating this object and call its onCreate, onDestroy methods.

class MyActivityDelegate { MyActivityDelegate(Activity a) {} public void onCreate(Bundle savedInstanceState) {} public void onDestroy() {} } class MyActivity extends ListActivity { MyActivityDelegate commonStuff; public MyActivity() { commonStuff = MyActivityDelegate(this); } public onCreate(Bundle savedInstanceState) { commonStuff.onCreate(savedInstanceState); // ... } } 

This minimizes the hassle and factores all common methods and members of your business. Another way to do this is to subclass all XXXActivty API classes: (

+2
source

Roboguice 1.1.1 includes support for major events for components injected into the context. See http://code.google.com/p/roboguice/wiki/Events for more details.

Example:

 @ContextScoped public class MyObserver { void handleOnCreate(@Observes OnCreatedEvent e) { Log.i("MyTag", "onCreated"); } } public class MyActivity extends RoboActivity { @Inject MyObserver observer; // injecting the component here will cause auto-wiring of the handleOnCreate method in the component. protected void onCreate(Bundle state) { super.onCreate(state); /* observer.handleOnCreate() will be invoked here */ } } 
+5
source

Take a look at http://code.google.com/p/android-method-interceptor/ , it uses Java Proxies.

0
source

Source: https://habr.com/ru/post/1335950/


All Articles