如果一个java类,没有继承任何类,是无法直接getApplicationContext的,这时候,可以写一个全局的Context获取类:
public class GlobalApplication extends Application {
private static GlobalApplication instance;
@Override
public void onCreate() {
super.onCreate();
instance = this;
}
public static GlobalApplication getInstance() {
if (instance == null)
instance = new GlobalApplication();
return instance;
}
}
最后不要忘了,全局Context要在AndroidManifest.xml的这里配置
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme"
android:name=".application.GlobalApplication" >
网友评论