猿问

在Android中获取“上下文”的静态方式?

在Android中获取“上下文”的静态方式?

有没有办法让电流Context静态方法中的实例?

我在寻找这种方法,因为我讨厌每次“上下文”实例发生变化时都保存它。


一只斗牛犬
浏览 602回答 3
3回答

萧十郎

这样做:在AndroidManifest文件中,声明以下内容。<application&nbsp;android:name="com.xyz.MyApplication"></application>然后在课堂上写:public&nbsp;class&nbsp;MyApplication&nbsp;extends&nbsp;Application&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;private&nbsp;static&nbsp;Context&nbsp;context; &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;void&nbsp;onCreate()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;super.onCreate(); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MyApplication.context&nbsp;=&nbsp;getApplicationContext(); &nbsp;&nbsp;&nbsp;&nbsp;} &nbsp;&nbsp;&nbsp;&nbsp;public&nbsp;static&nbsp;Context&nbsp;getAppContext()&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;return&nbsp;MyApplication.context; &nbsp;&nbsp;&nbsp;&nbsp;}}现在到处打电话MyApplication.getAppContext()静态获取应用程序上下文。
随时随地看视频慕课网APP

相关分类

Android
我要回答