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

Web-based content

 

Connect to the network


<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />



Types of permissions 
 
Request app permissions

Best practices for secure network communication

Handle user data
 
Security with HTTPS and SSL
 
Network security configuration
 
Use networking

Choose an HTTP client

HttpsURLConnection
 
Retrofit
 

Resolve DNS queries

DnsResolver
 
android_res_nsend
 

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)
    }
}

 

NetworkOnMainThreadException
  

Survive configuration changes

ViewModel Overview
 
LiveData Overview


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
            }

        }
    }
}

Application Fundamentals
 
Guide to app architecture

留言

這個網誌中的熱門文章

泰文子音與字形之間的變化

AUTOMAXX UP-5HX 使用心得