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

目录

一、全局变量是什么

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

[2.1 MainApplication类](#2.1 MainApplication类)

[2.2 XML文件](#2.2 XML文件)

三、全局变量读取

四、修改manifest

​编辑

五、效果展示


一、全局变量是什么

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

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

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

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

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");

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

java 复制代码
System.out.println(GlobalManager.getInstance().getData()); // 输出: Hello

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

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

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

java 复制代码
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 = {"未婚", "已婚"};

    @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;
            }
            // 获取当前应用的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对象,启动 AppReadActivity
            Intent intent = new Intent(AppWriteActivity.this, AppReadActivity.class);

            // 启动目标Activity
            startActivity(intent);
        }
    }

}

2.1 MainApplication类

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

这个自定义 Application 类的作用

  1. 存储全局数据

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

    • MainApplication 使用 mApp 作为静态实例,并在 onCreate() 里初始化它,这样,任何地方都可以通过 MainApplication.getInstance() 访问 Application,不用每次都 getApplication()
java 复制代码
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文件

信息收集的页面示意图,其具体代码如下:

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="保存到全局内存"
        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="跳转到读取页面"/>

</LinearLayout>

三、全局变量读取

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

java 复制代码
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(); // 读取全局内存中保存的变量信息
	}

	// 读取全局内存中保存的变量信息
	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所获取。

相关推荐
安东尼肉店3 小时前
Android compose屏幕适配终极解决方案
android
2501_916007473 小时前
HTTPS 抓包乱码怎么办?原因剖析、排查步骤与实战工具对策(HTTPS 抓包乱码、gzipbrotli、TLS 解密、iOS 抓包)
android·ios·小程序·https·uni-app·iphone·webview
feiyangqingyun4 小时前
基于Qt和FFmpeg的安卓监控模拟器/手机摄像头模拟成onvif和28181设备
android·qt·ffmpeg
用户2018792831679 小时前
ANR之RenderThread不可中断睡眠state=D
android
煤球王子9 小时前
简单学:Android14中的Bluetooth—PBAP下载
android
小趴菜82279 小时前
安卓接入Max广告源
android
齊家治國平天下9 小时前
Android 14 系统 ANR (Application Not Responding) 深度分析与解决指南
android·anr
ZHANG13HAO9 小时前
Android 13.0 Framework 实现应用通知使用权默认开启的技术指南
android
【ql君】qlexcel9 小时前
Android 安卓RIL介绍
android·安卓·ril
写点啥呢9 小时前
android12解决非CarProperty接口深色模式设置后开机无法保持
android·车机·aosp·深色模式·座舱