最近在做一个模拟Android京东商城的练手项目,其中一个需求是:当用户登录后,如何让用户的id,name,phone,address等信息实现整个应用的数据共享呢?
在两个activity之间传递数据,自然联想到比较常用方法,即通过intent意图绑定一个bundle对象进行传递。然而在多个松耦合的Activity中如何更好的实现数据的传递呢?在各大IT论坛博客中终于学习到了一种更好的解决办法:Application Context。

1.创建一个android.app.Application的子类,生成Setter&Getter

package com.example.jds.util;import android.app.Application;public class UserApplication extends Application {    private int id;    private String name;    private String pass;    public int getId() {        return id;    }    public void setId(int id) {        this.id = id;    }    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public String getPass() {        return pass;    }    public void setPass(String pass) {        this.pass = pass;    }}

2.在AndroidManifest.xml中配置这个类

<application        android:name="com.example.jds.util.UserApplication"        android:icon="@drawable/appimage"        android:label="@string/app_name"        android:theme="@style/jdsTheme" >        <activity        ...        </activity>...</application>

3.如何使用?

// UserApplication 是Android建立的一个全局可用的实例//在任意一个activity中使用该方法可以为变量赋值int id = 1;((UserApplication) getApplication()).setId(id);//在任意一个activity中使用该方法可以获取变量的值String name = ((UserApplication) getApplication()).getName();

附参考英文原文:
The more general problem you are encountering is how to save state across several Activities and all parts of your application. A static variable (for instance, a singleton) is a common Java way of achieving this. I have found however, that a more elegant way in Android is to associate your state with the Application context.
As you know, each Activity is also a Context, which is information about its execution environment in the broadest sense. Your application also has a context, and Android guarantees that it will exist as a single instance across your application.
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 and make it available for your entire application. You can access it from any context using the Context.getApplicationContext() method (Activity also provides a method getApplication() which has the exact same effect):

更多相关文章

  1. 使用webView访问https的url-处理SslError解决android2.2版本之前
  2. Android客户端与服务器数据交互流程
  3. android中关于Cursor类的介绍
  4. Android(安卓)应用自动启动的两种方法(开机自启动 与 另一个应用
  5. Android(安卓)开发技术选型(博客,新闻,阅读类)
  6. PC客户端与Android服务端的Socket同步通信(USB)(转载)
  7. View的工作原理——初识View和DecorView
  8. 远程调试Android/IOS设备/微信网页方法汇总
  9. Android总结之链式调用(方法链)

随机推荐

  1. Android(安卓)studio使用lambda表达式
  2. 学习:Android框架
  3. android图形系统详解
  4. Android挂断电话流程
  5. 跟雷军一起干,小米 Android 开发工程师内
  6. EditText设置不自动获取焦点,点击后才获取
  7. android拍照造成内存泄露问题
  8. android ProgressBar 的使用
  9. Android 原生加载框
  10. Activity去掉标题栏失败(使用AppCompat)