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

给个例子:

Java代码
  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. }



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必须在manifest注册(<application android:name=".MyApp")

更多相关文章

  1. beforeTextChanged,TextChanged,afterTextChanged的使用Android
  2. Android使用GPS定位
  3. Android(安卓)Path的使用
  4. Android中HandlerThread的使用
  5. Android(安卓)8. Android(安卓)方法过时替换记录表
  6. android 模拟器上GPS的使用
  7. 箭头函数的基础使用
  8. NPM 和webpack 的基础使用
  9. Python list sort方法的具体使用

随机推荐

  1. Android中的ANR异常如何分析又该怎么去避
  2. Android设置TextView显示指定个数字符,超
  3. Android(安卓)Handler使用
  4. Android(安卓)动态库反汇编
  5. WebView高度自适应方案探究
  6. 【Android】实现全屏、无标题栏效果
  7. android eclipse 真机调试
  8. android 中管理短信
  9. android - 为响应度而设计 - 开发文档翻
  10. Android(安卓)Service生命周期及用法