android – 如何获得我的活动上下文?

我真的不知道这个整个事情是如何工作的背后的想法,所以如果我有一个类A需要一个类B的上下文扩展Activity,我如何得到这个上下文?

我正在寻找一个更有效的方法,然后将上下文作为参数给A类构造函数,因为对于exsmple如果类A将有数百万的实例,那么我们将最终有数百万的冗余指针上下文,而我们应该能以某种方式只有一个地方和一个getter函数…

你可以使用Application类(public class在android.application包中),也就是:

Base class for those who need to maintain global application state.
You can provide your own implementation by specifying its name in your
AndroidManifest.xml’s tag, which will cause that class
to be instantiated for you when the process for your
application/package is created.

要使用这个类做:

public class App extends Application {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context mContext) {
        this.mContext = mContext;
    }

    ...

}

在您的清单中:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

在活动B:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampleactivitylayout);

        App.setContext(this);
                  ...
        }
...
}

在A类:

Context c = App.getContext();

注意:

There is normally no need to subclass Application. In most situation,
static singletons can provide the same functionality in a more modular
way. If your singleton needs a global context (for example to register
broadcast receivers), the function to retrieve it can be given a
Context which internally uses Context.getApplicationContext() when
first constructing the singleton.

http://stackoverflow.com/questions/12320857/how-to-get-my-activity-context

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:android – 如何获得我的活动上下文?