从静态方法启动 Android Activity

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20044163/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:12:51  来源:igfitidea点击:

Starting an Android Activity from a static method

androidandroid-activity

提问by Nathan

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?

我想从 android 设备上的静态 java 方法开始一个活动。我没有任何上下文或任何作为参数传递给静态函数的内容。为了启动活动,我必须使用当前运行的方法作为“this”指针调用“startActivity”。那么有没有办法获取当前正在运行的活动呢?

回答by Biraj Zalavadia

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);
        }

回答by Techfist

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.

在您的应用程序中创建一个扩展类 Application 的类,定义一个静态上下文并使用您的应用程序上下文对其进行初始化。您可以公开此类中的静态方法以访问定义的静态引用。就是这样。

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.

现在,您可以使用此静态方法访问应用程序中任何位置的上下文。