简体   繁体   English

Android:如何从扩展应用程序的 class 将应用程序上下文作为活动获取?

[英]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.

相关问题 Android-如何从Java类传递另一个活动应用程序上下文将片段扩展到asynctask? - Android - How to pass another activity application context from java class extends fragments to asynctask? Crosswalk-如何在XWalkExtension类中获取android应用程序上下文? - Crosswalk - How do you get android application context in the XWalkExtension class? 如何从不扩展Activity,Android的类中创建DatePicker? - How to create a DatePicker from class which do not extends Activity, Android? 如何从不扩展 Activity、Android 的类创建 TimePicker? - How to create a TimePicker from class which do not extends Activity, Android? 扩展Android中的类应用程序? - Extends class Application in Android? 从非活动单例类中获取应用程序上下文 - Get application context from non activity singleton class 如何从 Android 服务获取应用程序上下文? - How can I get the application context from an Android Service? 当我在android上扩展Application时,上下文在Glide上不起作用 - Context is not working on Glide when I extends Application on android 从扩展应用程序的另一个 class 的活动中调用方法 - Call method in an activity from another class that extends Application 如何从非活动和finish();获取应用程序上下文? - how to get application context from non activity and finish();?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM