# 系统API

系统API是Android平台提供的系统级服务接口，用于访问系统功能、管理权限、获取系统信息等。本文档介绍Android系统API的使用方法。

## 目录

- [系统服务API](#系统服务api)
- [系统权限API](#系统权限api)
- [系统功能API](#系统功能api)
- [系统版本API](#系统版本api)

---

## 系统服务API

### 1. ActivityManager

ActivityManager用于管理Activity和任务栈。

#### 获取ActivityManager

```java
// 获取ActivityManager实例
ActivityManager activityManager = (ActivityManager) 
    getSystemService(Context.ACTIVITY_SERVICE);
```

#### 常用方法

```java
// 获取运行中的应用列表
List<ActivityManager.RunningAppProcessInfo> runningApps = 
    activityManager.getRunningAppProcesses();

// 获取内存信息
ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(memoryInfo);
long totalMemory = memoryInfo.totalMem;
long availableMemory = memoryInfo.availMem;
boolean lowMemory = memoryInfo.lowMemory;

// 获取任务栈信息
List<ActivityManager.RunningTaskInfo> runningTasks = 
    activityManager.getRunningTasks(10);

// 获取应用任务信息
List<ActivityManager.AppTask> appTasks = 
    activityManager.getAppTasks();
```

#### 使用示例

```kotlin
class SystemInfoActivity : AppCompatActivity() {
    private lateinit var activityManager: ActivityManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_system_info)
        
        activityManager = getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
        
        // 获取内存信息
        val memoryInfo = ActivityManager.MemoryInfo()
        activityManager.getMemoryInfo(memoryInfo)
        
        val totalMemoryMB = memoryInfo.totalMem / (1024 * 1024)
        val availableMemoryMB = memoryInfo.availMem / (1024 * 1024)
        
        Log.d("Memory", "总内存: ${totalMemoryMB}MB")
        Log.d("Memory", "可用内存: ${availableMemoryMB}MB")
        Log.d("Memory", "低内存: ${memoryInfo.lowMemory}")
    }
}
```

### 2. WindowManager

WindowManager用于管理窗口和显示。

#### 获取WindowManager

```java
WindowManager windowManager = (WindowManager) 
    getSystemService(Context.WINDOW_SERVICE);
```

#### 常用方法

```java
// 获取默认显示信息
Display display = windowManager.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);

int width = metrics.widthPixels;
int height = metrics.heightPixels;
float density = metrics.density;
int densityDpi = metrics.densityDpi;

// 添加窗口
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.WRAP_CONTENT,
    WindowManager.LayoutParams.TYPE_APPLICATION,
    WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
    PixelFormat.TRANSLUCENT
);
windowManager.addView(view, params);

// 移除窗口
windowManager.removeView(view);
```

#### 使用示例

```kotlin
class WindowManagerActivity : AppCompatActivity() {
    private lateinit var windowManager: WindowManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_window_manager)
        
        windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
        
        // 获取屏幕信息
        val display = windowManager.defaultDisplay
        val metrics = DisplayMetrics()
        display.getMetrics(metrics)
        
        Log.d("Display", "屏幕宽度: ${metrics.widthPixels}px")
        Log.d("Display", "屏幕高度: ${metrics.heightPixels}px")
        Log.d("Display", "屏幕密度: ${metrics.density}")
        Log.d("Display", "DPI: ${metrics.densityDpi}")
    }
}
```

### 3. NotificationManager

NotificationManager用于管理通知。

#### 获取NotificationManager

```java
NotificationManager notificationManager = (NotificationManager) 
    getSystemService(Context.NOTIFICATION_SERVICE);
```

#### 创建通知渠道（Android 8.0+）

```java
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String channelId = "my_channel_id";
    String channelName = "My Channel";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    
    NotificationChannel channel = new NotificationChannel(
        channelId, channelName, importance
    );
    channel.setDescription("Channel description");
    
    notificationManager.createNotificationChannel(channel);
}
```

#### 发送通知

```java
// 创建通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(
    context, "my_channel_id"
)
    .setSmallIcon(R.drawable.ic_notification)
    .setContentTitle("通知标题")
    .setContentText("通知内容")
    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
    .setAutoCancel(true);

// 发送通知
int notificationId = 1;
notificationManager.notify(notificationId, builder.build());

// 取消通知
notificationManager.cancel(notificationId);
```

#### 使用示例

```kotlin
class NotificationActivity : AppCompatActivity() {
    private lateinit var notificationManager: NotificationManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notification)
        
        notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) 
            as NotificationManager
        
        // 创建通知渠道（Android 8.0+）
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            val channel = NotificationChannel(
                "my_channel_id",
                "My Channel",
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = "Channel description"
            }
            notificationManager.createNotificationChannel(channel)
        }
        
        // 发送通知
        button.setOnClickListener {
            showNotification()
        }
    }
    
    private fun showNotification() {
        val builder = NotificationCompat.Builder(this, "my_channel_id")
            .setSmallIcon(R.drawable.ic_notification)
            .setContentTitle("通知标题")
            .setContentText("通知内容")
            .setPriority(NotificationCompat.PRIORITY_DEFAULT)
            .setAutoCancel(true)
        
        notificationManager.notify(1, builder.build())
    }
}
```

### 4. LocationManager

LocationManager用于管理位置服务。

#### 获取LocationManager

```java
LocationManager locationManager = (LocationManager) 
    getSystemService(Context.LOCATION_SERVICE);
```

#### 检查位置服务是否可用

```java
boolean isGpsEnabled = locationManager.isProviderEnabled(
    LocationManager.GPS_PROVIDER
);
boolean isNetworkEnabled = locationManager.isProviderEnabled(
    LocationManager.NETWORK_PROVIDER
);
```

#### 请求位置更新

```java
// 检查权限
if (ContextCompat.checkSelfPermission(this, 
        Manifest.permission.ACCESS_FINE_LOCATION) 
    != PackageManager.PERMISSION_GRANTED) {
    // 请求权限
    return;
}

// 请求位置更新
LocationListener locationListener = new LocationListener() {
    @Override
    public void onLocationChanged(Location location) {
        double latitude = location.getLatitude();
        double longitude = location.getLongitude();
        float accuracy = location.getAccuracy();
    }
    
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {}
    
    @Override
    public void onProviderEnabled(String provider) {}
    
    @Override
    public void onProviderDisabled(String provider) {}
};

locationManager.requestLocationUpdates(
    LocationManager.GPS_PROVIDER,
    1000, // 最小时间间隔（毫秒）
    10,   // 最小距离（米）
    locationListener
);

// 停止位置更新
locationManager.removeUpdates(locationListener);
```

#### 使用示例

```kotlin
class LocationActivity : AppCompatActivity() {
    private lateinit var locationManager: LocationManager
    private lateinit var locationListener: LocationListener
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_location)
        
        locationManager = getSystemService(Context.LOCATION_SERVICE) 
            as LocationManager
        
        locationListener = object : LocationListener {
            override fun onLocationChanged(location: Location) {
                val latitude = location.latitude
                val longitude = location.longitude
                val accuracy = location.accuracy
                
                Log.d("Location", "纬度: $latitude, 经度: $longitude, 精度: $accuracy")
            }
            
            override fun onStatusChanged(provider: String?, status: Int, extras: Bundle?) {}
            override fun onProviderEnabled(provider: String) {}
            override fun onProviderDisabled(provider: String) {}
        }
        
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, 
                Manifest.permission.ACCESS_FINE_LOCATION) 
            == PackageManager.PERMISSION_GRANTED) {
            startLocationUpdates()
        } else {
            // 请求权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(Manifest.permission.ACCESS_FINE_LOCATION),
                REQUEST_LOCATION_PERMISSION
            )
        }
    }
    
    private fun startLocationUpdates() {
        locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER,
            1000L,
            10f,
            locationListener
        )
    }
    
    override fun onDestroy() {
        super.onDestroy()
        locationManager.removeUpdates(locationListener)
    }
    
    companion object {
        private const val REQUEST_LOCATION_PERMISSION = 100
    }
}
```

### 5. TelephonyManager

TelephonyManager用于访问电话相关信息。

#### 获取TelephonyManager

```java
TelephonyManager telephonyManager = (TelephonyManager) 
    getSystemService(Context.TELEPHONY_SERVICE);
```

#### 常用方法

```java
// 获取设备ID（需要READ_PHONE_STATE权限）
String deviceId = telephonyManager.getDeviceId();

// 获取SIM卡信息
String simSerialNumber = telephonyManager.getSimSerialNumber();
String simOperatorName = telephonyManager.getSimOperatorName();
String networkOperatorName = telephonyManager.getNetworkOperatorName();

// 获取网络类型
int networkType = telephonyManager.getNetworkType();
// NETWORK_TYPE_LTE, NETWORK_TYPE_UMTS, etc.

// 检查电话功能
boolean isPhone = telephonyManager.getPhoneType() != 
    TelephonyManager.PHONE_TYPE_NONE;
```

#### 使用示例

```kotlin
class TelephonyActivity : AppCompatActivity() {
    private lateinit var telephonyManager: TelephonyManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_telephony)
        
        telephonyManager = getSystemService(Context.TELEPHONY_SERVICE) 
            as TelephonyManager
        
        // 检查权限
        if (ContextCompat.checkSelfPermission(this, 
                Manifest.permission.READ_PHONE_STATE) 
            == PackageManager.PERMISSION_GRANTED) {
            getTelephonyInfo()
        }
    }
    
    private fun getTelephonyInfo() {
        val deviceId = telephonyManager.deviceId
        val simOperatorName = telephonyManager.simOperatorName
        val networkOperatorName = telephonyManager.networkOperatorName
        val networkType = telephonyManager.networkType
        
        Log.d("Telephony", "设备ID: $deviceId")
        Log.d("Telephony", "SIM运营商: $simOperatorName")
        Log.d("Telephony", "网络运营商: $networkOperatorName")
        Log.d("Telephony", "网络类型: $networkType")
    }
}
```

### 6. PowerManager

PowerManager用于管理电源和唤醒锁。

#### 获取PowerManager

```java
PowerManager powerManager = (PowerManager) 
    getSystemService(Context.POWER_SERVICE);
```

#### 唤醒锁

```java
// 获取唤醒锁
PowerManager.WakeLock wakeLock = powerManager.newWakeLock(
    PowerManager.PARTIAL_WAKE_LOCK,
    "MyApp::MyWakeLock"
);

// 获取唤醒锁
wakeLock.acquire();

// 释放唤醒锁
wakeLock.release();

// 检查是否持有唤醒锁
boolean isHeld = wakeLock.isHeld();
```

#### 使用示例

```kotlin
class PowerManagerActivity : AppCompatActivity() {
    private lateinit var powerManager: PowerManager
    private var wakeLock: PowerManager.WakeLock? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_power_manager)
        
        powerManager = getSystemService(Context.POWER_SERVICE) as PowerManager
        
        // 创建唤醒锁
        wakeLock = powerManager.newWakeLock(
            PowerManager.PARTIAL_WAKE_LOCK,
            "MyApp::MyWakeLock"
        )
    }
    
    private fun acquireWakeLock() {
        wakeLock?.acquire(10 * 60 * 1000L) // 10分钟超时
    }
    
    private fun releaseWakeLock() {
        wakeLock?.let {
            if (it.isHeld) {
                it.release()
            }
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        releaseWakeLock()
    }
}
```

---

## 系统权限API

### 1. 权限检查

#### 检查权限

```java
// 检查单个权限
int result = ContextCompat.checkSelfPermission(
    context,
    Manifest.permission.CAMERA
);

boolean hasPermission = result == PackageManager.PERMISSION_GRANTED;

// 检查多个权限
String[] permissions = {
    Manifest.permission.CAMERA,
    Manifest.permission.READ_EXTERNAL_STORAGE
};

int[] results = new int[permissions.length];
for (int i = 0; i < permissions.length; i++) {
    results[i] = ContextCompat.checkSelfPermission(
        context,
        permissions[i]
    );
}
```

#### 使用示例

```kotlin
class PermissionActivity : AppCompatActivity() {
    private fun checkPermission(permission: String): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            permission
        ) == PackageManager.PERMISSION_GRANTED
    }
    
    private fun checkPermissions(permissions: Array<String>): Boolean {
        return permissions.all { checkPermission(it) }
    }
}
```

### 2. 权限申请

#### 请求权限

```java
// 请求单个权限
ActivityCompat.requestPermissions(
    activity,
    new String[]{Manifest.permission.CAMERA},
    REQUEST_CODE_CAMERA
);

// 请求多个权限
ActivityCompat.requestPermissions(
    activity,
    new String[]{
        Manifest.permission.CAMERA,
        Manifest.permission.READ_EXTERNAL_STORAGE
    },
    REQUEST_CODE_PERMISSIONS
);

// 处理权限结果
@Override
public void onRequestPermissionsResult(
    int requestCode,
    @NonNull String[] permissions,
    @NonNull int[] grantResults
) {
    if (requestCode == REQUEST_CODE_CAMERA) {
        if (grantResults.length > 0 && 
            grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // 权限已授予
        } else {
            // 权限被拒绝
        }
    }
}
```

#### 使用示例

```kotlin
class PermissionActivity : AppCompatActivity() {
    companion object {
        private const val REQUEST_CODE_CAMERA = 100
        private const val REQUEST_CODE_PERMISSIONS = 101
    }
    
    private fun requestPermission(permission: String, requestCode: Int) {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(permission),
            requestCode
        )
    }
    
    private fun requestPermissions(permissions: Array<String>, requestCode: Int) {
        ActivityCompat.requestPermissions(
            this,
            permissions,
            requestCode
        )
    }
    
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        
        when (requestCode) {
            REQUEST_CODE_CAMERA -> {
                if (grantResults.isNotEmpty() && 
                    grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 权限已授予
                    openCamera()
                } else {
                    // 权限被拒绝
                    showPermissionDeniedMessage()
                }
            }
        }
    }
}
```

### 3. 权限说明

#### 显示权限说明

```java
// 检查是否需要显示权限说明
if (ActivityCompat.shouldShowRequestPermissionRationale(
        activity,
        Manifest.permission.CAMERA)) {
    // 显示说明对话框
    showPermissionRationale();
} else {
    // 直接请求权限
    ActivityCompat.requestPermissions(
        activity,
        new String[]{Manifest.permission.CAMERA},
        REQUEST_CODE_CAMERA
    );
}
```

#### 使用示例

```kotlin
class PermissionActivity : AppCompatActivity() {
    private fun requestPermissionWithRationale(permission: String, requestCode: Int) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(this, permission)) {
            // 显示说明对话框
            MaterialAlertDialogBuilder(this)
                .setTitle("需要权限")
                .setMessage("此功能需要相机权限才能使用")
                .setPositiveButton("确定") { _, _ ->
                    ActivityCompat.requestPermissions(
                        this,
                        arrayOf(permission),
                        requestCode
                    )
                }
                .setNegativeButton("取消", null)
                .show()
        } else {
            // 直接请求权限
            ActivityCompat.requestPermissions(
                this,
                arrayOf(permission),
                requestCode
            )
        }
    }
}
```

---

## 系统功能API

### 1. 文件系统API

#### 访问外部存储

```java
// 检查外部存储是否可用
boolean isExternalStorageAvailable = Environment.getExternalStorageState()
    .equals(Environment.MEDIA_MOUNTED);

// 获取外部存储目录
File externalStorageDir = Environment.getExternalStorageDirectory();
File downloadsDir = Environment.getExternalStoragePublicDirectory(
    Environment.DIRECTORY_DOWNLOADS
);

// 获取应用专用外部存储目录
File appExternalDir = getExternalFilesDir(null);
File appPicturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
```

#### 使用示例

```kotlin
class FileSystemActivity : AppCompatActivity() {
    private fun getExternalStorageInfo() {
        // 检查外部存储状态
        val state = Environment.getExternalStorageState()
        val isAvailable = state == Environment.MEDIA_MOUNTED
        
        if (isAvailable) {
            // 获取外部存储目录
            val externalStorageDir = Environment.getExternalStorageDirectory()
            val downloadsDir = Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_DOWNLOADS
            )
            
            // 获取应用专用目录
            val appExternalDir = getExternalFilesDir(null)
            val appPicturesDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)
            
            Log.d("Storage", "外部存储: ${externalStorageDir.absolutePath}")
            Log.d("Storage", "下载目录: ${downloadsDir.absolutePath}")
            Log.d("Storage", "应用外部目录: ${appExternalDir?.absolutePath}")
        }
    }
}
```

### 2. 网络API

#### 检查网络连接

```java
ConnectivityManager connectivityManager = (ConnectivityManager) 
    getSystemService(Context.CONNECTIVITY_SERVICE);

// 检查网络连接
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isConnected = networkInfo != null && networkInfo.isConnected();

// 获取网络类型
int networkType = networkInfo.getType();
// ConnectivityManager.TYPE_WIFI
// ConnectivityManager.TYPE_MOBILE
```

#### 使用示例

```kotlin
class NetworkActivity : AppCompatActivity() {
    private lateinit var connectivityManager: ConnectivityManager
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_network)
        
        connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) 
            as ConnectivityManager
        
        checkNetworkConnection()
    }
    
    private fun checkNetworkConnection() {
        val networkInfo = connectivityManager.activeNetworkInfo
        val isConnected = networkInfo != null && networkInfo.isConnected
        
        if (isConnected) {
            val networkType = networkInfo.type
            when (networkType) {
                ConnectivityManager.TYPE_WIFI -> {
                    Log.d("Network", "WiFi连接")
                }
                ConnectivityManager.TYPE_MOBILE -> {
                    Log.d("Network", "移动网络连接")
                }
            }
        } else {
            Log.d("Network", "无网络连接")
        }
    }
}
```

### 3. 传感器API

#### 使用传感器

```java
SensorManager sensorManager = (SensorManager) 
    getSystemService(Context.SENSOR_SERVICE);

// 获取传感器
Sensor accelerometer = sensorManager.getDefaultSensor(
    Sensor.TYPE_ACCELEROMETER
);

// 注册传感器监听器
SensorEventListener listener = new SensorEventListener() {
    @Override
    public void onSensorChanged(SensorEvent event) {
        float x = event.values[0];
        float y = event.values[1];
        float z = event.values[2];
    }
    
    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {}
};

sensorManager.registerListener(
    listener,
    accelerometer,
    SensorManager.SENSOR_DELAY_NORMAL
);

// 取消注册
sensorManager.unregisterListener(listener);
```

#### 使用示例

```kotlin
class SensorActivity : AppCompatActivity() {
    private lateinit var sensorManager: SensorManager
    private var accelerometer: Sensor? = null
    private val sensorListener = object : SensorEventListener {
        override fun onSensorChanged(event: SensorEvent) {
            val x = event.values[0]
            val y = event.values[1]
            val z = event.values[2]
            
            Log.d("Sensor", "X: $x, Y: $y, Z: $z")
        }
        
        override fun onAccuracyChanged(sensor: Sensor?, accuracy: Int) {}
    }
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sensor)
        
        sensorManager = getSystemService(Context.SENSOR_SERVICE) as SensorManager
        accelerometer = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER)
    }
    
    override fun onResume() {
        super.onResume()
        accelerometer?.let {
            sensorManager.registerListener(
                sensorListener,
                it,
                SensorManager.SENSOR_DELAY_NORMAL
            )
        }
    }
    
    override fun onPause() {
        super.onPause()
        sensorManager.unregisterListener(sensorListener)
    }
}
```

---

## 系统版本API

### 1. 获取系统版本信息

#### 系统版本

```java
// 获取Android版本号
int sdkVersion = Build.VERSION.SDK_INT;
String sdkVersionName = Build.VERSION.RELEASE; // "13", "12", etc.

// 获取设备信息
String manufacturer = Build.MANUFACTURER; // "Samsung", "Google", etc.
String model = Build.MODEL; // "Pixel 6", "Galaxy S21", etc.
String brand = Build.BRAND; // "google", "samsung", etc.
String device = Build.DEVICE; // "oriole", "o1q", etc.
String product = Build.PRODUCT; // "oriole", "o1q", etc.
```

#### 使用示例

```kotlin
class SystemVersionActivity : AppCompatActivity() {
    private fun getSystemVersionInfo() {
        // Android版本
        val sdkVersion = Build.VERSION.SDK_INT
        val sdkVersionName = Build.VERSION.RELEASE
        
        // 设备信息
        val manufacturer = Build.MANUFACTURER
        val model = Build.MODEL
        val brand = Build.BRAND
        val device = Build.DEVICE
        val product = Build.PRODUCT
        
        Log.d("System", "SDK版本: $sdkVersion")
        Log.d("System", "Android版本: $sdkVersionName")
        Log.d("System", "制造商: $manufacturer")
        Log.d("System", "型号: $model")
        Log.d("System", "品牌: $brand")
        Log.d("System", "设备: $device")
        Log.d("System", "产品: $product")
    }
}
```

### 2. 版本检查

#### 检查Android版本

```java
// 检查Android版本
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    // Android 8.0及以上
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
    // Android 9.0及以上
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
    // Android 10及以上
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
    // Android 11及以上
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
    // Android 12及以上
}

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
    // Android 13及以上
}
```

#### 使用示例

```kotlin
class VersionCheckActivity : AppCompatActivity() {
    private fun checkAndroidVersion() {
        when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU -> {
                // Android 13+
                Log.d("Version", "Android 13或更高版本")
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.S -> {
                // Android 12+
                Log.d("Version", "Android 12或更高版本")
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                // Android 11+
                Log.d("Version", "Android 11或更高版本")
            }
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q -> {
                // Android 10+
                Log.d("Version", "Android 10或更高版本")
            }
            else -> {
                Log.d("Version", "Android 10以下版本")
            }
        }
    }
    
    private fun useNewFeature() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            // 使用Android 8.0+的新特性
            useNotificationChannel()
        } else {
            // 使用旧版本API
            useOldNotification()
        }
    }
}
```

### 3. 应用版本信息

#### 获取应用版本

```java
try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(
        getPackageName(),
        0
    );
    
    String versionName = packageInfo.versionName; // "1.0.0"
    int versionCode = packageInfo.versionCode; // 1
    String packageName = packageInfo.packageName; // "com.example.app"
    
} catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}
```

#### 使用示例

```kotlin
class AppVersionActivity : AppCompatActivity() {
    private fun getAppVersionInfo() {
        try {
            val packageInfo = packageManager.getPackageInfo(
                packageName,
                0
            )
            
            val versionName = packageInfo.versionName
            val versionCode = packageInfo.longVersionCode // API 28+
            val packageName = packageInfo.packageName
            
            Log.d("App", "版本名称: $versionName")
            Log.d("App", "版本代码: $versionCode")
            Log.d("App", "包名: $packageName")
            
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
    }
}
```

---

## 总结

系统API提供了访问Android系统功能和信息的能力：

1. **系统服务API**：ActivityManager、WindowManager、NotificationManager等
2. **系统权限API**：权限检查、申请和处理
3. **系统功能API**：文件系统、网络、传感器等
4. **系统版本API**：获取系统和应用版本信息

使用系统API时需要注意：
- 申请必要的权限
- 检查系统版本兼容性
- 正确处理生命周期
- 及时释放资源

通过合理使用系统API，可以构建功能强大的Android应用。
