打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
android中使用Application实现全局变量
 
woa,找到一个和我有类似需求的问题,其下给出了不错的解决方案,也正是我之前想到的,这种方法貌似很方便。

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

给个例子:
Java代码
  1. class MyApp extends Application {   
  2.   
  3.   private String myState;   
  4.   
  5.   public String getState(){   
  6.     return myState;   
  7.   }   
  8.   public void setState(String s){   
  9.     myState = s;   
  10.   }   
  11. }   
  12.   
  13. class Blah extends Activity {   
  14.   
  15.   @Override  
  16.   public void onCreate(Bundle b){   
  17.     ...   
  18.     MyApp appState = ((MyApp)getApplicationContext());   
  19.     String state = appState.getState();   
  20.     ...   
  21.   }   
  22. }  


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的架构体系。
 
 
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Android全局变量的定义与使用
android不同activity之间共享数据解决方法
Android中Activity共享变量的另一方法:Application context
Android全局对象Application的使用,以及如何在任何地方得到Application全局对象
android getContext()、getApplicationContext()和this有什么区别
android不同Activity之间的数据共享
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服