哩哩啦啦 發表於 2025-7-24 09:59:22

Android Studio如何利用Application操作全局变量的代码详解

<div id="navCategory"><h5 class="catalogue">目录</h5><ul class="first_class_ul"><li>一、全局变量是什么</li><li>二、如何把输入的信息存储到全局变量</li><ul class="second_class_ul"><li>2.1&nbsp;MainApplication类</li><li>2.2 XML文件</li></ul><li>三、全局变量读取</li><ul class="second_class_ul"></ul><li>四、修改manifest</li><ul class="second_class_ul"></ul><li>五、效果展示</li><ul class="second_class_ul"></ul></ul></div><p class="maodian"></p><h2>一、全局变量是什么</h2>
<p><strong>全局变量</strong>是指<strong>在程序的整个生命周期内都可访问的变量</strong>,它的作用范围不限于某个函数、方法或类,而是可以被多个代码模块共享。</p>
<p>学习过java的可能会对此有些陌生,java中并没有全局变量的概念,但是在学习servlet的时候,必然接触过请求域和应用域,所谓的应用域对象servletContext,也就是servlet上下文对象,在这个对象中绑定的数据可以被所有用户所共享。比如setAttribute方法可以向域中绑定数据,getAttribute和removeAttribute分别可以从域中获取、移除数据。</p>
<p>类比来看,<strong>Application Scope(应用域)</strong> 很像 Java 的全局变量,因为它在整个应用程序的生命周期内都是可用的,适用于存储全局数据。</p>
<p>另外可以用单例模式来存储&ldquo;全局变量&rdquo;:</p>
<div class="jb51code"><pre class="brush: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");</pre></div>
<p>这样读取的时候,就会有固定的输出内容:</p>
<div class="jb51code"><pre class="brush:java;">System.out.println(GlobalManager.getInstance().getData()); // 输出: Hello</pre></div>
<p>在AS中Application的生命周期覆盖了全过程,不像Activity活动页面,一旦页面关闭生命周期就进入destroy,利用全生命特性,可以用来存储全局变量。</p>
<p class="maodian"></p><h2>二、如何把输入的信息存储到全局变量</h2>
<p>先看第一段代码,其作用就是把用户的注册信息保存到全局变量hashmap中。</p>
<div class="jb51code"><pre class="brush: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);
      }
    }

}</pre></div>
<p class="maodian"></p><h3>2.1&nbsp;MainApplication类</h3>
<p>其中,我自定义了一个MainApplication类,具体代码如下:</p>
<p><strong>这个自定义 <code>Application</code> 类的作用</strong></p>
<p><strong>存储全局数据</strong></p>
<ul><li>定义了 <code>infoMap</code> 变量,用于存储一些全局信息,比如用户输入的数据。</li><li>由于 <code>Application</code> 的生命周期与应用相同(应用启动 -&gt; 关闭),<code>infoMap</code> 里的数据在应用运行期间都是有效的。</li></ul>
<p><strong>提供 <code>getInstance()</code> 方法,作为单例使用</strong></p>
<ul><li><code>MainApplication</code> 使用 <code>mApp</code> 作为静态实例,并在 <code>onCreate()</code> 里初始化它,这样,任何地方都可以通过 <code>MainApplication.getInstance()</code> 访问 <code>Application</code>,不用每次都 <code>getApplication()</code>。</li></ul>
<div class="jb51code"><pre class="brush:java;">public class MainApplication extends Application {
    private static MainApplication mApp;
    public HashMap&lt;String,String&gt; infoMap =new HashMap&lt;String,String&gt;();

    public static MainApplication getInstance(){
      return mApp;
    }

    @Override
    public void onCreate() {
      super.onCreate();
      mApp = this;
    }
}
</pre></div>
<p class="maodian"></p><h3>2.2 XML文件</h3>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202507/2025072409540688.png" /></p>
<p>信息收集的页面示意图,其具体代码如下:</p>
<div class="jb51code"><pre class="brush:xml;">&lt;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" &gt;

    &lt;RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="40dp" &gt;

      &lt;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" /&gt;

      &lt;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" /&gt;
    &lt;/RelativeLayout&gt;

    &lt;RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="40dp" &gt;

      &lt;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" /&gt;

      &lt;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" /&gt;
    &lt;/RelativeLayout&gt;
   
    &lt;RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="40dp" &gt;

      &lt;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" /&gt;

      &lt;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" /&gt;
    &lt;/RelativeLayout&gt;
   
    &lt;RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="40dp" &gt;

      &lt;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" /&gt;

      &lt;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" /&gt;
    &lt;/RelativeLayout&gt;
   
    &lt;RelativeLayout
      android:layout_width="match_parent"
      android:layout_height="40dp" &gt;

      &lt;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" /&gt;
    &lt;/RelativeLayout&gt;
   
    &lt;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" /&gt;
    &lt;Button
      android:id="@+id/btn_intent"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="跳转到读取页面"/&gt;

&lt;/LinearLayout&gt;</pre></div>
<p class="maodian"></p><h2>三、全局变量读取</h2>
<p>这里的代码是从全局变量infoMap中读取用户的注册信息</p>
<div class="jb51code"><pre class="brush: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&lt;String, String&gt; mapParam = app.infoMap;
                // 遍历映射全局变量内部的键值对信息
                for (Map.Entry&lt;String, String&gt; item_map : mapParam.entrySet()) {
                        desc = String.format("%s\n %s的取值为%s",
                                        desc, item_map.getKey(), item_map.getValue());
                }
                if (mapParam.size() &lt;= 0) {
                        desc = "全局内存中保存的信息为空";
                }
                tv_app.setText(desc);
        }
       
}
</pre></div>
<p class="maodian"></p><h2>四、修改manifest</h2>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202507/2025072409540614.jpg" /></p>
<p class="maodian"></p><h2>五、效果展示</h2>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202507/2025072409540721.png" /></p>
<p>可以看到全局变量的信息已经被页面2所获取。</p>
<p style="text-align:center"><img alt="" src="https://img.jbzj.com/file_images/article/202507/2025072409540726.png" /></p>
<p>以上就是Android Studio如何利用Application操作全局变量的代码详解的详细内容,更多关于Android Studio Application全局变量的资料请关注琼殿技术社区其它相关文章!</p>
                           
                            <div class="art_xg">
                              <b>您可能感兴趣的文章:</b><ul><li>解决Android Studio一直停留在MyApplication:syncing的问题</li><li>Android Studio报:“Attribute application@theme or @ icon ”问题的解决</li><li>Android&nbsp;Studio实现自定义全局悬浮按钮的示例代码</li><li>Android&nbsp;Studio全局搜索快捷键(Ctrl+Shift+F)失效问题及解决</li><li>Android&nbsp;Studio&nbsp;全局查找问题</li></ul>
                            </div>

                        </div>
                        <!--endmain-->
頁: [1]
查看完整版本: Android Studio如何利用Application操作全局变量的代码详解