Android 开发指南
Android 简介
Android 是 Google 开发的移动操作系统,基于 Linux 内核。
核心特点
- 开源免费:基于 AOSP
- Java/Kotlin:官方支持语言
- 丰富生态:Google Play 和第三方应用商店
- 跨设备:手机、平板、TV、穿戴设备
开发环境
Android Studio
官方 IDE,基于 IntelliJ IDEA。
下载地址:https://developer.android.com/studio
SDK 工具
- SDK Manager:管理 SDK 版本
- AVD Manager:管理模拟器
- Gradle:构建工具
快速开始
创建项目
- 打开 Android Studio
- New Project → Empty Activity
- 配置项目信息
- 选择最低 SDK 版本
- 点击 Finish
项目结构
MyApp/
├── app/
│ ├── src/
│ │ ├── main/
│ │ │ ├── java/ # Java/Kotlin 代码
│ │ │ ├── res/ # 资源文件
│ │ │ │ ├── layout/ # 布局文件
│ │ │ │ ├── values/ # 值资源
│ │ │ │ └── drawable/ # 图片资源
│ │ │ └── AndroidManifest.xml
│ │ └── test/ # 测试代码
│ └── build.gradle # 模块构建配置
├── gradle/
└── build.gradle # 项目构建配置
第一个应用
MainActivity.kt
package com.example.myapp
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Android!"
android:textSize="24sp" />
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="点击我"
android:layout_marginTop="16dp" />
</LinearLayout>
添加点击事件
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val textView = findViewById<TextView>(R.id.textView)
val button = findViewById<Button>(R.id.button)
button.setOnClickListener {
textView.text = "按钮被点击了!"
}
}
}
四大组件
Activity(活动)
应用的单个屏幕。
class SecondActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_second)
}
}
Service(服务)
后台运行的组件。
class MyService : Service() {
override fun onBind(intent: Intent?): IBinder? {
return null
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
// 执行后台任务
return START_STICKY
}
}
BroadcastReceiver(广播接收器)
接收系统或应用广播。
class MyReceiver : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
when (intent?.action) {
Intent.ACTION_BATTERY_LOW -> {
// 电量低
}
}
}
}
ContentProvider(内容提供者)
共享数据。
class MyProvider : ContentProvider() {
override fun onCreate(): Boolean = true
override fun query(...): Cursor? = null
override fun insert(...): Uri? = null
override fun update(...): Int = 0
override fun delete(...): Int = 0
override fun getType(...): String? = null
}
布局
LinearLayout(线性布局)
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:text="Item 1" />
<TextView android:text="Item 2" />
</LinearLayout>
RelativeLayout(相对布局)
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text1"
android:layout_centerInParent="true"
android:text="Center" />
<Button
android:layout_below="@id/text1"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
ConstraintLayout(约束布局)
<androidx.constraintlayout.widget.ConstraintLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/text"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintStart_toStartOf="parent"
android:text="Hello" />
</androidx.constraintlayout.widget.ConstraintLayout>
常用控件
TextView(文本)
<TextView
android:text="Hello"
android:textSize="18sp"
android:textColor="#000000"
android:textStyle="bold" />
EditText(输入框)
<EditText
android:hint="请输入内容"
android:inputType="text"
android:maxLines="1" />
Button(按钮)
<Button
android:text="点击"
android:onClick="onButtonClick" />
ImageView(图片)
<ImageView
android:src="@drawable/image"
android:scaleType="centerCrop" />
RecyclerView(列表)
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
Intent(意图)
显式 Intent
// 启动 Activity
val intent = Intent(this, SecondActivity::class.java)
intent.putExtra("key", "value")
startActivity(intent)
// 接收数据
val value = intent.getStringExtra("key")
隐式 Intent
// 打开网页
val intent = Intent(Intent.ACTION_VIEW, Uri.parse("https://www.google.com"))
startActivity(intent)
// 拨打电话
val intent = Intent(Intent.ACTION_DIAL, Uri.parse("tel:10086"))
startActivity(intent)
// 发送短信
val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:10086"))
intent.putExtra("sms_body", "Hello")
startActivity(intent)
数据存储
SharedPreferences
// 保存
val prefs = getSharedPreferences("MyPrefs", MODE_PRIVATE)
prefs.edit().apply {
putString("name", "张三")
putInt("age", 25)
apply()
}
// 读取
val name = prefs.getString("name", "")
val age = prefs.getInt("age", 0)
文件存储
// 写入
val file = File(filesDir, "data.txt")
file.writeText("Hello Android")
// 读取
val content = file.readText()
SQLite 数据库
class DBHelper(context: Context) : SQLiteOpenHelper(
context, "mydb.db", null, 1
) {
override fun onCreate(db: SQLiteDatabase) {
db.execSQL("""
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT,
age INTEGER
)
""")
}
override fun onUpgrade(db: SQLiteDatabase, oldVersion: Int, newVersion: Int) {
db.execSQL("DROP TABLE IF EXISTS users")
onCreate(db)
}
}
// 使用
val db = DBHelper(this).writableDatabase
db.execSQL("INSERT INTO users VALUES (1, '张三', 25)")
网络请求
OkHttp
val client = OkHttpClient()
val request = Request.Builder()
.url("https://api.example.com/data")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
// 失败
}
override fun onResponse(call: Call, response: Response) {
val data = response.body?.string()
// 处理数据
}
})
Retrofit
interface ApiService {
@GET("users")
suspend fun getUsers(): List<User>
}
val retrofit = Retrofit.Builder()
.baseUrl("https://api.example.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val api = retrofit.create(ApiService::class.java)
权限
AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
运行时权限
// 检查权限
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
// 请求权限
ActivityCompat.requestPermissions(
this,
arrayOf(Manifest.permission.CAMERA),
100
)
}
// 处理结果
override fun onRequestPermissionsResult(
requestCode: Int,
permissions: Array<String>,
grantResults: IntArray
) {
if (requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// 权限已授予
}
}
学习路径
第一阶段:基础(2周)
- Android Studio 使用
- Activity 和布局
- 常用控件
- Intent 和数据传递
第二阶段:进阶(3周)
- Fragment
- RecyclerView
- 数据存储
- 网络请求
第三阶段:高级(4周)
- MVVM 架构
- Jetpack 组件
- Kotlin 协程
- 性能优化
第四阶段:实战(4周)
- 完整项目开发
- 第三方库集成
- 打包发布
- 持续集成