当前位置:首页 > 学习笔记 > 正文内容

Android开发完全指南:现代移动应用开发的核心实践

廖万里18小时前学习笔记0
Android开发完全指南
"Android是全球用户量最大的移动操作系统,掌握Android开发技能意味着能够触达数十亿用户。从Java到Kotlin,从传统开发到Jetpack Compose,Android开发生态正在经历革命性变革。"

一、Android开发现状与趋势

Android自2008年发布以来,已经成为全球市场份额最高的移动操作系统。截至2024年,Android占据了全球移动操作系统市场约70%的份额,活跃设备超过30亿台。这为开发者提供了巨大的用户基础和商业机会。

技术栈演进

Android开发经历了从Java到Kotlin的转变。2017年Google宣布Kotlin成为Android官方开发语言,2019年Kotlin成为首选语言。如今,新项目几乎全部使用Kotlin开发,Kotlin协程、扩展函数、空安全等特性极大提升了开发效率。 声明式UI框架Jetpack Compose的推出,标志着Android UI开发范式的转变。相比传统的XML布局,Compose使用Kotlin代码声明UI,代码更简洁、状态管理更清晰、开发体验更流畅。

二、项目架构最佳实践

现代Android应用推荐使用MVVM架构,结合Jetpack组件实现清晰的分层。

架构组件

// ViewModel:管理UI状态,存活于配置更改
class MainViewModel(
    private val repository: UserRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(UiState.Loading)
    val uiState: StateFlow = _uiState.asStateFlow()
    
    fun loadUsers() {
        viewModelScope.launch {
            repository.getUsers()
                .onSuccess { users ->
                    _uiState.value = UiState.Success(users)
                }
                .onFailure { error ->
                    _uiState.value = UiState.Error(error.message ?: "Unknown error")
                }
        }
    }
}

// 数据层:Repository模式
class UserRepository @Inject constructor(
    private val api: UserApi,
    private val dao: UserDao
) {
    fun getUsers(): Flow>> = flow {
        try {
            val users = api.getUsers()
            dao.insertAll(users)
            emit(Result.success(users))
        } catch (e: Exception) {
            val cached = dao.getAll()
            if (cached.isNotEmpty()) {
                emit(Result.success(cached))
            } else {
                emit(Result.failure(e))
            }
        }
    }
}

依赖注入

// 使用Hilt进行依赖注入
@HiltAndroidApp
class MyApplication : Application()

@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    
    private val viewModel: MainViewModel by viewModels()
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme {
                MainScreen(viewModel = viewModel)
            }
        }
    }
}

@Module
@InstallIn(SingletonComponent::class)
object NetworkModule {
    
    @Provides
    @Singleton
    fun provideOkHttpClient(): OkHttpClient {
        return OkHttpClient.Builder()
            .addInterceptor(LoggingInterceptor())
            .connectTimeout(30, TimeUnit.SECONDS)
            .build()
    }
    
    @Provides
    @Singleton
    fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit {
        return Retrofit.Builder()
            .baseUrl("https://api.example.com/")
            .client(okHttpClient)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
    }
}

三、Jetpack Compose UI开发

Compose是Android现代UI开发的核心,使用声明式编程范式。

基础组件

@Composable
fun UserListScreen(
    viewModel: UserViewModel,
    onUserClick: (User) -> Unit
) {
    val uiState by viewModel.uiState.collectAsState()
    
    when (val state = uiState) {
        is UiState.Loading -> {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                CircularProgressIndicator()
            }
        }
        is UiState.Success -> {
            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                items(state.data) { user ->
                    UserCard(
                        user = user,
                        onClick = { onUserClick(user) }
                    )
                }
            }
        }
        is UiState.Error -> {
            ErrorView(
                message = state.message,
                onRetry = { viewModel.loadUsers() }
            )
        }
    }
}

@Composable
fun UserCard(
    user: User,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable(onClick = onClick),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            AsyncImage(
                model = user.avatar,
                contentDescription = "Avatar",
                modifier = Modifier
                    .size(48.dp)
                    .clip(CircleShape),
                contentScale = ContentScale.Crop
            )
            
            Spacer(modifier = Modifier.width(16.dp))
            
            Column {
                Text(
                    text = user.name,
                    style = MaterialTheme.typography.titleMedium
                )
                Text(
                    text = user.email,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        }
    }
}

状态管理

// 状态提升模式
@Composable
fun SearchScreen(
    searchQuery: String,
    onSearchQueryChange: (String) -> Unit,
    results: List
) {
    Column {
        SearchBar(
            query = searchQuery,
            onQueryChange = onSearchQueryChange,
            modifier = Modifier.fillMaxWidth()
        )
        
        LazyColumn {
            items(results) { user ->
                UserItem(user)
            }
        }
    }
}

// 使用remember和mutableStateOf管理局部状态
@Composable
fun Counter() {
    var count by remember { mutableStateOf(0) }
    
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Text(text = "Count: $count")
        Button(onClick = { count++ }) {
            Text("Increment")
        }
    }
}

四、网络请求与数据持久化

Retrofit网络请求

interface UserApi {
    @GET("users")
    suspend fun getUsers(): List
    
    @GET("users/{id}")
    suspend fun getUser(@Path("id") id: Long): User
    
    @POST("users")
    suspend fun createUser(@Body user: UserRequest): User
    
    @Multipart
    @POST("upload")
    suspend fun uploadFile(@Part file: MultipartBody.Part): UploadResponse
}

// 协程配合网络请求
class UserRepository @Inject constructor(
    private val api: UserApi
) {
    suspend fun getUsers(): Result> = try {
        Result.success(api.getUsers())
    } catch (e: Exception) {
        Result.failure(e)
    }
}

Room数据库

@Entity(tableName = "users")
data class UserEntity(
    @PrimaryKey val id: Long,
    val name: String,
    val email: String,
    val avatar: String?
)

@Dao
interface UserDao {
    @Query("SELECT * FROM users")
    fun getAll(): Flow>
    
    @Query("SELECT * FROM users WHERE id = :id")
    suspend fun getById(id: Long): UserEntity?
    
    @Insert(onConflict = OnConflictStrategy.REPLACE)
    suspend fun insertAll(users: List)
    
    @Delete
    suspend fun delete(user: UserEntity)
}

@Database(entities = [UserEntity::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

五、异步处理与协程

Kotlin协程是Android异步处理的最佳选择,简化了异步代码编写。
// 协程作用域
class MainViewModel : ViewModel() {
    
    // viewModelScope自动绑定ViewModel生命周期
    fun loadData() {
        viewModelScope.launch {
            // 并行请求
            val deferredUsers = async { repository.getUsers() }
            val deferredPosts = async { repository.getPosts() }
            
            val users = deferredUsers.await()
            val posts = deferredPosts.await()
            
            _uiState.value = UiState.Success(Data(users, posts))
        }
    }
}

// 流式数据处理
fun getRecentPosts(): Flow> = channelFlow {
    database.getPosts()
        .collect { posts ->
            val filtered = posts.filter { it.timestamp > Date() - 7.days }
            send(filtered)
        }
}

// 协程异常处理
viewModelScope.launch {
    try {
        val result = repository.riskyOperation()
        handleSuccess(result)
    } catch (e: CancellationException) {
        throw e  // 不要捕获取消异常
    } catch (e: Exception) {
        handleError(e)
    }
}

六、性能优化实践

启动优化

// 使用SplashScreen API
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        val splashScreen = installSplashScreen()
        
        super.onCreate(savedInstanceState)
        
        splashScreen.setKeepOnScreenCondition {
            viewModel.isLoading.value
        }
        
        setContent {
            MyAppTheme {
                MainScreen()
            }
        }
    }
}

// 延迟初始化
class MyApp : Application() {
    override fun onCreate() {
        super.onCreate()
        
        // 核心组件立即初始化
        initCoreComponents()
        
        // 非核心组件延迟初始化
        WorkManager.getInstance(this).enqueue(
            OneTimeWorkRequestBuilder().build()
        )
    }
}

内存优化

// 使用WeakReference避免内存泄漏
class ImageLoader(context: Context) {
    private val context = context.applicationContext
    private val cache = LruCache((Runtime.getRuntime().maxMemory() / 8).toInt())
    
    fun load(url: String, imageView: ImageView) {
        val bitmap = cache.get(url)
        if (bitmap != null) {
            imageView.setImageBitmap(bitmap)
            return
        }
        
        // 异步加载
        CoroutineScope(Dispatchers.IO).launch {
            val loaded = downloadBitmap(url)
            cache.put(url, loaded)
            withContext(Dispatchers.Main) {
                imageView.setImageBitmap(loaded)
            }
        }
    }
}

// 避免在Activity中使用静态变量持有Context
// 错误示例
companion object {
    private var context: Context? = null  // 内存泄漏!
}

// 正确做法
companion object {
    private var weakContext: WeakReference? = null
}

七、安全最佳实践

// 使用EncryptedSharedPreferences存储敏感数据
val masterKey = MasterKey.Builder(context)
    .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)
    .build()

val sharedPreferences = EncryptedSharedPreferences.create(
    context,
    "secret_shared_prefs",
    masterKey,
    EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,
    EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM
)

// 网络安全配置
// network_security_config.xml


    
        api.example.com
        
            base64EncodedPin=
        
    

总结

Android开发生态正在快速演进,掌握现代Android开发需要学习Kotlin、Jetpack Compose、协程等新技术。推荐采用MVVM架构,使用Jetpack组件构建可维护的应用。注重性能优化和安全实践,为用户提供流畅、安全的体验。 持续关注Android官方文档和最佳实践,保持技术栈更新,是成为优秀Android开发者的关键。

本文链接:https://www.kkkliao.cn/?id=848 转载需授权!

分享到:

版权声明:本文由廖万里的博客发布,如需转载请注明出处。


发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。