在Android中使用Intent在两个Activity间传递数据时,只能是基本类型数据,或者是序列化对象。Intent是一种基于消息的进程内和进程间通信模型,当我们需要在我们应用程序内部,多个Activity间进行复杂数据对象共享交互时,使用Intent就显得很不方便。此时,我们就需要一种数据共享的机制来实现。当然,直接使用java语言中的静态变量是可以的,但在Android中有更为优雅的实现方式。

【转自: http://www.javaeye.com/topic/552758】
【原文链接:http://stackoverflow.com/questions/708012/ android-how-to-declare-global-variables】

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

  1. classMyAppextendsApplication{
  2. privateStringmyState;
  3. publicStringgetState(){
  4. returnmyState;
  5. }
  6. publicvoidsetState(Strings){
  7. myState=s;
  8. }
  9. }
  10. classBlahextendsActivity{
  11. @Override
  12. publicvoidonCreate(Bundleb){
  13. ...
  14. MyAppappState=((MyApp)getApplicationContext());
  15. Stringstate=appState.getState();
  16. ...
  17. }
  18. }

更多相关文章

  1. Nginx系列教程(四)| 一文带你读懂Nginx的动静分离
  2. “罗永浩抖音首秀”销售数据的可视化大屏是怎么做出来的呢?
  3. Nginx系列教程(三)| 一文带你读懂Nginx的负载均衡
  4. 不吹不黑!GitHub 上帮助人们学习编码的 12 个资源,错过血亏...
  5. Android(安卓)SQLite教程:内部架构及SQLite使用办法
  6. Android在开发中的实用技巧之Parcelable的使用以及如何传递复杂
  7. android ListView分页加载
  8. [置顶] JuheNews For aNdroid (改进版)
  9. 条件数据库Android:sqllite的简单使用

随机推荐

  1. Android常用图片加载库介绍及对比
  2. Android(安卓)Studio 4.0版本创建Activit
  3. Android(安卓)SDK开发包国内下载地址
  4. Android(安卓)UI更新
  5. AndroidManifest 中original-package标签
  6. Android动态壁纸的制作教程
  7. Android数字签名
  8. Android面试题集锦之Service
  9. 如何画Q版角色?绘画q版动漫人物
  10. Ubuntu系统-FFmpeg安装及环境配置