目录
引言
在Android开发中,四大组件(Activity、Service、BroadcastReceiver、ContentProvider)构成了应用程序的骨架。理解它们的工作原理和使用方式是每个Android开发者的必备技能。本文将深入探讨这四大组件,并通过Kotlin代码示例展示实际应用。
1. Activity:用户交互的核心
1.1 基础概念与生命周期
Activity是Android应用中最基本的用户界面组件,每个屏幕界面通常对应一个Activity。
生命周期图示:
onCreate() → onStart() → onResume() → Running
↑ ↓ ↓
onRestart() ← onStop() ← onPause()
↓
onDestroy()
1.2 Kotlin代码示例
基础Activity实现
class MainActivity : AppCompatActivity() {
companion object {
private const val REQUEST_CODE = 1001
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// 恢复保存的状态
savedInstanceState?.getString("key")?.let {
// 处理恢复的数据
}
// 启动另一个Activity
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
val intent = Intent(this, SecondActivity::class.java).apply {
putExtra("message", "Hello from MainActivity!")
}
startActivity(intent)
}
// 使用Activity Result API(替代startActivityForResult)
val resultLauncher = registerForActivityResult(
ActivityResultContracts.StartActivityForResult()
) {
result ->
if (result.resultCode == RESULT_OK) {
val data = result.data?.getStringExtra("result")
// 处理返回结果
}
}
}
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
outState.putString("key", "value")
}
override fun onResume() {
super.onResume()
// 恢复资源、注册监听器等
}
override fun onPause() {
super.onPause()
// 释放资源、保存数据等
}
}
启动模式示例
// AndroidManifest.xml中的配置示例
/*
<activity
android:name=".StandardActivity"
android:launchMode="standard" />
<activity
android:name=".SingleTopActivity"
android:launchMode="singleTop" />
<activity
android:name=".SingleTaskActivity"
android:launchMode="singleTask"
android:taskAffinity="com.example.customTask" />
<activity
android:name=".SingleInstanceActivity"
android:launchMode="singleInstance" />
*/
class SingleTopActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_single_top)
}
// 当Activity已存在且位于栈顶时调用
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
// 处理新的Intent
intent?.getStringExtra("data")?.let {
updateUI(it)
}
}
private fun updateUI(data: String) {
// 更新界面
}
}
2. Service:后台执行的利器
2.1 Service的类型与生命周期
两种主要类型:
- Started Service:通过startService()启动,独立运行
- Bound Service:通过bindService()绑定,提供客户端-服务器接口
Kotlin代码示例
基础Service实现
class MyService : Service() {
private lateinit var notificationManager: NotificationManager
private val serviceChannelId = "service_channel"
override fun onCreate() {
super.onCreate()
notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
createNotificationChannel()
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// 执行后台任务
performBackgroundTask()
// 创建前台服务通知
val notification = NotificationCompat.Builder(this, serviceChannelId)
.setContentTitle("服务运行中")
.setContentText("正在执行后台任务...")
.setSmallIcon(R.drawable.ic_service)
.build()
// 启动为前台服务(Android 9+需要权限)
startForeground(1, notification)
return START_STICKY // 服务被终止后会自动重启
}
override fun onBind(intent: Intent?): IBinder? {
// 返回Binder实例用于绑定服务
return MyBinder()
}
inner class MyBinder : Binder() {
fun getService(): MyService = this@MyService
}
private fun performBackgroundTask() {
// 执行耗时操作
Thread {
// 模拟耗时任务
Thread.sleep(5000)
// 使用Handler或LiveData通知UI更新
Handler(Looper.getMainLooper()).post {
// 更新UI
}
}.start()
}
private fun createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(
serviceChannelId,
"Service Channel",
NotificationManager.IMPORTANCE_LOW
).apply {
description = "Channel for service notifications"
}
notificationManager.createNotificationChannel(channel)
}
}
override fun onDestroy() {
super.onDestroy()
// 清理资源
}
}
Service启动与管理
class ServiceActivity : AppCompatActivity() {
private lateinit var serviceIntent: Intent
private var isBound = false
private lateinit var myService: MyService
private val connection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
val binder = service as MyService.MyBinder
myService = binder.getService()
isBound = true
// 可以调用服务的方法
}
override fun onServiceDisconnected(name: ComponentName?) {
isBound = false
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_service)
serviceIntent = Intent(this, MyService::class

最低0.47元/天 解锁文章
2591

被折叠的 条评论
为什么被折叠?



