2017年5月24日 (周三) 大雨(超j8大)
自定义了一个类 App类 继承了Application 类 定义一个静态变量public static Context context;
import android.content.Context;
public class App extends Application {
private static Context context;
@Override
public void onCreate() {
context = getApplicationContext();
}
}
但是在调用APP.context
时程序报错奔溃

开始以为是调用静态变量 未实例化App 所以没调用onCreate()
所以未执行到context = getApplicationContext();
所以没获取到contenxt的原因 于是对App类做了稍微微的调整
import android.content.Context;
public class App extends Application {
private static Context context;
@Override
public void onCreate() {
context = getApplicationContext();
}
public static Context getContext(){
return context;
}
}
调用:Context context=new App().getContext();
按常理来说 类实例化后执行了onCreate()
应该获取到了getApplicationContext()
但是...
程序依然报错闪退

于是采用了万能的问题解决方法


在查阅了大量资料后最终发现了问题
原来是
AndroidManifest.xml
文件中未对自定义的App类进行初始化在
<application>
中添加了一行android:name="com.example.administrator.App"(你自定义的那个类名)
告知系统当程序启动的时候应该初始化App类,而不是系统默认的Application
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme"
android:name="com.example.administrator.App" //这一行!!!!!
></application>
执行到Context context=App.context;
成功获取到系统的Context
网友评论