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?
1.2. To start an activity, use the method startActivity(intent) . This method is defined on the Context object which Activity extends. The following code demonstrates how you can start another activity via an intent. # Start the activity connect to the # specified class Intent i = new Intent(this, ActivityTwo.
The startActivity() method starts an instance of the DisplayMessageActivity that's specified by the Intent . Next, you need to create that class.
The static method is similar to instance or class method of a class but with the difference that the static method can be called through the name of class without creating any instance of that class. A static method is also called class method as it is related with a class and not with individual instance of the class.
Yes it is. If your requirement are like that then there is no harm in doing that.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With