android 如何定义全局变量

android 如何定义全局变量,第1张

找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。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()方法获取这个实例,进而获取其中的状态(变量)。

new 一个class: public class saveName {  }

在class加全局变量:private String myName

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

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

可以将变量存放在Application中,Context,中文直译为“上下文”,SDK中对其说明如下:

Interface to global information about an application environment. This is an abstract class whose implementation

is provided by the Android system. It allows access to application-specific resources and classes, as well as up-calls

for application-level operations such as launching activities, broadcasting and receiving intents, etc。

从上可知一下三点即:

1、它描述的是一个应用程序环境的信息,即上下文。

2、该类是一个抽象(abstract class)类,Android提供了该抽象类的具体实现类(后面我们会讲到是ContextIml类)。

3、通过它我们可以获取应用程序的资源和类,也包括一些应用级别 *** 作,例如:启动一个Activity,发送广播,接受Intent信息等。

以下为使用Application存储全局变量的示例代码:

1.继承Application,并在Application里声明全局变量。

public class MyApplication extends Application {

private User user

public User getUser() {

return user

}

public void setUser(User user) {

this.user = user

}

}

2.在AndroidManifest.xml的application节点中声明这个Application。

<application android:name="com.xxx.xxx.MyApplication">

3.在Activity中获取Application对象,并存取全局变量。

User user = new User()

user.setUserName("example")

MyrApplication app= (MyApplication ) getApplicationContext()

app.setUser(user)//将变量存到application

User tmp = app.getUser()//从application中读取全局变量。


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

原文地址: http://outofmemory.cn/tougao/7796780.html

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

发表评论

登录后才能评论

评论列表(0条)

保存