如何从任何地方的语境? [英] How to get the Context from anywhere?
本文介绍了如何从任何地方的语境?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Android中,有没有什么办法让一个静态的方式应用的背景下?例如,从后台线程取回它。
In Android, is there any way to get the context of the application of a static way? For example to retrieving it from a background thread.
感谢
推荐答案
最简单的(正确)的方法是:
The easiest (and correct) way is:
定义一个新类
public class MyApp extends Application {
private static MyApp instance;
public static MyApp getInstance() {
return instance;
}
public static Context getContext(){
return instance;
// or return instance.getApplicationContext();
}
@Override
public void onCreate() {
instance = this;
super.onCreate();
}
}
然后在你的清单,你需要把这个类添加到名称字段的应用程序选项卡。或编辑XML,并把
Then in your manifest you need to add this class to the "Name" field at the "Application" tab. Or edit the xml and put
<application
android:name="com.example.app.MyApp"
android:icon="@drawable/icon"
android:label="@string/app_name"
.......
<activity
......
,然后从任何地方,你可以叫
and then from anywhere you can call
MyApp.getContext();
希望它可以帮助
Hope it helps
这篇关于如何从任何地方的语境?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文