Save global variables in Android

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.