如果要在应用程序上下文中访问某些函数例如 getResources() 和 getString(),用户会收到一个错误“Application Context cannot cast to Activity Context”。为了解决此问题,可以通过将应用程序上下文强制转换为 Activity 上下文,然后将其传递给所需的函数,然后获取 Activity 上下文的引用来避免错误。
示例代码如下:
//获取应用上下文
Context applicationContext = getApplicationContext();
//获取Activity上下文
Activity activityContext = this;
// 使用Activity上下文执行函数
String string = activityContext.getResources().getString(R.string.app_name);
// 强制转换应用上下文到 Activity 上下文
String string2 = ((Activity) applicationContext).getResources().getString(R.string.app_name);