如何将字符串从 MainActivity 传输到单个对象?

How to transfer string from MainActivity into single object?

我有 ServiceBuilder 初始化改造实例的对象

object ServiceBuilder {

    //private var url: String? = null
    var url = "http://no-google.com"    // The default link

    fun loadUrl(url: String): ServiceBuilder{
        this.url = url
        return this
    }

    private var logger = HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)

    val headerInterceptor = object: Interceptor {

        override fun intercept(chain: Interceptor.Chain): Response {

            var request = chain.request()

            request = request.newBuilder()
                .addHeader("x-device-type", Build.DEVICE)
                .addHeader("Accept-Language", Locale.getDefault().language)
                .build()

            val response = chain.proceed(request)
            return response
        }

    }

    // Create OkHttp Client
    private val okHttp = OkHttpClient.Builder()
        .callTimeout(5, TimeUnit.SECONDS)
        .addInterceptor(headerInterceptor)
        .addInterceptor(logger)

    // Create Retrofit Builder
    private val builder = Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttp.build())

    // Create Retrofit Instance
    private val retrofit = builder.build()

    fun <T> buildService(serviceType: Class<T>): T {
        return retrofit.create(serviceType)
    }
}

getUrlFromServer() 方法在 MainActivity

private fun getUrlFromServer(str: String){
        val destinationService = ServiceBuilder
            .loadUrl("http://google.com")       // <-- This call can not reply url into ServiceBuilder object
            .buildService(DestinationService::class.java)

        val requestCall = destinationService.getList()

        requestCall.enqueue(object: Callback<List<Destination>> {
            override fun onResponse(
                call: Call<List<Destination>>,
                response: Response<List<Destination>>
            ) {
                if (response.isSuccessful){
                    val destinationList = response.body()
                    //Toast.makeText(this, destinationList.toString(), Toast.LENGTH_LONG)
                }
            }

            override fun onFailure(call: Call<List<Destination>>, t: Throwable) {
                TODO("Not yet implemented")
            }

        })
    }

我不明白为什么 ServiceBuilder 中的 loadUrl() 函数无法加载 url。我需要将 url 从 MainActivity 发送到 ServiceBuilder 对象。

请告诉我如何以良好的方式决定这个问题

因为创建改造实例,发生在 ServiceBuilder loadUrl 函数之前。 实际上改造实例,总是用“http://no-google.com”url!!

创建
fun <T> buildService(serviceType: Class<T>): T {
    // Create Retrofit Builder
    private val builder = Retrofit.Builder()
        .baseUrl(url)
        .addConverterFactory(GsonConverterFactory.create())
        .client(okHttp.build())

    // Create Retrofit Instance
    private val retrofit = builder.build()

    return retrofit.create(serviceType)
}