android 中使用 application (类似于vuex , 控制全局变量)

访问量: 416

refer to: https://www.mobomo.com/2011/05/how-to-use-application-object-of-android/

1. 创建一个 class: 

public class MyApplication extends Application {
      //声明成 单例
      private static MyApplication singleton;
      public static MyApplication getInstance(){
          return singleton;
      }


	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}

	@Override
	public void onCreate() {
		super.onCreate();
		singleton = this;        // 还是声明成为单例
	}

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}

	@Override
	public void onTerminate() {
		super.onTerminate();
	}

}

2.  修改 AndroidManifest.xml:   (注意最后的 android:name ) 

<application android:icon="@drawable/icon" android:label="@string/app_name" android:name="MyApplication">

3.  然后,就可以在Activity 中调用了。

MyApplication myApplication = (MyApplication)getApplicationContext();

4. 记得,声明成为单例。 如下:

public class MyApplication extends Application {
	private static MyApplication singleton;
	
	public static MyApplication getInstance(){
		return singleton;
	}
	@Override
	public void onCreate() {
		super.onCreate();
		singleton = this;
	}
}

订阅/RSS Feed

Subscribe

分类/category