Android应用如何设计全局变量存储

Android应用如何设计全局变量存储,第1张

new 一个class: public class saveName {  }

在class加全局变量:private String myName

在class加方法设置变量:public void setMyName(String name){ myName = name}

在class加方法取得变量:public String getMyName(){ return myName;}

Android提供了一个类似于ServletContext的全局变量,叫Application。可以利用它存储一些全局变量!

示例:

import java.util.Collections

import java.util.HashMap

import java.util.Map

import android.app.Application

public class MyApplication extends Application {

private Map<String, Object>mData

public Map<String, Object>getmData() {

return mData

}

@Override

public void onCreate() {

super.onCreate()

mData = new HashMap<String, Object>()

//synchronized the map

mData = Collections.synchronizedMap(mData)

// then restore your map

}

public void onTerminate() {

super.onTerminate()

//save data of the map

}

}

然后在AndroidManifest里面配置<application>节点的属性

<application android:name=".MyApplication">

找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。The more general problem you are encountering is how to save stateacross several Activities and all parts of your application. A staticvariable (for instance, a singleton) is a common Java way of achievingthis. I have found however, that a more elegant way in Android is toassociate your state with the Application context.--如想在整个应用中使用,在java中一般是使用静态变量,而在android中有个更优雅的方式是使用Application context。As you know, each Activity is also a Context, which is informationabout its execution environment in the broadest sense. Your applicationalso has a context, and Android guarantees that it will exist as asingle instance across your application.--每个Activity 都是Context,其包含了其运行时的一些状态,android保证了其是single instance的。The way to do this is to create your own subclass of android.app.Application,and then specify that class in the application tag in your manifest.Now Android will automatically create an instance of that class andmake it available for your entire application. You can access it fromany context using the Context.getApplicationContext() method (Activityalso provides a method getApplication() which has the exact sameeffect):--方法是创建一个属于你自己的android.app.Application的子类,然后在manifest中申明一下这个类,这是 android就为此建立一个全局可用的实例,你可以在其他任何地方使用Context.getApplicationContext()方法获取这个实例,进而获取其中的状态(变量)。


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/bake/11732160.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-18
下一篇 2023-05-18

发表评论

登录后才能评论

评论列表(0条)

保存