如何在Android上的Kotlin类中使用上下文

问题描述 投票:1回答:1

在我的应用程序中,我使用了Retrofit和okHttpClient来获取服务器的一些请求。 在这个改造配置中,我想将一些数据发送到Header到服务器。 这个数据是设备UUID,对于获取设备UUID,我在一个类中编写代码(此类名称为Extensions):

@SuppressLint("HardwareIds")
fun Context.getDeviceUUID(): String {
    return try {
        Settings.Secure.getString(contentResolver, Settings.Secure.ANDROID_ID)
    } catch (e: Exception) {
        "exception"
    }
}

为获取设备UUID,我应该通过context

我想将此设备UUID发送到ApiClient类。 ApiClient类:

class ApiClient {

    private val apiServices: ApiServices

    init {
        //Gson
        val gson = GsonBuilder()
            .setLenient()
            .create()

        //Http log
        val loggingInterceptor = HttpLoggingInterceptor()
        loggingInterceptor.level =
            if (BuildConfig.DEBUG) HttpLoggingInterceptor.Level.BODY else HttpLoggingInterceptor.Level.NONE

        //Http Builder
        val clientBuilder = OkHttpClient.Builder()
        clientBuilder.interceptors().add(loggingInterceptor)
        clientBuilder.addInterceptor { chain ->
            val request = chain.request()
            request.newBuilder().addHeader("uuid", ).build()
            chain.proceed(request)
        }

        //Http client
        val client = clientBuilder
            .readTimeout(NETWORK_CONNECTIONS_TIME, TimeUnit.SECONDS)
            .writeTimeout(NETWORK_CONNECTIONS_TIME, TimeUnit.SECONDS)
            .connectTimeout(NETWORK_CONNECTIONS_TIME, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .build()

        //Retrofit
        val retrofit = Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .addCallAdapterFactory(RxJava2CallAdapterFactory.createWithScheduler(Schedulers.io()))
            .build()

        //Init apiServices
        apiServices = retrofit.create(ApiServices::class.java)
    }

    companion object {
        private var apiClient: ApiClient? = null

        val instance: ApiClient
            get() {
                if (apiClient == null) {
                    apiClient = ApiClient()
                }
                return apiClient as ApiClient
            }
    }
}

我应该在这段代码中使用getDeviceUUID:request.newBuilder().addHeader("uuid", ).build()

我如何将context传递给ApiClient类?

android kotlin
1个回答
1
投票

你需要修改ApiClientget()中有一个构造函数和一个参数。

class APiClient(var deviceId: String) {
init {
    //Stuff goes here
}
companion object {
    private var apiClient: APiClient? = null
    fun getInstance(deviceId: String): APiClient =
            apiClient ?: synchronized(this) {
                apiClient ?: APiClient(deviceId).also {
                    apiClient = it
                }
            }
}
}

PS,deviceUUID可以是全球因为它不会改变。更好的方法是让它像在Application类中一样在Global Access中。从哪里可以直接使用它。每次都不需要在构造函数中传递它。

© www.soinside.com 2019 - 2024. All rights reserved.