如何将正在运行的前台服务的进度传达给可组合项?

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

我正在寻找一种方法,当我的服务运行时,将实时进度返回到我的 UI,目前我正在使用共享的 hilt viewModel 来获取进度%和结果,但注入到 Service 中会给出:

禁止注入 @HiltViewModel 类,因为它无法正确创建 ViewModel 实例。 通过 Android API(例如 ViewModelProvider)访问 ViewModel。

我的可组合项:

Button(onClick = {
                val intent = Intent(context, TestService::class.java).also {
                    it.action = TestService.Actions.START.toString()
                    it.putExtra("imageUri", imageUri) // Pass the image URI to the service
                }

                ContextCompat.startForegroundService(context, intent)
            }) {
            Text(text = "Start Service")
            }

            ProgressBar()


@Composable
fun ProgressBar() {
    val serviceViewModel: ServiceViewModel = viewModel()

    val progress by serviceViewModel.progress.collectAsState()
    val result by serviceViewModel.result.collectAsState()

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        LinearProgressIndicator(
            progress = { progress },
        ) // Use state
        Text("Progress: ${progress}%")
    }

}

我的服务:

@AndroidEntryPoint
class TestService : Service(){


    @Inject
    lateinit var serviceViewModel: ServiceViewModel

    override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
        when(intent?.action) {
            Actions.STOP.toString() -> stopSelf()
            Actions.START.toString() -> start(intent)
        }
        return START_NOT_STICKY 
    }
//.... other stuff

        val progressCallback: (Float) -> Unit = { progress ->
            serviceViewModel.updateProgress(progress)
        }

//....calling progressCallback

和我的视图模型:

@HiltViewModel
class ServiceViewModel @Inject constructor() : ViewModel(){
    private val _progress = MutableStateFlow(0f)
    val progress: StateFlow<Float> = _progress.asStateFlow()

    private val _result = MutableStateFlow<Extracted?>(null)
    val result: StateFlow<Extracted?> = _result.asStateFlow()

    fun updateProgress(newProgress: Float) {
        viewModelScope.launch { 
            _progress.value = newProgress
        }
    }

    fun updateResult(newResult: Extracted) {
        viewModelScope.launch {
            _result.value = newResult
        }
    }
}

我尝试了

ViewModelProvider(this)[ServiceViewModel::class.java]
,解决了堆栈溢出错误,但似乎已被弃用,我让它工作的唯一方法是创建多个实例。

我也尝试过广播接收器,但可组合项看不到广播。

android kotlin android-jetpack-compose dagger-hilt
1个回答
0
投票

将流移至与 ViewModel 分开的单例类中,然后将新的单例类注入到 ViewModel 和 Service 中。然后,该服务会更新进度,而 ViewModel 只是提供可组合项的流程

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