如何定义全局变量

kvguo 2009-12-27 02:02:06
找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。

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()方法获取这个实例,进而获取其中的状态(变量)。

给个例子:

class MyApp extends Application {  
  
  private String myState;  
  
  public String getState(){  
    return myState;  
  }  
  public void setState(String s){  
    myState = s;  
  }  
}  
  
class Blah extends Activity {  
  
  @Override  
  public void onCreate(Bundle b){  
    ...  
    MyApp appState = ((MyApp)getApplicationContext());  
    String state = appState.getState();  
    ...  
  }  



This has essentially the same effect as using a static variable orsingleton, but integrates quite well into the existing Androidframework. Note that this will not work across processes (should yourapp be one of the rare ones that has multiple processes).
--这个效果就是使用静态变量是一样的,但是其更符合android的架构体系。

原文链接:http://stackoverflow.com/questions/708012/android-how-to-declare-global-variables
...全文
289 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
zxh_wolfe 2009-12-28
  • 打赏
  • 举报
回复
学习了,谢谢了
nj_dobetter 2009-12-27
  • 打赏
  • 举报
回复
顶。
Android在界面(View)方面增强了,数据(data)模型方面却弱化了,程序员控制内存数据不是很方便。期待后续版本加强。

80,350

社区成员

发帖
与我相关
我的任务
社区描述
移动平台 Android
androidandroid-studioandroidx 技术论坛(原bbs)
社区管理员
  • Android
  • yechaoa
  • 失落夏天
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧