Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting an Android Activity from a static method

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?

like image 930
Nathan Avatar asked Nov 18 '13 09:11

Nathan


People also ask

Which method is use for start activity in Android?

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.

Which method is use for start activity?

The startActivity() method starts an instance of the DisplayMessageActivity that's specified by the Intent . Next, you need to create that class.

What is static method in Android?

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.

Can an activity start itself Android?

Yes it is. If your requirement are like that then there is no harm in doing that.


1 Answers

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);
        }
like image 84
Biraj Zalavadia Avatar answered Sep 21 '22 17:09

Biraj Zalavadia