init
This commit is contained in:
@@ -0,0 +1,50 @@
|
||||
package com.sw.inbound.utils
|
||||
|
||||
import android.content.Context
|
||||
import android.view.View
|
||||
import androidx.compose.runtime.Composable
|
||||
import androidx.compose.ui.platform.LocalContext
|
||||
import androidx.compose.ui.platform.LocalView
|
||||
|
||||
/**
|
||||
* Context 工具类
|
||||
*/
|
||||
object ContextUtils {
|
||||
|
||||
// ========== Composable 内获取 ==========
|
||||
|
||||
/**
|
||||
* 获取当前 Composable 的 Activity Context
|
||||
* 只能在 @Composable 函数中调用
|
||||
*/
|
||||
@Composable
|
||||
fun getActivityContext(): Context {
|
||||
return LocalContext.current
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取当前 Composable 的 View
|
||||
*/
|
||||
@Composable
|
||||
fun getLocalView(): View {
|
||||
return LocalView.current
|
||||
}
|
||||
|
||||
// ========== 非 Composable 环境获取 ==========
|
||||
|
||||
/**
|
||||
* 通过静态 Application 引用获取
|
||||
* 需要在 Application 类中初始化
|
||||
*/
|
||||
private var _applicationContext: Context? = null
|
||||
|
||||
fun initAppContext(context: Context) {
|
||||
_applicationContext = context.applicationContext
|
||||
}
|
||||
|
||||
fun getAppContext(): Context {
|
||||
return _applicationContext ?: throw IllegalStateException(
|
||||
"Application context not initialized. Call initAppContext() first."
|
||||
)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user