Android Connectivity - Connect to the network Study Notes
Android Connectivity
Bluetooth, NFC, Wi-Fi P2P, USB, and SIP
Perform network operations overview
https://developer.android.com/training/basics/network-ops
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Best practices for secure network communication
Choose an HTTP client
Resolve DNS queries
Encapsulate network operations with a repository
interface UserService {
@GET("/users/{id}")
suspend fun getUser(@Path("id") id: String): User
}
class UserRepository constructor(
private val userService: UserService
) {
suspend fun getUserById(id: String): User {
return userService.getUser(id)
}
}
Survive configuration changes
class MainViewModel constructor(
savedStateHandle: SavedStateHandle,
userRepository: UserRepository
) : ViewModel() {
private val userId: String = savedStateHandle["uid"] ?:
throw IllegalArgumentException("Missing user ID")
private val _user = MutableLiveData<User>()
val user = _user as LiveData<User>
init {
viewModelScope.launch {
try {
// Calling the repository is safe as it will move execution off
// the main thread
val user = userRepository.getUserById(userId)
_user.value = user
} catch (error: Exception) {
// show error message to user
}
}
}
}
留言
張貼留言