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):
class MyApp extends Application {
private String myState;
public String getState(){
return myState;
}
public void setState(String s){
myState = s;
}
}
class Blah extends Activity {
@Override
public void onCreate(Bundle b){
...
MyApp appState = ((MyApp)getApplicationContext());
String state = appState.getState();
...
}
}
This has essentially the same effect as using a static variable or singleton,
but integrates quite well into the existing Android framework.
Note that this will not work across processes (should your app be one of the rare ones that has multiple processes).
然后再manifest中添加应用:
<application android:name=".MyApp" android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".ClickableListItemActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
说明:
-
需添加的内容:android:name=".your_App_Name"
-
位置:当前activity所在的位置,(我刚开始以为需要新建一个<application></application>)
分享到:
相关推荐
c语言中头文件的-函数-全局变量
v-13-全局变量和局部变量.ev4.rar
精彩编程与编程技巧-避免使用全局变量 ...
Python由荷兰数学和计算机科学研究学会的吉多·范罗苏姆于1990年代初设计,Python提供了高效的高级数据结构,还能简单有效地面向对象编程。Python语法和动态类型,以及解释型语言的本质,使它成为多数平台上写脚本和...
Transact-sql 最常用全局变量 绝对精华 本人私藏许久 如有下载 不胜荣幸
python局部变量全局变量-静态方法-实例变量静态变量代码解析。
Android中用Application类实现全局变量
2023-04-06-项目笔记-第一阶段- 8.循环语句 8.1while循环的实例 9.函数 9.1函数的使用 10.数组 10.1.数组的使用 11....常见关键字 12.1关键字 typedef 12.2关键字static 12.2.1修饰局部变量 12.2.2修饰全局变量
android 全局变量的定义使用
用MFC制作的工程由很多文件构成,它不能象一般C++程序那样随意在类外定义全局变量,在这里要想定义能被工程内多个文件共享的全局变量和函数必须用一些特殊方法才行。实际上有多种方法可以实现,这里只介绍两种方法。
python自学教程-19-修改全局变量.ev4.rar
python数据清洗-18-访问全局变量.ev4.rar
Android-Application被回收引发空指针异常分析(消灭全局变量)-例子 http://blog.csdn.net/zivensonice/article/details/51451486
C语言实现s-function源码,包含参数输入和S-function的全局变量的使用。
uni-app全局变量的几种实现方式.zip
Android用Application设置全局变量以及使用 如果想在整个应用中使用全局变量,在java中一般是使用静态变量,public类型;而在android中如果使用这样的全局变量就不符合Android的框架架构,但是可以使用一种更优雅...
VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量VC中如何定义全局变量...
全局变量、局部变量、静态全局变量、静态局部变量的区别
当时想到的就是使用全局变量,在 app.js 中定义好全局变量,点击组件页面时就修改全局变量的值,父页面同样使用全局变量的值,这样一来就可以动态打开/关闭弹出层且传递值了。 下面先看看 app.js 中怎么定义的: ...
在C++中,声明一个类,并且定义一个全局变量,练习全局变量的使用。注意全局变量的使用技巧和方法。