安卓:坚持跨越活动对象对象

2023-09-07 09:10:56 作者:生来不讨喜

我已经得到了我使用与各种事物进行互动的对象。对象本身在我的第一个活动是初始化,所有的后续活动中使用。什么是使其公的所有活动的最佳方式?

I've got an object that I use to interact with various things. The object itself is initialized in my first activity and used in all subsequent activities. What's the best way to make it "public" to all activities?

推荐答案

创建扩展应用程序的类并保持实例那里。

Create a class that extends Application and hold the instance there.

class MyApp extends Application{
    private Object obj;
    public Object getObject(){
         return obj;
    }
}

然后在你的活动

MyApp ma = (MyApp)getApplicationContext();
Object o = ma.getObject();

您可以阅读更多关于Android开发者网站上的应用程序类:http://developer.android.com/reference/android/app/Application.html

You can read more about the Application class on the android developer website: http://developer.android.com/reference/android/app/Application.html