关于在Android设置全局变量随时获取context
2024-08-25 05:55:33
最实在的办法就是继承Application,在里面设置全局变量,因为Application是android的应用入口,并且运行周期贯穿整个程序运行。
import android.app.Application; public class MyApplication extends Application{
private static Context mContext; public static Context getContext (){
return this.mContext;
}
public void setContext (Context mContext){
this.mContext= c;
}
@Override
public static void onCreate(){
mContext=this;
super.onCreate();
}
}
同时要在AndroidManifest.xml里面的application属性添加android:name=".MyApplication",指明自己定义的application
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@android:style/Theme.Translucent" >
然后在整个程序中,需要context的时候就可以直接调用MyApplication.getContext()进行获取,其他的全局变量也类似。
最新文章
- try,catch,finally含return时的执行顺序及丢失的伪例
- Excel图表的基本类型与选择
- ListView组件应用源码
- android中图片的三级缓存cache策略(内存/文件/网络)
- SimpleDateFormatter Java中的用法
- poj 1581 A Contesting Decision
- (转载)file_get_contents(";php://input";)
- shc加密shell脚本
- ubuntu系统搭建以太坊私有链
- TPshop入门大纲
- 基于Kafka的生产者消费者消息处理本地调试
- PyQt5系列教程(六)如何让界面和逻辑分离
- 学习笔记之1001 Inventions That Changed the World
- python的多线程和守护线程
- Oracle学习笔记(三)
- JAVA中的static关键字(静态变量和成员变量)
- 【DataStructure】Some useful methods about linkedList.
- nodejs之log4js日志记录模块简单配置使用
- Java中的Set,List,Map的区别
- Android中Native和H5交互
热门文章
- Altium Designer 6三维元件库建模教程
- HDU 5821 Ball (排序)
- How to create custom methods for use in spring security expression language annotations
- JOIN 相关内容
- js 对象与函数的区别
- 全代码实现ios-2
- OpenGL光照测试
- Android - Facebook KeyHash 設定
- Sending messages to non-windowed applications -- AllocateHWnd, DeallocateHWnd
- function设置jsp页面使用js控制文本框只读,并且按下backspace删除按钮后停在原页面