Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> Android中的數據共享-application context

Android中的數據共享-application context

編輯:關於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中配置這個類


        
...

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. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved