Ajay Chauhan
Ajay Chauhan

Reputation: 1551

Is it a good practice to start activity using static method from another activity?

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?

Upvotes: 3

Views: 281

Answers (1)

jeprubio
jeprubio

Reputation: 18002

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.

Upvotes: 2

Related Questions