How to get my activity context?

前端 未结 7 1711
小鲜肉
小鲜肉 2020-12-02 08:49

I don\'t really get the idea behind how this whole thing works really, so if I have some class A that need the context of a class B which extends <

相关标签:
7条回答
  • 2020-12-02 09:18

    You can use Application class(public class in android.application package),that is:

    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.

    To use this class do:

    public class App extends Application {
    
        private static Context mContext;
    
        public static Context getContext() {
            return mContext;
        }
    
        public static void setContext(Context mContext) {
            this.mContext = mContext;
        }
    
        ...
    
    }
    

    In your manifest:

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

    In Activity B:

    public class B extends Activity {
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.sampleactivitylayout);
    
            App.setContext(this);
                      ...
            }
    ...
    }
    

    In class A:

    Context c = App.getContext();
    

    Note:

    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.

    0 讨论(0)
提交回复
热议问题