这样您就可以从任何地方访问applicationContext,这样您就可以在任何地方使用AndroidManifest.xml; Application,getString(),sharedPreferences等
单身人士:
package com.domain.packagename;
import android.content.Context;
/**
* Created by Versa on 10.09.15.
*/
public class ApplicationContextSingleton {
private static PrefsContextSingleton mInstance;
private Context context;
public static ApplicationContextSingleton getInstance() {
if (mInstance == null) mInstance = getSync();
return mInstance;
}
private static synchronized ApplicationContextSingleton getSync() {
if (mInstance == null) mInstance = new PrefsContextSingleton();
return mInstance;
}
public void initialize(Context context) {
this.context = context;
}
public Context getApplicationContext() {
return context;
}
}
初始化AndroidManifest.xml子类中的Singleton:
package com.domain.packagename;
import android.app.Application;
/**
* Created by Versa on 25.08.15.
*/
public class mApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
ApplicationContextSingleton.getInstance().initialize(this);
}
}
如果我没错,这会给你一个applicationContext到处的钩子,用AndroidManifest.xml调用它你不应该在任何时候都清楚这一点,因为当应用程序关闭时,无论如何都是这样。
记得更新AndroidManifest.xml以使用这个Application子类:
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.domain.packagename"
>
android:allowBackup="true"
android:name=".mApplication"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:icon="@drawable/app_icon"
>
如果你在这里看到任何错误,请告诉我,谢谢。:)