gpt4 book ai didi

android - 在没有上下文的情况下获取共享偏好

转载 作者:行者123 更新时间:2023-12-05 05:58:46 24 4
gpt4 key购买 nike

大家晚上好!我想使用共享首选项来存储我的 token (我知道这不安全,我是 android 开发的新手,只想尝试)然后将其传递给拦截器。我如何在那里初始化共享首选项?谢谢!或者你能给我一个如何实现拦截器或存储 token 的提示吗?

抱歉,我已经尝试搜索此主题,但无法实现其他开发人员的方法。

object NetworkModule {

var sharedPreferences = //GET SHARED PREFERENCES THERE

var authToken: String? = sharedPreferences.getString("Token", null)
val baseURL = //my base url


val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}


var httpClient = OkHttpClient.Builder().addInterceptor { chain ->
chain.proceed(
chain.request().newBuilder().also { it.addHeader("Authorization", "Bearer $authToken") }
.build()
)
}.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.addNetworkInterceptor(loggingInterceptor)
.build()

val retrofit = Retrofit.Builder().baseUrl(baseURL).addConverterFactory(
GsonConverterFactory.create()
).client(httpClient).build()


val api: API by lazy { retrofit.create() }
val apiClient = ApiClient(api)
}

最佳答案

您可以使用 ApplicationContext 从您的应用任何地方访问SharedPreferences。这是 Android 开发中非常普遍的做法,而且非常安全。

要访问ApplicationContext请看下面的代码:

  1. 在您的 Application 类中,添加一个 Application Singleton

    class MyApplication : Application() {
    override fun onCreate() {
    super.onCreate()
    instance = this
    }

    companion object {
    lateinit var instance: MyApplication
    private set
    }
    }

    ( What is an Application Class? )

  2. 在您的应用中的任何位置使用 ApplicationContext!

    var sharedPreferences = getApplicationContext() //here you go!

此代码可以完成工作,但是,如果您对最佳 Android 开发实践感兴趣,请阅读:

推荐的 2 个选项

  1. 最佳实践:创建一个新的管理器类,负责应用的整个 SharedPreferences 使用(例如 SharedPreferenceManager)。此类是一个 Singleton 类,它是用 ApplicationContext 实例化的,并且在 SharedPreferences 中具有与 CRUD 操作相关的所有方法,在您的例子中是 setToken getToken。由于管理器类是独立的,因此它不应导致任何 Lifecycle 错误或 NullPointer 错误。

    由于附加示例代码会使我的答案困惑,我决定引用 someone else's code here, this will teach you how to implement it.

  2. 如果您懒得遵循 #2:您可以使用已经为您完成此操作的库:Pixplicity/EasyPrefs .

    • Manager 类一样易于使用 ✅
    • 没有更多与 SharedPreferences 相关的错误 ✅
    • 您可以随时改造任何现有项目 ✅

如果您有任何问题,请告诉我。谢谢。

关于android - 在没有上下文的情况下获取共享偏好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68366122/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com