Android?Studio如何利用Application操作全局變量的代碼詳解
一、全局變量是什么
全局變量是指在程序的整個生命周期內(nèi)都可訪問的變量,它的作用范圍不限于某個函數(shù)、方法或類,而是可以被多個代碼模塊共享。
學(xué)習(xí)過java的可能會對此有些陌生,java中并沒有全局變量的概念,但是在學(xué)習(xí)servlet的時候,必然接觸過請求域和應(yīng)用域,所謂的應(yīng)用域?qū)ο髎ervletContext,也就是servlet上下文對象,在這個對象中綁定的數(shù)據(jù)可以被所有用戶所共享。比如setAttribute方法可以向域中綁定數(shù)據(jù),getAttribute和removeAttribute分別可以從域中獲取、移除數(shù)據(jù)。
類比來看,Application Scope(應(yīng)用域) 很像 Java 的全局變量,因為它在整個應(yīng)用程序的生命周期內(nèi)都是可用的,適用于存儲全局數(shù)據(jù)。
另外可以用單例模式來存儲“全局變量”:
public class GlobalManager {
private static GlobalManager instance = new GlobalManager();
private String data;
private GlobalManager() {} // 私有構(gòu)造方法,防止外部實例化
public static GlobalManager getInstance() {
return instance;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
}
//設(shè)置全局變量
GlobalManager.getInstance().setData("Hello");這樣讀取的時候,就會有固定的輸出內(nèi)容:
System.out.println(GlobalManager.getInstance().getData()); // 輸出: Hello
在AS中Application的生命周期覆蓋了全過程,不像Activity活動頁面,一旦頁面關(guān)閉生命周期就進入destroy,利用全生命特性,可以用來存儲全局變量。
二、如何把輸入的信息存儲到全局變量
先看第一段代碼,其作用就是把用戶的注冊信息保存到全局變量hashmap中。
public class AppWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {
private EditText et_name; // 聲明一個編輯框?qū)ο?
private EditText et_age; // 聲明一個編輯框?qū)ο?
private EditText et_height; // 聲明一個編輯框?qū)ο?
private EditText et_weight; // 聲明一個編輯框?qū)ο?
private boolean isMarried = false;
private String[] typeArray = {"未婚", "已婚"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_write);
et_name = findViewById(R.id.et_name);
et_age = findViewById(R.id.et_age);
et_height = findViewById(R.id.et_height);
et_weight = findViewById(R.id.et_weight);
CheckBox ck_married = findViewById(R.id.ck_married);
ck_married.setOnCheckedChangeListener(this);
findViewById(R.id.btn_save).setOnClickListener(this);
findViewById(R.id.btn_intent).setOnClickListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
isMarried = isChecked;
}
@Override
public void onClick(View v) {
if (v.getId() == R.id.btn_save) {
String name = et_name.getText().toString();
String age = et_age.getText().toString();
String height = et_height.getText().toString();
String weight = et_weight.getText().toString();
if (TextUtils.isEmpty(name)) {
ToastUtil.show(this, "請先填寫姓名");
return;
} else if (TextUtils.isEmpty(age)) {
ToastUtil.show(this, "請先填寫年齡");
return;
} else if (TextUtils.isEmpty(height)) {
ToastUtil.show(this, "請先填寫身高");
return;
} else if (TextUtils.isEmpty(weight)) {
ToastUtil.show(this, "請先填寫體重");
return;
}
// 獲取當前應(yīng)用的Application實例
MainApplication app = MainApplication.getInstance();
// 以下直接修改Application實例中保存的映射全局變量
app.infoMap.put("name", name);
app.infoMap.put("age", age);
app.infoMap.put("height", height);
app.infoMap.put("weight", weight);
app.infoMap.put("married", typeArray[!isMarried ? 0 : 1]);
app.infoMap.put("update_time", DateUtil.getNowDateTime("yyyy-MM-dd HH:mm:ss"));
ToastUtil.show(this, "數(shù)據(jù)已寫入全局內(nèi)存");
}
if (v.getId() == R.id.btn_intent){
// 創(chuàng)建Intent對象,啟動 AppReadActivity
Intent intent = new Intent(AppWriteActivity.this, AppReadActivity.class);
// 啟動目標Activity
startActivity(intent);
}
}
}2.1 MainApplication類
其中,我自定義了一個MainApplication類,具體代碼如下:
這個自定義 Application 類的作用
存儲全局數(shù)據(jù)
- 定義了
infoMap變量,用于存儲一些全局信息,比如用戶輸入的數(shù)據(jù)。 - 由于
Application的生命周期與應(yīng)用相同(應(yīng)用啟動 -> 關(guān)閉),infoMap里的數(shù)據(jù)在應(yīng)用運行期間都是有效的。
提供 getInstance() 方法,作為單例使用
MainApplication使用mApp作為靜態(tài)實例,并在onCreate()里初始化它,這樣,任何地方都可以通過MainApplication.getInstance()訪問Application,不用每次都getApplication()。
public class MainApplication extends Application {
private static MainApplication mApp;
public HashMap<String,String> infoMap =new HashMap<String,String>();
public static MainApplication getInstance(){
return mApp;
}
@Override
public void onCreate() {
super.onCreate();
mApp = this;
}
}
2.2 XML文件

信息收集的頁面示意圖,其具體代碼如下:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="姓名:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_name"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_name"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="請輸入姓名"
android:inputType="text"
android:maxLength="12"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_age"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="年齡:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_age"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_age"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="請輸入年齡"
android:inputType="number"
android:maxLength="2"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_height"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="身高:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_height"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_height"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="請輸入身高"
android:inputType="number"
android:maxLength="3"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<TextView
android:id="@+id/tv_weight"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:text="體重:"
android:textColor="@color/black"
android:textSize="17sp" />
<EditText
android:id="@+id/et_weight"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginBottom="3dp"
android:layout_marginTop="3dp"
android:layout_toRightOf="@+id/tv_weight"
android:background="@drawable/editext_selector"
android:gravity="left|center"
android:hint="請輸入體重"
android:inputType="numberDecimal"
android:maxLength="5"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="40dp" >
<CheckBox
android:id="@+id/ck_married"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:gravity="center"
android:checked="false"
android:text="已婚"
android:textColor="@color/black"
android:textSize="17sp" />
</RelativeLayout>
<Button
android:id="@+id/btn_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="保存到全局內(nèi)存"
android:textColor="@color/black"
android:textSize="17sp" />
<Button
android:id="@+id/btn_intent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="跳轉(zhuǎn)到讀取頁面"/>
</LinearLayout>三、全局變量讀取
這里的代碼是從全局變量infoMap中讀取用戶的注冊信息
public class AppReadActivity extends AppCompatActivity {
private TextView tv_app; // 聲明一個文本視圖對象
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_app_read);
tv_app = findViewById(R.id.tv_app);
readAppMemory(); // 讀取全局內(nèi)存中保存的變量信息
}
// 讀取全局內(nèi)存中保存的變量信息
private void readAppMemory() {
String desc = "全局內(nèi)存中保存的信息如下:";
// 獲取當前應(yīng)用的Application實例
MainApplication app = MainApplication.getInstance();
// 獲取Application實例中保存的映射全局變量
Map<String, String> mapParam = app.infoMap;
// 遍歷映射全局變量內(nèi)部的鍵值對信息
for (Map.Entry<String, String> item_map : mapParam.entrySet()) {
desc = String.format("%s\n %s的取值為%s",
desc, item_map.getKey(), item_map.getValue());
}
if (mapParam.size() <= 0) {
desc = "全局內(nèi)存中保存的信息為空";
}
tv_app.setText(desc);
}
}
四、修改manifest

五、效果展示

可以看到全局變量的信息已經(jīng)被頁面2所獲取。

以上就是Android Studio如何利用Application操作全局變量的代碼詳解的詳細內(nèi)容,更多關(guān)于Android Studio Application全局變量的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android Zxing生成二維碼經(jīng)典案例分享
這篇文章主要為大家分享了Android Zxing生成二維碼經(jīng)典案例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2016-11-11
Android自定義ViewGroup之第一次接觸ViewGroup
這篇文章主要為大家詳細介紹了Android自定義ViewGroup之第一次接觸ViewGroup,感興趣的小伙伴們可以參考一下2016-06-06
簡單掌握Android Widget桌面小部件的創(chuàng)建步驟
這篇文章主要介紹了簡單掌握Android Widget桌面小部件的創(chuàng)建步驟,Widget一般采用web前端技術(shù)進行開發(fā),需要的朋友可以參考下2016-03-03
android應(yīng)用實現(xiàn)開機自動啟動方法
這篇文章主要介紹了android應(yīng)用實現(xiàn)開機自動啟動方法,本文講解了原理和編碼實例,需要的朋友可以參考下2015-05-05
Windows下Flutter+Idea環(huán)境搭建及配置
這篇文章介紹了Windows下Flutter+Idea環(huán)境搭建及配置的方法,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-12-12
Android編程中沉浸式狀態(tài)欄的三種實現(xiàn)方式詳解
這篇文章主要介紹了Android編程中沉浸式狀態(tài)欄的三種實現(xiàn)方式,簡單描述了沉浸式狀態(tài)欄的概念、功能并結(jié)合實例形式詳細分析了Android實現(xiàn)沉浸式狀態(tài)欄的三種操作技巧與注意事項,需要的朋友可以參考下2018-02-02

