保留应用程序上下文并将其用于 Toast 和 SharedPreferences 是否安全?

Is it safe to keep an application Context and use it for Toast and SharedPreferences?

  1. 我如何获得应用程序上下文:

    private static OBDApplication mInstance;
    
    public static OBDApplication getInstance () {
        return mInstance;
    }
    @Override
    public void onCreate () {
        super.onCreate();
        mInstance = this;
    }
    
  2. 我知道application Context不是处处可以用的,比如DialogstartActivity。而且我知道,当 activity 被销毁时,我应该始终让带有 activity Conetxt 的引用完成。但是我注意到,ToastSharedPreferences可以使用application Context,而且不会导致内存泄漏,看起来很无辜。

  3. 那我该怎么办?如果以上问题不存在,那就可以爽了:

    public static void toast ( @StringRes int resID){
        Toast.makeText(OBDApplication.getInstance().getApplicationContext(), resID, Toast.LENGTH_SHORT).show();
    }
    
  4. 但我知道最简单的方法,所以我花了一些时间搜索,但我得到了一些相反的意见。

    有人说:"it's bad to use application Context, cause while activity destroy, the toast of this activity should release too, but if u use application Context which means it's life is as long as the application. So is kind of waste".

    然而有人说:"it's good to use application Context, cause in this case, you always use a same object , a same toast ,that means it will not produce new toast again and again".

是的,您当然也可以将应用程序上下文用于 show toast 和 sharedprefrence,因为它们都是在不与 activity 交互的情况下使用的。

简单的例子就像服务,你可以从服务中使用这两个服务,服务没有任何 activity 参考,但它工作正常..

您甚至可以在

中使用 Application Context 通过应用程序

ActivityService 意味着您可以在所有 Android 组件中使用。

还显示 Toast 消息,SharedPreferences,餐饮 DataBase 对象,LayoutInflater

Application – is a singleton instance running in your application process. It can be accessed via methods like getApplication() from an Activity or Service, and getApplicationContext() from any other object that inherits from Context. Regardless of where or how it is accessed, you will always receive the same instance from within your process.

据我所知,Toast 和共享首选项没有应用程序的父视图,它将接受所有应用程序上下文,并且不会要求应用程序的应用程序上下文。即使您的应用程序未处于活动状态,它也能正常工作。

然而,在我们的应用程序中,我们可能会创建一些仅在我们的应用程序上下文中 运行 的视图。当您将其保存为静态并尝试在该特定上下文不存在时使用时,它将出现异常。

所以,保存边界是,我们不应该在任何地方保存我们的应用程序上下文的实例。您应该在需要时从应用程序中检索它,使用 getActivity() 来自片段,this 来自 Activity。