[英]Android: How do I get the Application Context as an Activity from a class that extends Application?
How do I retrieve the Application Context as an Activity in class that extends Application?如何检索应用程序上下文作为扩展应用程序的 class 中的活动? I need to retrieve the context as an Activity so that I can broadcast
PendingIntent
s.我需要将上下文作为 Activity 检索,以便我可以广播
PendingIntent
。 My current code is:我目前的代码是:
public class SharedResources extends Application {
private static Activity context;
@Override
public void onCreate() {
super.onCreate();
context = (Activity) getApplicationContext();
}
}
But I get an error, stating that my class SharedResources
cannot be cast to android.app.Activity
.但我收到一个错误,指出我的 class
SharedResources
无法转换为android.app.Activity
。
You don't need activity context for shared preferences.您不需要共享偏好的活动上下文。 You can get the shared preferences instance in the following manner also.
您也可以通过以下方式获取共享首选项实例。
SharedPreferences pref = getApplicationContext().getSharedPreferences("YOUR_SHARED_PREF_NAME", 0)
SharedPreferences just needs a context object, not activity context. SharedPreferences 只需要一个上下文 object,而不是活动上下文。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.