platform

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Android Platform Skill

Android平台技能

Quick Start

快速入门

Activity Lifecycle

Activity生命周期

kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // Cleanup
    }
}
kotlin
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // Cleanup
    }
}

Fragment Usage

Fragment使用

kotlin
class UserFragment : Fragment() {
    private val viewModel: UserViewModel by viewModels()
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.user.observe(viewLifecycleOwner) { user ->
            updateUI(user)
        }
    }
}
kotlin
class UserFragment : Fragment() {
    private val viewModel: UserViewModel by viewModels()
    
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel.user.observe(viewLifecycleOwner) { user ->
            updateUI(user)
        }
    }
}

Key Concepts

核心概念

Lifecycle Callbacks

生命周期回调

  • onCreate()
    : Initial setup
  • onStart()
    : Become visible
  • onResume()
    : Gain focus
  • onPause()
    : Lose focus
  • onStop()
    : Hidden
  • onDestroy()
    : Final cleanup
  • onCreate()
    : 初始设置
  • onStart()
    : 变为可见
  • onResume()
    : 获取焦点
  • onPause()
    : 失去焦点
  • onStop()
    : 被隐藏
  • onDestroy()
    : 最终清理

Fragment Lifecycle

Fragment生命周期

Similar to Activity but with:
  • onAttach()
    : Attached to activity
  • onDetach()
    : Detached
  • Fragment manager for transactions
与Activity类似,但包含:
  • onAttach()
    : 依附到Activity
  • onDetach()
    : 解除依附
  • 用于事务的Fragment管理器

Intent System

Intent系统

kotlin
// Explicit
startActivity(Intent(this, DetailActivity::class.java))

// Implicit
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com")))
kotlin
// Explicit
startActivity(Intent(this, DetailActivity::class.java))

// Implicit
startActivity(Intent(Intent.ACTION_VIEW, Uri.parse("https://example.com")))

Services

Service

  • Started:
    startService()
  • Bound:
    bindService()
  • Foreground: Visible notification
  • 启动型:
    startService()
  • 绑定型:
    bindService()
  • 前台型:显示通知

Best Practices

最佳实践

✅ Handle lifecycle properly ✅ Use ViewModel for state ✅ Unregister listeners ✅ Test configuration changes ✅ Respect process lifecycle
✅ 正确处理生命周期 ✅ 使用ViewModel管理状态 ✅ 注销监听器 ✅ 测试配置变更 ✅ 遵循进程生命周期

Resources

资源