編輯:關於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):
本來不想寫這些基礎中的基礎,但是想想這些內容雖然用不到,但需要做這樣的了解和學習,也是概念性的居多,理解至上。不過還是不多說,就講兩個部分吧。一。系統架構這次的沒有Xm
昨天在用360掃描應用漏洞時,掃描結果,出來一個android:exported屬性,其實之前根本不知道這個屬性,更不知道這個屬性用來干嘛
在《Android Handler之消息循環的深入解析》中談到了Handler是用於操作線程內部的消息隊列,所以Handler可以用來線程間通信ITC,這種方式更加安全和
ActiveAndroid和OrmLite都是ORM架構的數據庫,之前使用的是OrmLite,今天研究了一番ActiveAndroid,發現兩者各有千秋,在代碼上,Act