You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

屏幕旋转时API调用中断如何处理?含多API与登录场景

Solutions for Screen Rotation Interrupting API Calls

Hey there! Let's break down practical fixes for both of your screen rotation + API call issues—these are classic Android development headaches, but we’ve got solid, user-friendly solutions.

1. Handling 7 Concurrent API Calls in an Activity

When multiple API calls are running, screen rotation interrupts them because the Activity gets destroyed and recreated. Here are two reliable approaches:

Option 1: Temporarily Lock Screen Orientation Until All APIs Complete

You can lock the screen to its current orientation when you start the first API call, then unlock it once the final call succeeds. This prevents rotation mid-request entirely.

Here’s a quick Kotlin example:

import android.content.pm.ActivityInfo

// When starting your API sequence
val originalOrientation = requestedOrientation
// Lock to the current screen orientation
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED)

// Once all 7 API calls finish successfully:
setRequestedOrientation(originalOrientation) // Restore normal rotation behavior

Pro tip: Add a safety check in onDestroy() to unlock the orientation if the Activity gets destroyed unexpectedly (like low memory). This ensures users don’t get stuck with a locked screen later.

Locking orientation can harm user experience, so a better long-term fix is decoupling API calls from the Activity lifecycle using a ViewModel. ViewModels survive screen rotations, so your API calls will keep running even when the Activity recreates.

Use viewModelScope (for Kotlin Coroutines) to launch requests, then expose results via LiveData or Flow:

class MyActivityViewModel : ViewModel() {
    private val _apiResults = MutableLiveData<List<ApiResponse>>()
    val apiResults: LiveData<List<ApiResponse>> = _apiResults

    fun fetchAllData() {
        viewModelScope.launch {
            // Launch all 7 API calls concurrently with async/await
            val responses = listOf(
                async { apiService.call1() },
                async { apiService.call2() },
                // ... up to call7
            ).awaitAll()

            _apiResults.postValue(responses)
        }
    }
}

In your Activity, observe the apiResults LiveData. When the Activity recreates after rotation, it will automatically re-subscribe and receive results once they’re ready—no interruptions, no locked orientation.

2. Fixing Login Screen API Interruptions

For your login scenario, the ViewModel approach is even more critical. Here’s how to implement it smoothly:

  1. Move the login API call to a ViewModel:
class LoginViewModel : ViewModel() {
    private val _loginState = MutableLiveData<LoginState>()
    val loginState: LiveData<LoginState> = _loginState

    fun login(username: String, password: String) {
        viewModelScope.launch {
            _loginState.postValue(LoginState.Loading)
            try {
                val authToken = apiService.login(username, password)
                _loginState.postValue(LoginState.Success(authToken))
            } catch (e: Exception) {
                _loginState.postValue(LoginState.Error(e.message))
            }
        }
    }

    sealed class LoginState {
        object Loading : LoginState()
        data class Success(val token: String) : LoginState()
        data class Error(val message: String?) : LoginState()
    }
}
  1. In your LoginActivity, observe the loginState:
class LoginActivity : AppCompatActivity() {
    private lateinit var viewModel: LoginViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        viewModel = ViewModelProvider(this)[LoginViewModel::class.java]

        loginButton.setOnClickListener {
            val username = usernameInput.text.toString()
            val password = passwordInput.text.toString()
            viewModel.login(username, password)
        }

        viewModel.loginState.observe(this) { state ->
            when (state) {
                is LoginViewModel.LoginState.Loading -> showLoadingSpinner()
                is LoginViewModel.LoginState.Success -> navigateToHomeScreen(state.token)
                is LoginViewModel.LoginState.Error -> showErrorToast(state.message)
            }
        }
    }
}

Now, when the user clicks login and rotates the screen, the API call keeps running in the ViewModel. The new Activity instance will immediately pick up the loginState LiveData and handle the result (navigate to home, show error) once it’s ready—no stuck state for the user.


内容的提问来源于stack exchange,提问作者Sumedh Ulhe

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 09:35:31