【问题标题】:How to change Retrofit baseUrl from shared preferences at runtime如何在运行时从共享首选项更改 Retrofit baseUrl
【发布时间】:2020-07-04 21:34:44
【问题描述】:

我正在尝试在运行时从我的应用程序中的 SharedPreferences 更改 Retrofit baseUrl,但只有在我关闭并打开应用程序时才会实施更改。我尝试使用 onSharedPreferenceChangeListener() 和 onPreferenceChangeListener() 但我仍然得到相同的结果。如何实现侦听器以便它们在运行时更改 baseUrl?

    private val moshi = Moshi.Builder()
        .add(KotlinJsonAdapterFactory())
        .build()

    private val retrofit = Retrofit.Builder()
        .addConverterFactory(MoshiConverterFactory.create(moshi))
        .addCallAdapterFactory(CoroutineCallAdapterFactory())
        .baseUrl(CompanyApiService .apiBaseUrl)
        .build()

    interface CompanyApiService {
        @GET("employees")
        fun getEmployeesAsync(): Deferred<List<Employees>>

        @GET("title/{id}")
        fun getTitlesAsync(@Path("id") id: Int): Deferred<List<Titles>>

        @POST("message")
        fun submitMessage(@Body message: Message): Call<String>
    }

    object CompanyApi {
        val retrofitService: CompanyApiService by lazy {
        retrofit.create(CompanyApiService ::class.java)
    }

    var apiBaseUrl = ""
    }

MainActivity.kt

    class MainActivity : AppCompatActivity(), SharedPreferences.OnSharedPreferenceChangeListener {

    ...

        PreferenceManager.setDefaultValues(this, R.xml.main_preference, false)
        val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this)
        sharedPrefs.registerOnSharedPreferenceChangeListener(this)

        val apiBaseUrl = sharedPrefs.getString(KEY_PREF_BASE_URL, "")

        CompanyApi.apiBaseUrl = apiBaseUrl!!
    }

    override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences?, key: String?) {
       if (key == KEY_PREF_BASE_URL) {
            val newApiBaseUrl = sharedPreferences?.getString(key, "")
            CompanyApi.apiBaseUrl = newApiBaseUrl!!
       }
    }

【问题讨论】:

    标签: android kotlin sharedpreferences retrofit2 moshi


    【解决方案1】:

    Lucky for you Retrofit 有一个简单的解决方案:

    public interface UserManager {  
        @GET
        public Call<ResponseBody> userName(@Url String url);
    }
    

    URL 字符串应指定您希望使用的完整 URL。

    另外,看看这个 -> enter link description here

    【讨论】:

      【解决方案2】:
      object CompanyApi {
          val retrofitService: CompanyApiService by lazy {
          retrofit.create(CompanyApiService ::class.java)
      }
      

      这会创建一个单例,您需要更改它并在更改 base_url 时重新创建您的 Api,但我不建议这样做。创建一个改造实例是消耗性的,你以后可能会遇到错误。

      【讨论】:

        猜你喜欢
        • 2011-06-17
        • 1970-01-01
        • 1970-01-01
        • 2019-10-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多