码迷,mamicode.com
首页 > 移动开发 > 详细

Android中的数据共享-application context

时间:2015-06-14 09:33:51      阅读:237      评论:0      收藏:0      [点我收藏+]

标签:android   共享   数据   

最近在做一个模拟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):

Android中的数据共享-application context

标签:android   共享   数据   

原文地址:http://blog.csdn.net/leoleohan/article/details/46486321

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!