最实在的办法就是继承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()进行获取,其他的全局变量也类似。

更多相关文章

  1. Netty实战(三)Unity程序采用netty和其他netty程序通信
  2. Android 程序执行Linux命令的解决方法及注意事项
  3. android学习——activity的生命周期
  4. Mono for Android (2)-- Android应用程序初认识
  5. Android程序调试时生成main.out.xml文件
  6. [干货] Android 深入浅出 Activity 生命周期(二)
  7. 使用valgrind检测Android native程序的内存

随机推荐

  1. Android(安卓)View动画开发笔记
  2. Android Flexboxlayout使用详解
  3. 开启Android开发的旅程!
  4. android之Layout(二)
  5. android shell 2
  6. Android(安卓)WebView如何加载assets下的
  7. [转]NDK中log输出方法
  8. Android细节问题总结(二)
  9. android编译系统的makefile文件Android.m
  10. Android(安卓)Gradle 基本模板