1.0 能用
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package net.bluemangoo.indpjsk.ui
|
||||
|
||||
import android.content.Context
|
||||
import android.content.Intent
|
||||
import androidx.lifecycle.ViewModel
|
||||
import androidx.lifecycle.viewModelScope
|
||||
import net.bluemangoo.indpjsk.data.CaptureProfile
|
||||
import net.bluemangoo.indpjsk.data.PredefinedProfiles
|
||||
import net.bluemangoo.indpjsk.state.CaptureStateHolder
|
||||
import net.bluemangoo.indpjsk.state.CaptureStatus
|
||||
import net.bluemangoo.indpjsk.vpn.CaptureVpnService
|
||||
import net.bluemangoo.indpjsk.vpn.VpnLog
|
||||
import kotlinx.coroutines.flow.SharingStarted
|
||||
import kotlinx.coroutines.flow.StateFlow
|
||||
import kotlinx.coroutines.flow.map
|
||||
import kotlinx.coroutines.flow.stateIn
|
||||
import java.io.File
|
||||
|
||||
data class CaptureUiState(
|
||||
val profiles: List<CaptureProfile> = emptyList(),
|
||||
val selectedProfile: CaptureProfile? = null,
|
||||
val status: CaptureStatus = CaptureStatus.IDLE,
|
||||
val lastCapturedFile: File? = null,
|
||||
val errorMessage: String? = null
|
||||
)
|
||||
|
||||
class CaptureViewModel : ViewModel() {
|
||||
|
||||
val uiState: StateFlow<CaptureUiState> = CaptureStateHolder.state
|
||||
.map { s ->
|
||||
CaptureUiState(
|
||||
profiles = PredefinedProfiles.all,
|
||||
selectedProfile = s.profile,
|
||||
status = s.status,
|
||||
lastCapturedFile = s.lastCapturedFile,
|
||||
errorMessage = s.errorMessage
|
||||
)
|
||||
}
|
||||
.stateIn(
|
||||
scope = viewModelScope,
|
||||
started = SharingStarted.WhileSubscribed(5_000),
|
||||
initialValue = CaptureUiState(
|
||||
profiles = PredefinedProfiles.all,
|
||||
selectedProfile = PredefinedProfiles.all.firstOrNull()
|
||||
)
|
||||
)
|
||||
|
||||
fun selectProfile(profile: CaptureProfile) {
|
||||
CaptureStateHolder.selectProfile(profile)
|
||||
}
|
||||
|
||||
fun startCapture(context: Context) {
|
||||
val profile = uiState.value.selectedProfile ?: return
|
||||
VpnLog.clear()
|
||||
CaptureStateHolder.setRunning()
|
||||
|
||||
val intent = Intent(context, CaptureVpnService::class.java).apply {
|
||||
action = CaptureVpnService.ACTION_START
|
||||
putExtra(CaptureVpnService.EXTRA_PROFILE_ID, profile.id)
|
||||
}
|
||||
context.startService(intent)
|
||||
}
|
||||
|
||||
fun stopCapture(context: Context) {
|
||||
val intent = Intent(context, CaptureVpnService::class.java).apply {
|
||||
action = CaptureVpnService.ACTION_STOP
|
||||
}
|
||||
context.startService(intent)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user