سؤال

After reading the the Avoiding memory leaks article by @RomainGuy I realized that my current Android application is plagued with the mistake of passing the application's main activity around. So whenever I, can I simply replace that activity parameter with Activity.getApplicationContext().

But there are certain classes in my application that still need to run methods that can only be members of the applications main activity.

Thus I was thinking of possibly using the Command Pattern to workaround this limitation.

The problem is that, if we look at that example:

public class SomeCommandExecuableOnlyByActivity implements Command 
{
    public void execute(Object data) 
    {
        doIt( ((MyActivity)data).getWindow() );
    }    
}

I am running again into the dead end of needing the pass around the activity (this time disguised as Object data).

How do I get out of this "chicken & the egg" situation?

Is there a better way to approach this problem?

هل كانت مفيدة؟

المحلول

I think what you may be missing here is a proper separation of concerns. If you say you have to pass your main activity around to other activities in order to invoke some functionality on it, then it seems to me your app's architecture has some fundamental design flaws.

Whether or not to use the command pattern here I cannot tell, but what I'd generally do is identify those methods that require shared access, move them to a separate class and then either keep a separate instance of that class in all activities requiring this functionality, or if you need to share instance state, create it in the global application context and provide a global access path to it (not desirable, but without a DI framework like RoboGuice it's very difficult to implement DI on Android, since constructors are rendered void.)

In my opinion, in a well designed Android application, an Activity is free of business logic and only provides operations that change the state of the UI. The flow of the user interface or any other computations would be left to other classes. The Model-View-Presenter pattern helps tremendously here to keep your code structured by responsibility.

Without giving us more insight into what you're exactly trying to achieve, it's hard to give out specific advice though.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top