Home » Android » Starting an Android Activity from a static method

Starting an Android Activity from a static method

Posted by: admin June 15, 2020 Leave a comment

Questions:

I want to start an activity from a static java method on an android device.
I do not have any context or anything passed as parameter to the static function.
For starting the activity I must call “startActivity” with the current running method as “this” pointer. So is there a way to get the current running activity?

How to&Answers:

Create a Class in your app extending class Application, define a static context and initialise this with your application context. You can expose a static method from this class for accessing defined static reference. Thats it.

class MyApp extends Application{

    private static Context mContext;

    public void onCreate(){
       mContext = this.getApplicationContext();
    }

    public static Context getAppContext(){
       return mContext;
    }
}

Now you can use this static method for accessing context anywhere in your app.

Answer:

You can access only static variables/objects inside static method.
So You need to Implement this way

public class MainActivity extends Activity {
    private static Context mContext;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mContext = this;

    }

    public static void goToLoginActivity() {
        Intent login = new Intent(mContext, LoginActivity.class);
        mContext.startActivity(login);
    }

}

NOTE : But this is not the proper way to do so, this may cause window leak issue.

Better approach is pass activity/context object as parameter like this.

public static void goToLoginActivity(Context mContext) {
            Intent login = new Intent(mContext, LoginActivity.class);
            mContext.startActivity(login);
        }