3

I have seen this as a common practice to start activity using static method like this

class HomeScreenActivity{
  ....
  ....

  public static void startHomeActivity(Context context){
    Intent intent = new Intent(context,HomeScreenActivity.class);
    activity.startActivity();
  }
  ....
  ....

}


class LoginActivity{
  ....
  ....

  public void startActivity(){
    HomeScreenActivity.start(this);
  }    
  ....
  ....
}

Is this a good practice , can it create memory leaks, what are the problems it can create?

Bruno
  • 3,872
  • 4
  • 20
  • 37
Ajay Chauhan
  • 1,471
  • 4
  • 17
  • 37

1 Answers1

2

This is not a bad practice if this is what you are asking about.

What is a bad practice is, for example, having a context variable in a static field, this would create a leak. For example:

public class App extends Application {
    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }


    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this

    }
}

This one is a bad practice. And android studio should warn you (static context fields). That could be solved for example by using WeakReference.

But since the method of your example is static and the context is provided as an argument there is nothing wrong with it. If you want the method to be static it is a good practice to pass activity/context object as parameter.

If you suspect there is a leak you can override the onDestroy method of that context to find out when there is a leak (onDestroy won't be called as there is still a reference to it). Also, leaks can be found by uding the Memory Profiler and/or the LeakCanary lib.

jeprubio
  • 17,312
  • 5
  • 45
  • 56
  • If we are passing activity context ,and that activity gets destroyed ie loginactivity gets destroyed ,in that case it will create a leak ,right? – Ajay Chauhan Jan 16 '20 at 09:42
  • Only in the example I posted of bad practice, not in your code, because in the code you posted it's instantly used and not saved anywhere. The leak means it should be destroyed but it can not be destroyed because there is still a reference to it. – jeprubio Jan 16 '20 at 09:45
  • I've just added some info about how to find if there is a leak to the answer as this is also relevant to the question. – jeprubio Jan 16 '20 at 09:55