现代 Android 开发

93 阅读2分钟

第七章:现代 Android 开发

Jetpack 组件库介绍

Jetpack 是 Android 官方推荐的开发组件集,类似于前端中的各种框架生态。这些组件能帮助我们更快地开发高质量的应用:

Navigation 导航组件

类似于前端的路由系统:

// 定义导航图 (nav_graph.xml)
<?xml version="1.0" encoding="utf-8"?>
<navigation xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/nav_graph"
    app:startDestination="@id/homeFragment">

    <fragment
        android:id="@+id/homeFragment"
        android:name=".HomeFragment">
        <action
            android:id="@+id/action_home_to_detail"
            app:destination="@id/detailFragment" />
    </fragment>

    <fragment
        android:id="@+id/detailFragment"
        android:name=".DetailFragment" />
</navigation>

// 在代码中使用
findNavController().navigate(R.id.action_home_to_detail)

Lifecycle 组件

自动管理生命周期,避免内存泄漏:

class MyObserver : LifecycleObserver {
    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    fun onResume() {
        // 处理 Resume 事件
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    fun onPause() {
        // 处理 Pause 事件
    }
}

// 在 Activity 中使用
lifecycle.addObserver(MyObserver())

MVVM 架构实践

ViewModel 层

class UserViewModel : ViewModel() {
    private val repository = UserRepository()
    private val _users = MutableStateFlow<List<User>>(emptyList())
    val users: StateFlow<List<User>> = _users.asStateFlow()

    init {
        viewModelScope.launch {
            repository.getUsers()
                .catch { e -> 
                    // 错误处理
                }
                .collect { users ->
                    _users.value = users
                }
        }
    }
}

Repository 层

class UserRepository @Inject constructor(
    private val apiService: ApiService,
    private val userDao: UserDao
) {
    fun getUsers() = flow {
        // 先从数据库加载
        emit(userDao.getAll())
        
        // 再从网络请求
        val remoteUsers = apiService.getUsers()
        userDao.insertAll(remoteUsers)
        
        // 发送最新数据
        emit(userDao.getAll())
    }
}

Kotlin 协程

基础用法

// 启动协程
lifecycleScope.launch {
    try {
        val result = withContext(Dispatchers.IO) {
            // 执行耗时操作
            api.fetchData()
        }
        // 更新 UI
        updateUI(result)
    } catch (e: Exception) {
        // 错误处理
    }
}

Flow 数据流

类似于 RxJS:

fun getDataFlow() = flow {
    while(true) {
        emit(fetchLatestData())
        delay(1000)
    }
}

// 使用 Flow
lifecycleScope.launch {
    getDataFlow()
        .filter { it.isValid }
        .map { it.process() }
        .collect { result ->
            // 处理结果
        }
}

组件化与模块化

项目结构

app/
├── build.gradle
├── src/
│   ├── main/
│   │   ├── java/
│   │   │   ├── data/         # 数据层
│   │   │   ├── domain/       # 领域层
│   │   │   ├── presentation/ # 展示层
│   │   │   └── di/          # 依赖注入
│   │   └── res/
├── feature_home/     # 首页模块
├── feature_profile/  # 个人中心模块
└── core/            # 核心模块

依赖注入(使用 Hilt)

@HiltAndroidApp
class MyApplication : Application()

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var userRepository: UserRepository
    
    private val viewModel: UserViewModel by viewModels()
}

@Module
@InstallIn(SingletonComponent::class)
object AppModule {
    @Provides
    @Singleton
    fun provideApiService(): ApiService {
        return Retrofit.Builder()
            .baseUrl("https://api.example.com")
            .build()
            .create(ApiService::class.java)
    }
}

模块间通信

使用接口定义模块间的通信契约:

// core 模块
interface UserProvider {
    fun getUserInfo(): Flow<User>
    fun updateUser(user: User)
}

// feature_profile 模块实现
@Module
@InstallIn(SingletonComponent::class)
class UserModule {
    @Provides
    @Singleton
    fun provideUserProvider(): UserProvider = UserProviderImpl()
}

这些现代 Android 开发的概念和工具,帮助我们构建更加健壮和可维护的应用。在下一章中,我们将学习如何打包和发布 Android 应用。