Android 游戏开发实战指南:从零起步如何克服性能优化难题与跨机型适配挑战

引言:Android 游戏开发的机遇与挑战
Android 游戏开发是一个充满活力但也极具挑战的领域。根据 Google Play 的数据,Android 设备在全球拥有超过 30 亿活跃用户,这为游戏开发者提供了巨大的市场潜力。然而,Android 生态系统的碎片化问题——从低端入门机到高端旗舰机,从不同厂商的定制系统到各种屏幕尺寸和分辨率——给开发者带来了性能优化和跨机型适配的双重挑战。
本文将从零起步,系统性地讲解如何克服这些挑战。我们将深入探讨性能优化的核心原则、跨机型适配的实用策略,并通过完整的代码示例来展示具体实现方法。无论你是刚入门的开发者还是有经验的游戏程序员,这篇指南都将为你提供可操作的解决方案。
第一部分:Android 游戏开发基础架构
1.1 理解 Android 游戏的运行环境
在开始优化之前,我们需要理解 Android 游戏的运行环境。Android 游戏通常运行在 Java 虚拟机(JVM)或 Android Runtime(ART)之上,这意味着我们需要关注内存管理、线程调度和图形渲染管线。
关键概念:
主线程(UI 线程)
:负责处理用户输入和 UI 更新,任何耗时操作都会导致界面卡顿
渲染线程
:负责图形绘制,通常与主线程分离
游戏循环(Game Loop)
:游戏的核心,负责更新游戏状态和渲染
1.2 选择合适的游戏引擎
对于从零起步的开发者,选择合适的游戏引擎至关重要。以下是主流选择:
Unity
:功能强大,跨平台支持好,但包体积较大
LibGDX
:轻量级,Java 开发,适合 2D 游戏
Godot
:开源,GDScript 语言,学习曲线平缓
自研引擎
:完全控制,但开发成本高
代码示例:LibGDX 基础游戏结构
public class MyGame extends ApplicationAdapter {
SpriteBatch batch;
Texture texture;

@Override
public void create() {
batch = new SpriteBatch();
texture = new Texture(“player.png”); // 加载纹理
}

@Override
public void render() {
// 清屏
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

// 游戏逻辑更新
update();

// 渲染
batch.begin();
batch.draw(texture, x, y);
batch.end();
}

@Override
public void dispose() {
batch.dispose();
texture.dispose(); // 释放资源
}

private void update() {
// 游戏状态更新逻辑
}
}
第二部分:性能优化难题的系统性解决方案
2.1 内存优化:避免 OOM 和频繁 GC
Android 设备的内存限制严格,游戏开发中常见的内存问题包括纹理过大、对象频繁创建和资源泄漏。
2.1.1 纹理内存优化
问题分析
:一张 1024×1024 的 RGBA8888 纹理占用内存 = 1024 × 1024 × 4 = 4MB。如果游戏有 20 张这样的纹理,仅纹理就占用 80MB 内存。
优化策略
:
纹理压缩
:使用 ETC2、ASTC 等压缩格式
纹理图集(Texture Atlas)
:减少 Draw Call
动态加载与卸载
:按需加载资源
代码示例:纹理压缩与加载
// 使用 LibGDX 的纹理压缩工具
public class TextureManager {
private ObjectMap textures = new ObjectMap<>();

// 加载压缩纹理
public void loadCompressedTexture(String name, String path) {
// 使用 Pixmap 加载并压缩
Pixmap pixmap = new Pixmap(Gdx.files.internal(path));
Pixmap compressed = compressPixmap(pixmap);

Texture texture = new Texture(compressed);
textures.put(name, texture);

pixmap.dispose();
compressed.dispose();
}

private Pixmap compressPixmap(Pixmap original) {
// 简单的压缩示例:降低颜色深度
int width = original.getWidth();
int height = original.getHeight();
Pixmap compressed = new Pixmap(width, height, Pixmap.Format.RGB565);

for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { int color = original.getPixel(x, y); // 提取 RGB 并量化 int r = ((color >> 24) & 0xFF) >> 3;
int g = ((color >> 16) & 0xFF) >> 2;
int b = ((color >> 8) & 0xFF) >> 3;
int newColor = (r << 11) | (g << 5) | b; compressed.drawPixel(x, y, newColor); } } return compressed; } public void unloadTexture(String name) { if (textures.containsKey(name)) { textures.get(name).dispose(); textures.remove(name); } } } 2.1.2 对象池模式减少 GC 压力 频繁创建和销毁对象会触发垃圾回收,导致游戏卡顿。对象池模式可以重用对象,减少 GC 频率。 代码示例:对象池实现 public class GameObjectPool {
private final Supplier factory;
private final Queue pool;
private final int maxSize;

public GameObjectPool(Supplier factory, int initialSize, int maxSize) {
this.factory = factory;
this.pool = new ArrayDeque<>(initialSize);
this.maxSize = maxSize;

// 预创建对象
for (int i = 0; i < initialSize; i++) { pool.offer(factory.get()); } } public T obtain() { T obj = pool.poll(); if (obj == null) { obj = factory.get(); } return obj; } public void free(T obj) { if (pool.size() < maxSize) { pool.offer(obj); } } } // 使用示例:子弹对象池 public class Bullet { public float x, y, vx, vy; public boolean active; public void reset() { x = y = vx = vy = 0; active = false; } } // 在游戏初始化时创建子弹池 GameObjectPool bulletPool = new GameObjectPool<>(
() -> new Bullet(), // 工厂方法
50, // 初始大小
100 // 最大容量
);

// 使用子弹
public void shoot(float startX, float startY) {
Bullet bullet = bulletPool.obtain();
bullet.x = startX;
bullet.y = startY;
bullet.vx = 10;
bullet.active = true;
activeBullets.add(bullet);
}

// 回收子弹
public void removeBullet(Bullet bullet) {
bullet.reset();
bulletPool.free(bullet);
activeBullets.remove(bullet);
}
2.2 CPU 优化:减少主线程负担
2.2.1 异步加载与后台处理
问题
:在主线程加载资源或进行复杂计算会导致 ANR(Application Not Responding)。
解决方案
:使用 AsyncTask、HandlerThread 或 Kotlin 协程进行异步处理。
代码示例:异步资源加载
public class AssetLoader {
private Handler backgroundHandler;
private Handler mainHandler;

public AssetLoader() {
HandlerThread backgroundThread = new HandlerThread(“AssetLoader”);
backgroundThread.start();
backgroundHandler = new Handler(backgroundThread.getLooper());
mainHandler = new Handler(Looper.getMainLooper());
}

public interface LoadCallback {
void onLoaded(Texture texture);
void onError(String error);
}

public void loadTextureAsync(String path, LoadCallback callback) {
backgroundHandler.post(() -> {
try {
// 在后台线程加载
Texture texture = new Texture(Gdx.files.internal(path));

// 切换回主线程回调
mainHandler.post(() -> callback.onLoaded(texture));
} catch (Exception e) {
mainHandler.post(() -> callback.onError(e.getMessage()));
}
});
}
}

// 使用示例
assetLoader.loadTextureAsync(“level2.png”, new AssetLoader.LoadCallback() {
@Override
public void onLoaded(Texture texture) {
// 更新 UI 或游戏状态
gameScreen.setBackground(texture);
hideLoadingScreen();
}

@Override
public void onError(String error) {
showErrorDialog(error);
}
});
2.2.2 优化游戏循环
问题
:游戏循环中进行过多计算会导致帧率下降。
优化策略
:
固定时间步长
:确保物理模拟稳定
分帧处理
:将重计算分散到多帧
使用高效数据结构
:如 Spatial Hashing 进行碰撞检测
代码示例:优化的游戏循环
public class OptimizedGameLoop {
private static final float FIXED_TIMESTEP = 1f / 60f; // 60 FPS
private float accumulator = 0f;
private long lastTime = System.nanoTime();

public void run() {
long currentTime = System.nanoTime();
float deltaTime = (currentTime – lastTime) / 1e9f;
lastTime = currentTime;

// 防止时间跳跃
if (deltaTime > 0.25f) deltaTime = 0.25f;

accumulator += deltaTime;

// 固定时间步长更新
while (accumulator >= FIXED_TIMESTEP) {
update(FIXED_TIMESTEP);
accumulator -= FIXED_TIMESTEP;
}

// 渲染(使用插值)
float alpha = accumulator / FIXED_TIMESTEP;
render(alpha);
}

private void update(float deltaTime) {
// 物理更新、AI 等
physicsWorld.step(deltaTime);
aiSystem.update(deltaTime);
}

private void render(float alpha) {
// 使用 alpha 进行平滑插值渲染
// 例如:lerp(currentPos, previousPos, alpha)
}
}
2.3 GPU 优化:提升渲染效率
2.3.1 减少 Draw Call
问题
:每次调用
glDrawElements
或
glDrawArrays
都会产生 CPU-GPU 通信开销。
解决方案
:
批处理(Batching)
:合并相同材质的绘制调用
实例化渲染(Instancing)
:一次绘制多个相同物体
纹理图集
:减少纹理切换
代码示例:简单的批处理渲染
public class BatchRenderer {
private static final int MAX_BATCH_SIZE = 1000;
private FloatBuffer vertexBuffer;
private ShortBuffer indexBuffer;
private int drawCallCount = 0;

public BatchRenderer() {
vertexBuffer = BufferUtils.newFloatBuffer(MAX_BATCH_SIZE * 4 * 5); // 4顶点 * 5属性
indexBuffer = BufferUtils.newShortBuffer(MAX_BATCH_SIZE * 6); // 6索引/四边形
}

public void begin() {
vertexBuffer.clear();
indexBuffer.clear();
drawCallCount = 0;
}

public void draw(float x, float y, float width, float height, float u, float v, float u2, float v2) {
// 添加顶点数据到缓冲区
int baseVertex = vertexBuffer.position() / 5;

// 左下
vertexBuffer.put(x).put(y).put(0).put(u).put(v);
// 右下
vertexBuffer.put(x + width).put(y).put(0).put(u2).put(v);
// 右上
vertexBuffer.put(x + width).put(y + height).put(0).put(u2).put(v2);
// 左上
vertexBuffer.put(x).put(y + height).put(0).put(u).put(v2);

// 添加索引
indexBuffer.put((short) baseVertex);
indexBuffer.put((short) (baseVertex + 1));
indexBuffer.put((short) (baseVertex + 2));
indexBuffer.put((short) baseVertex);
indexBuffer.put((short) (baseVertex + 2));
indexBuffer.put((short) (baseVertex + 3));
}

public void end() {
vertexBuffer.flip();
indexBuffer.flip();

// 一次性提交所有数据
// OpenGL 绑定和绘制代码…
drawCallCount++;
}

public int getDrawCallCount() {
return drawCallCount;
}
}
2.3.2 着色器优化
问题
:复杂的着色器计算会消耗大量 GPU 时间。
优化策略
:
减少分支和循环
:GPU 不擅长分支预测
使用低精度浮点数
:
mediump
代替
highp
预计算
:将计算移到 CPU 或预处理
代码示例:优化的顶点着色器
// 优化前:复杂计算
attribute vec3 a_position;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec2 v_texCoords;

void main() {
// 复杂的矩阵运算
vec4 worldPos = u_projTrans * vec4(a_position, 1.0);
// 多余的计算
worldPos = worldPos * 2.0 – 1.0;
gl_Position = worldPos;
v_texCoords = a_texCoord0;
}

// 优化后:简化计算
attribute vec3 a_position;
attribute vec2 a_texCoord0;
uniform mat4 u_projTrans;
varying vec2 v_texCoords;

void main() {
// 直接计算
gl_Position = u_projTrans * vec4(a_position, 1.0);
v_texCoords = a_texCoord0;
}
第三部分:跨机型适配挑战的全面策略
3.1 屏幕适配:从分辨率到长宽比
Android 设备的屏幕尺寸从 4 英寸到 12 英寸不等,分辨率从 720p 到 4K,长宽比从 16:9 到 21:9。
3.1.1 动态视口管理
核心原则
:使用相对坐标系,而非绝对像素坐标。
代码示例:自适应视口
public class AdaptiveViewport implements Viewport {
private float virtualWidth;
private float virtualHeight;
private float worldWidth;
private float worldHeight;

public AdaptiveViewport(float virtualWidth, float virtualHeight) {
this.virtualWidth = virtualWidth;
this.virtualHeight = virtualHeight;
this.worldWidth = virtualWidth;
this.worldHeight = virtualHeight;
}

@Override
public void update(int screenWidth, int screenHeight, boolean centerCamera) {
// 计算缩放比例
float scaleX = screenWidth / virtualWidth;
float scaleY = screenHeight / virtualHeight;

// 保持长宽比,选择较小的缩放因子
float scale = Math.min(scaleX, scaleY);

// 计算视口尺寸(保持居中)
int viewportWidth = (int) (virtualWidth * scale);
int viewportHeight = (int) (virtualHeight * scale);

int x = (screenWidth – viewportWidth) / 2;
int y = (screenHeight – viewportHeight) / 2;

// 设置 OpenGL 视口
Gdx.gl.glViewport(x, y, viewportWidth, viewportHeight);

// 更新相机
if (camera != null) {
camera.viewportWidth = virtualWidth;
camera.viewportHeight = virtualHeight;
if (centerCamera) {
camera.position.set(virtualWidth / 2, virtualHeight / 2, 0);
}
camera.update();
}
}

// 坐标转换:屏幕坐标 -> 世界坐标
public Vector2 screenToWorld(float screenX, float screenY) {
int screenWidth = Gdx.graphics.getWidth();
int screenHeight = Gdx.graphics.getHeight();

float scale = Math.min(screenWidth / virtualWidth, screenHeight / virtualHeight);
int viewportWidth = (int) (virtualWidth * scale);
int viewportHeight = (int) (virtualHeight * scale);
int x = (screenWidth – viewportWidth) / 2;
int y = (screenHeight – viewportHeight) / 2;

// 转换到视口内坐标
float viewportX = screenX – x;
float viewportY = screenHeight – screenY – y; // Y 轴翻转

// 转换到世界坐标
float worldX = viewportX / scale;
float worldY = viewportY / scale;

return new Vector2(worldX, worldY);
}
}
3.1.2 安全区域处理(刘海屏/挖孔屏)
现代 Android 设备有刘海、挖孔等异形屏,需要处理安全区域。
代码示例:安全区域检测
public class SafeAreaHelper {
private static final int[] INSETS_TYPE_MASK = {
WindowInsets.Type.systemBars(),
WindowInsets.Type.displayCutout()
};

public static void applySafeArea(Window window) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
// Android 11+
window.setDecorFitsSystemWindows(false);

WindowInsetsController controller = window.getInsetsController();
if (controller != null) {
controller.hide(WindowInsets.Type.systemBars());
controller.setSystemBarsBehavior(
WindowInsetsController.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
);
}
} else {
// 旧版本兼容
window.getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
);
}
}

// 获取安全区域边界
public static Rect getSafeAreaInsets(Activity activity) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
WindowMetrics metrics = activity.getWindowManager().getCurrentWindowMetrics();
WindowInsets insets = metrics.getWindowInsets();

// 获取刘海区域
Rect cutoutRect = new Rect();
DisplayCutout cutout = insets.getDisplayCutout();
if (cutout != null) {
cutoutRect.set(
cutout.getSafeInsetLeft(),
cutout.getSafeInsetTop(),
cutout.getSafeInsetRight(),
cutout.getSafeInsetBottom()
);
}
return cutoutRect;
}
return new Rect();
}
}
3.2 性能适配:动态调整游戏负载
不同设备的性能差异巨大,需要动态调整游戏设置。
3.2.1 设备性能分级
策略
:根据 CPU 核心数、内存大小、GPU 型号等进行分级。
代码示例:设备性能检测
public class DevicePerformance {
public enum PerformanceLevel {
LOW, MEDIUM, HIGH, ULTRA
}

public static PerformanceLevel detectPerformanceLevel() {
int cpuCores = Runtime.getRuntime().availableProcessors();
long totalMemory = getTotalMemory();
String gpuModel = getGpuModel();

// 内存阈值(MB)
long memoryThresholdLow = 1024; // 1GB
long memoryThresholdMedium = 2048; // 2GB
long memoryThresholdHigh = 4096; // 4GB

// CPU 阈值
int cpuThresholdLow = 4;
int cpuThresholdMedium = 6;

// 评估
if (totalMemory < memoryThresholdLow || cpuCores <= 2) { return PerformanceLevel.LOW; } else if (totalMemory < memoryThresholdMedium || cpuCores <= cpuThresholdLow) { return PerformanceLevel.MEDIUM; } else if (totalMemory < memoryThresholdHigh || cpuCores <= cpuThresholdMedium) { return PerformanceLevel.HIGH; } else { return PerformanceLevel.ULTRA; } } private static long getTotalMemory() { ActivityManager activityManager = (ActivityManager) Gdx.app.getContext() .getSystemService(Context.ACTIVITY_SERVICE); ActivityManager.MemoryInfo memoryInfo = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(memoryInfo); return memoryInfo.totalMem / (1024 * 1024); // 转换为 MB } private static String getGpuModel() { // 通过 OpenGL 获取 GPU 信息 String glRenderer = Gdx.gl.glGetString(GL20.GL_RENDERER); return glRenderer != null ? glRenderer : "Unknown"; } } 3.2.2 动态画质调整 代码示例:动态调整纹理质量 public class QualityManager { private PerformanceLevel level; private Map textureVariants;

public QualityManager() {
level = DevicePerformance.detectPerformanceLevel();
textureVariants = new HashMap<>();

// 根据性能等级选择纹理路径
switch (level) {
case LOW:
textureVariants.put(“background”, “bg_low.png”);
textureVariants.put(“character”, “char_low.png”);
break;
case MEDIUM:
textureVariants.put(“background”, “bg_med.png”);
textureVariants.put(“character”, “char_med.png”);
break;
case HIGH:
case ULTRA:
textureVariants.put(“background”, “bg_high.png”);
textureVariants.put(“character”, “char_high.png”);
break;
}
}

public String getTexturePath(String baseName) {
return textureVariants.getOrDefault(baseName, baseName + “.png”);
}

public int getParticleCount() {
switch (level) {
case LOW: return 10;
case MEDIUM: return 25;
case HIGH: return 50;
case ULTRA: return 100;
default: return 25;
}
}

public boolean enableShadows() {
return level != PerformanceLevel.LOW;
}
}
3.3 系统与硬件适配
3.3.1 电池优化与省电模式
问题
:游戏耗电快,用户可能开启省电模式。
解决方案
:
检测省电模式
:
PowerManager.isPowerSaveMode()
降低帧率
:从 60fps 降到 30fps
减少后台工作
:暂停粒子系统、AI 更新
代码示例:电池优化
public class BatteryOptimizer {
private boolean isLowPowerMode = false;
private int targetFrameRate = 60;

public void checkPowerMode() {
PowerManager powerManager = (PowerManager) Gdx.app.getContext()
.getSystemService(Context.POWER_SERVICE);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
isLowPowerMode = powerManager.isPowerSaveMode();
}

// 检查电池电量
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = Gdx.app.getContext().registerReceiver(null, filter);
if (batteryStatus != null) {
int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
float batteryPct = level * 100 / (float) scale;

if (batteryPct < 20) { isLowPowerMode = true; } } // 调整帧率 if (isLowPowerMode) { targetFrameRate = 30; Gdx.graphics.setContinuousRendering(false); Gdx.graphics.setFrameRate(30); } else { targetFrameRate = 60; Gdx.graphics.setContinuousRendering(true); Gdx.graphics.setFrameRate(60); } } public boolean shouldReduceEffects() { return isLowPowerMode; } } 3.3.2 输入适配:触摸、手柄、键盘 代码示例:统一输入管理器 public class UnifiedInputManager implements InputProcessor { private Vector2 touchPos = new Vector2(); private boolean[] keys = new boolean[256]; private boolean[] gamepadButtons = new boolean[20]; private Vector2 gamepadStick = new Vector2(); // 触摸事件 @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) { touchPos.set(screenX, screenY); // 转换为世界坐标 touchPos = viewport.screenToWorld(touchPos.x, touchPos.y); return true; } // 键盘事件 @Override public boolean keyDown(int keycode) { if (keycode >= 0 && keycode < keys.length) { keys[keycode] = true; } return true; } // 游戏手柄事件(需要额外处理) public void onGamepadButton(int buttonCode, boolean pressed) { if (buttonCode >= 0 && buttonCode < gamepadButtons.length) { gamepadButtons[buttonCode] = pressed; } } public void onGamepadStick(float x, float y) { gamepadStick.set(x, y); } // 统一查询接口 public Vector2 getMovementInput() { Vector2 input = new Vector2(); // 键盘方向键 if (keys[Input.Keys.LEFT]) input.x -= 1; if (keys[Input.Keys.RIGHT]) input.x += 1; if (keys[Input.Keys.UP]) input.y += 1; if (keys[Input.Keys.DOWN]) input.y -= 1; // 游戏手柄摇杆 if (Math.abs(gamepadStick.x) > 0.2f) input.x += gamepadStick.x;
if (Math.abs(gamepadStick.y) > 0.2f) input.y += gamepadStick.y;

// 触摸(虚拟摇杆)
// … 实现虚拟摇杆逻辑

// 归一化
if (input.len() > 1) input.nor();

return input;
}

public boolean isActionPressed() {
return keys[Input.Keys.SPACE] || gamepadButtons[0] || isTouchingActionArea();
}

private boolean isTouchingActionArea() {
// 检查触摸是否在屏幕右半部分(动作区域)
return touchPos.x > Gdx.graphics.getWidth() / 2;
}
}
第四部分:实战案例与工具链
4.1 性能分析工具
4.1.1 Android Profiler
使用方法
:
在 Android Studio 中打开 Profiler
监控 CPU、内存、网络使用情况
查看帧率(FPS)和渲染时间
关键指标
:
帧时间
:每帧耗时应 < 16.67ms(60fps) 内存分配 :避免每帧分配 > 1KB
GPU 渲染
:查看渲染管道瓶颈
4.1.2 GPU Inspector
使用方法
:
安装 GPU Inspector 插件
捕获渲染帧
分析 Draw Call 数量和渲染状态
4.2 自动化测试框架
代码示例:性能回归测试
public class PerformanceTest {
private static final int TEST_DURATION = 30; // 秒
private static final int TARGET_FPS = 60;

public static class TestResult {
public float avgFPS;
public float avgFrameTime;
public long memoryUsed;
public boolean passed;
}

public TestResult runTest(Game game) {
TestResult result = new TestResult();
List frameTimes = new ArrayList<>();
long startTime = System.currentTimeMillis();

// 运行游戏循环
while (System.currentTimeMillis() – startTime < TEST_DURATION * 1000) { long frameStart = System.nanoTime(); game.render(); long frameEnd = System.nanoTime(); float frameTime = (frameEnd - frameStart) / 1e6f; // 转换为毫秒 frameTimes.add(frameTime); } // 计算结果 result.avgFrameTime = (float) frameTimes.stream().mapToDouble(Float::doubleValue).average().orElse(0); result.avgFPS = 1000 / result.avgFrameTime; result.memoryUsed = getCurrentMemoryUsage(); // 判断是否通过 result.passed = result.avgFPS >= TARGET_FPS * 0.95f; // 允许 5% 误差

return result;
}

private long getCurrentMemoryUsage() {
Runtime runtime = Runtime.getRuntime();
return (runtime.totalMemory() – runtime.freeMemory()) / (1024 * 1024);
}
}
4.3 持续集成与部署
GitHub Actions 示例:自动化构建与测试
name: Android Game CI

on:
push:
branches: [ main ]
pull_request:
branches: [ main ]

jobs:
build-and-test:
runs-on: ubuntu-latest

steps:
– uses: actions/checkout@v3

– name: Set up JDK 11
uses: actions/setup-java@v3
with:
java-version: ’11’
distribution: ‘temurin’

– name: Build APK
run: ./gradlew assembleRelease

– name: Run Unit Tests
run: ./gradlew test

– name: Run Performance Tests
run: |
# 启动模拟器并运行性能测试
echo “y” | $ANDROID_HOME/tools/bin/avdmanager create avd -n test -k “system-images;android-30;google_apis;x86_64”
$ANDROID_HOME/emulator/emulator -avd test -no-window -no-audio -no-snapshot &
adb wait-for-device
./gradlew installDebug
adb shell am instrument -w com.example.game.test/androidx.test.runner.AndroidJUnitRunner

– name: Upload APK
uses: actions/upload-artifact@v3
with:
name: game-apk
path: app/build/outputs/apk/release/app-release.apk
第五部分:最佳实践与常见陷阱
5.1 性能优化黄金法则
测量,不要猜测
:使用 Profiler 工具量化性能问题
优化热点
:80% 的时间花在 20% 的代码上
分层优化
:从算法层面开始,再到代码层面
保持简单
:复杂的优化往往引入更多 bug
5.2 跨机型适配清单
[ ]
屏幕适配
:测试 4:3、16:9、18:9、19.5:9 等比例
[ ]
分辨率适配
:从 720p 到 4K
[ ]
性能适配
:测试低端(2GB RAM)、中端(4GB RAM)、高端(8GB+ RAM)
[ ]
系统版本
:Android 5.0 到最新版本
[ ]
厂商定制
:小米、华为、三星等不同 ROM
[ ]
输入方式
:触摸、手柄、键盘、鼠标
[ ]
特殊硬件
:刘海屏、折叠屏、5G 网络
5.3 常见陷阱与解决方案
陷阱
现象
解决方案
内存泄漏
内存持续增长,最终 OOM
使用 LeakCanary 检测,确保资源释放
主线程阻塞
界面卡顿,ANR
异步加载,后台线程处理
过度绘制
GPU 负载高,发热
减少半透明层,使用
clipRect
纹理过大
加载慢,内存高
压缩纹理,使用图集
帧率不稳定
画面卡顿
固定时间步长,减少 GC
结语:持续优化与迭代
Android 游戏开发是一个持续优化的过程。性能优化和跨机型适配不是一次性任务,而是需要贯穿整个开发周期的工作。建议建立以下流程:
开发阶段
:使用性能分析工具,建立基准测试
测试阶段
:在多款真实设备上测试,收集性能数据
发布阶段
:监控线上性能,收集用户反馈
迭代阶段
:根据数据持续优化,发布更新
记住,
没有完美的优化,只有权衡
。在性能、画质、包体积和开发成本之间找到平衡点,才是成功的关键。希望这篇指南能帮助你克服 Android 游戏开发中的性能优化和跨机型适配挑战,创造出优秀的游戏作品!