silence鼬、2015年6月28日在学习Android的时候一直未context的问题觉得头疼,因为想做一些工具类,但是又不是四大组件,总要来回传递context,觉得很麻烦,就想全局获取,最后看到application是全局单例的,所以改造一下。 1. 首先需要重写Application,主要重写里面的onCreate方法,就是创建的时候,初始化一个Map,这样就可以插入任意值。然后在整个应用中的各个文件中就可以对该变量进行操作了。2. 在程序中有两种获得方式getInstance() 和 在四大组件中通过 getApplication() 分别获得app
PackageCom.xin.app;ImportJava.util.HashMap;ImportJava.util.Map;ImportAndroid.app.Application;ImportAndroid.util.Log;/** * * @author Silence Ferret * @url http://write.blog.csdn.net/mdeditor#!postId=46674445 * @tip
Welcome Reprint * * * Public class App extends application { Private StaticAPP instance;PrivateMap Innermap =NewHashMap ();@Override Public void onCreate() {Super. OnCreate (); Instance = This;//Note here, not a common single-case approach} Public StaticAppgetinstance() {LOG.V ("App","getinstance instance"+instance.tostring ());returnInstance } Public void AddParam(Object key,object value) {Innermap.put (key, value); } PublicObjectGetParam(Object key) {returnInnermap.get (key); }}
The above code adds an internal map, and the corresponding access method, which can be used globally using getapplication () and App.getinstance ().
Save global variables in Android