Android Studio:如何利用Application操作全局变量

ops/2025/2/11 23:19:50/

目录

一、全局变量是什么 

二、如何把输入的信息存储到全局变量

Application%E7%B1%BB-toc" name="tableOfContents" style="margin-left:40px">2.1 MainApplication

 2.2 XML文件

 三、全局变量读取

四、修改manifest

​编辑 

五、效果展示


 

一、全局变量是什么 

        全局变量是指在程序的整个生命周期内都可访问的变量,它的作用范围不限于某个函数、方法或类,而是可以被多个代码模块共享。

        学习过java的可能会对此有些陌生,java中并没有全局变量的概念,但是在学习servlet的时候,必然接触过请求域和应用域,所谓的应用域对象servletContext,也就是servlet上下文对象,在这个对象中绑定的数据可以被所有用户所共享。比如setAttribute方法可以向域中绑定数据,getAttribute和removeAttribute分别可以从域中获取、移除数据。

        类比来看,Application Scope(应用域) 很像 Java 的全局变量,因为它在整个应用程序的生命周期内都是可用的,适用于存储全局数据。

        另外可以用单例模式来存储“全局变量”:

public class GlobalManager {private static GlobalManager instance = new GlobalManager();private String data;private GlobalManager() {}  // 私有构造方法,防止外部实例化public static GlobalManager getInstance() {return instance;}public String getData() {return data;}public void setData(String data) {this.data = data;}
}//设置全局变量
GlobalManager.getInstance().setData("Hello");

这样读取的时候,就会有固定的输出内容:

System.out.println(GlobalManager.getInstance().getData()); // 输出: Hello

在AS中Application的生命周期覆盖了全过程,不像Activity活动页面,一旦页面关闭生命周期就进入destroy,利用全生命特性,可以用来存储全局变量

二、如何把输入的信息存储到全局变量

先看第一段代码,其作用就是把用户的注册信息保存到全局变量hashmap中。

public class AppWriteActivity extends AppCompatActivity implements View.OnClickListener, CompoundButton.OnCheckedChangeListener {private EditText et_name; // 声明一个编辑框对象private EditText et_age; // 声明一个编辑框对象private EditText et_height; // 声明一个编辑框对象private EditText et_weight; // 声明一个编辑框对象private boolean isMarried = false;private String[] typeArray = {"未婚", "已婚"};@Overrideprotected 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);}@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {isMarried = isChecked;}@Overridepublic 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;}// 获取当前应用的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, "数据已写入全局内存");}if (v.getId() == R.id.btn_intent){// 创建Intent对象,启动 AppReadActivityIntent intent = new Intent(AppWriteActivity.this, AppReadActivity.class);// 启动目标ActivitystartActivity(intent);}}}

Application%E7%B1%BB" name="2.1%C2%A0MainApplication%E7%B1%BB">2.1 MainApplication

其中,我自定义了一个MainApplication类,具体代码如下:

这个自定义 Application 类的作用

  1. 存储全局数据

    • 定义了 infoMap 变量,用于存储一些全局信息,比如用户输入的数据。
    • 由于 Application 的生命周期与应用相同(应用启动 -> 关闭),infoMap 里的数据在应用运行期间都是有效的。
  2. 提供 getInstance() 方法,作为单例使用


public class MainApplication extends Application {private static MainApplication mApp;public HashMap<String,String> infoMap =new HashMap<String,String>();public static MainApplication getInstance(){return mApp;}@Overridepublic 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" ><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="40dp" ><TextViewandroid: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" /><EditTextandroid: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><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="40dp" ><TextViewandroid: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" /><EditTextandroid: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><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="40dp" ><TextViewandroid: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" /><EditTextandroid: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><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="40dp" ><TextViewandroid: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" /><EditTextandroid: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><RelativeLayoutandroid:layout_width="match_parent"android:layout_height="40dp" ><CheckBoxandroid: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><Buttonandroid:id="@+id/btn_save"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="保存到全局内存"android:textColor="@color/black"android:textSize="17sp" /><Buttonandroid:id="@+id/btn_intent"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="跳转到读取页面"/></LinearLayout>

 三、全局变量读取

这里的代码是从全局变量infoMap中读取用户的注册信息

public class AppReadActivity extends AppCompatActivity {private TextView tv_app; // 声明一个文本视图对象@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_app_read);tv_app = findViewById(R.id.tv_app);readAppMemory(); // 读取全局内存中保存的变量信息}// 读取全局内存中保存的变量信息private void readAppMemory() {String desc = "全局内存中保存的信息如下:";// 获取当前应用的Application实例MainApplication app = MainApplication.getInstance();// 获取Application实例中保存的映射全局变量Map<String, String> mapParam = app.infoMap;// 遍历映射全局变量内部的键值对信息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 = "全局内存中保存的信息为空";}tv_app.setText(desc);}}

四、修改manifest

 

五、效果展示

可以看到全局变量的信息已经被页面2所获取。


http://www.ppmy.cn/ops/157639.html

相关文章

速度超越DeepSeek!Le Chat 1100tok/s闪电回答,ChatGPT 4o和DeepSeek R1被秒杀?

2023年&#xff0c;当全球科技界还在ChatGPT引发的AI狂潮中沉浮时&#xff0c;一场来自欧洲的"静默革命"正悄然改变游戏规则。法国人工智能公司Mistral AI推出的聊天机器人Le Chat以"比ChatGPT快10倍"的惊人宣言震动业界&#xff0c;其背后承载的不仅是技术…

【实战篇】巧用 DeepSeek,让 Excel 数据处理更高效

一、为何选择用 DeepSeek 处理 Excel 在日常工作与生活里,Excel 是我们频繁使用的工具。不管是统计公司销售数据、分析学生成绩,还是梳理个人财务状况,Excel 凭借其强大的功能,如数据排序、筛选和简单公式计算,为我们提供了诸多便利。但当面对复杂的数据处理任务,比如从…

关于 IoT DC3 中设备(Device)的理解

在物联网系统中&#xff0c;设备&#xff08;Device&#xff09;是一个非常宽泛的概念&#xff0c;它可以指代任何能够接入系统并进行数据交互的实体。包括但不限于手机、电脑、服务器、网关、硬件设备甚至是某些软件程序等所有能接入到该平台的媒介。 内容 定义 目的 示例 …

LS-SDMTSP:粒子群优化算法(PSO)求解大规模单仓库多旅行商问题(LS-SDMTSP),MATLAB代码

一、问题定义 大规模单仓库多旅行商问题&#xff08;Large-Scale Single-Depot Multi-Traveling Salesman Problem&#xff0c;简称 LS-SDMTSP&#xff09;是组合优化领域中极具挑战性的经典问题。假设存在一个单一仓库&#xff0c;它既是所有旅行商的出发地&#xff0c;也是最…

LINUX——内核

引言 Linux 内核&#xff08;Kernel&#xff09;是操作系统的核心&#xff0c;负责管理计算机的硬件资源并为用户空间程序提供基础服务。它是 Linux 生态的“心脏”&#xff0c;驱动着从嵌入式设备到超级计算机的各类系统。理解 Linux 内核的设计原理和核心机制&#xff0c;是…

网络安全 纵向是什么意思 网络安全维度

信息安全工程师-网络信息安全概述 网络信息安全相关概念 网络信息安全的发展历经了通信保密、计算机安全、信息保障、可信计算等阶段。狭义上的网络信息安全特指网络信息系统的各组成要素符合安全属性的要求&#xff0c;即机密性、完整性、可用性、抗抵赖性、可控性。广义上的…

VSCode使用总结

1、VSCode左边资源窗口字体大小设置 方法一&#xff08;使用&#xff0c;已成功&#xff09; 进入安装目录Microsoft VS Code\resources\app\out\vs\workbench(如果是下载的压缩包&#xff0c;解压后resources\app\out\vs\workbench) 打开文件 workbench.desktop.main.css 搜…

Java 大视界 -- Java 大数据在智能家居中的应用与场景构建(79)

&#x1f496;亲爱的朋友们&#xff0c;热烈欢迎来到 青云交的博客&#xff01;能与诸位在此相逢&#xff0c;我倍感荣幸。在这飞速更迭的时代&#xff0c;我们都渴望一方心灵净土&#xff0c;而 我的博客 正是这样温暖的所在。这里为你呈上趣味与实用兼具的知识&#xff0c;也…