2025最全MonoDroid示例精讲:从入门到精通Android开发实战
项目概述
MonoDroid(现为.NET for Android)作为Xamarin平台的重要组成部分,为C#开发者提供了构建原生Android应用的强大能力。本文基于monodroid-samples项目(仓库地址:https://gitcode.com/gh_mirrors/mo/monodroid-samples),系统梳理12个核心示例项目,涵盖从基础UI组件到高级系统服务的完整开发场景。通过本文,你将掌握:
- 10+常用Android API的C#实现方式
- 跨进程通信(AIDL)、传感器集成等进阶技术
- Activity生命周期管理与状态保存最佳实践
- 符合Material Design规范的UI组件开发
环境准备
开发环境配置
# 克隆项目仓库
git clone https://gitcode.com/gh_mirrors/mo/monodroid-samples.git
cd monodroid-samples
# 安装.NET SDK (要求.NET 6+)
sudo apt-get install dotnet-sdk-7.0
# 构建示例项目(以Phoneword为例)
cd Phoneword
dotnet build Phoneword.sln
项目结构解析
monodroid-samples/
├── AIDLDemo/ # 跨进程通信示例
├── AccelerometerPlay/ # 加速度传感器应用
├── ActivityLifecycle/ # 活动生命周期演示
├── Button/ # 基础按钮交互
├── LocalNotifications/ # 本地通知系统
├── Phoneword/ # 电话号码转换工具(入门示例)
└── ...(共12个示例项目)
核心示例详解
1. Activity生命周期管理
Activity作为Android应用的基本组件,其生命周期管理直接影响应用性能与用户体验。ActivityLifecycle示例完整展示了活动从创建到销毁的全过程:
[Activity(Label = "Activity A", MainLauncher = true)]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle? bundle)
{
Log.Debug(GetType().FullName, "Activity A - OnCreate");
base.OnCreate(bundle);
SetContentView(Resource.Layout.activity_main);
// 状态恢复示例
if (bundle != null)
{
_counter = bundle.GetInt("click_count", 0);
}
}
protected override void OnSaveInstanceState(Bundle outState)
{
outState.PutInt("click_count", _counter);
base.OnSaveInstanceState(outState);
}
// 完整生命周期方法实现
protected override void OnStart() { ... }
protected override void OnResume() { ... }
protected override void OnPause() { ... }
protected override void OnStop() { ... }
protected override void OnDestroy() { ... }
}
生命周期流程图:
2. 本地通知系统实现
LocalNotifications示例演示了Android 8.0+通知渠道机制、权限请求及点击跳转功能。核心实现如下:
void CreateNotification()
{
// 1. 创建通知内容
var builder = new NotificationCompat.Builder(this, CHANNEL_ID)
.SetAutoCancel(true)
.SetContentTitle("Button Clicked")
.SetNumber(count)
.SetSmallIcon(Resource.Mipmap.ic_stat_button_click)
.SetContentText($"The button has been clicked {count} times.");
// 2. 创建跳转意图
var resultIntent = new Intent(this, typeof(SecondActivity));
resultIntent.PutExtra(COUNT_KEY, count);
// 3. 构建返回栈
var stackBuilder = TaskStackBuilder.Create(this);
stackBuilder.AddParentStack(Class.FromType(typeof(SecondActivity)));
stackBuilder.AddNextIntent(resultIntent);
// 4. 发送通知
var notificationManager = NotificationManagerCompat.From(this);
notificationManager.Notify(NOTIFICATION_ID, builder.Build());
}
通知渠道创建(Android O+必需):
void CreateNotificationChannel()
{
if (OperatingSystem.IsAndroidVersionAtLeast(26))
{
var channel = new NotificationChannel(CHANNEL_ID, "通知演示",
NotificationImportance.Default)
{
Description = "用于演示本地通知功能"
};
var manager = (NotificationManager)GetSystemService(NotificationService);
manager.CreateNotificationChannel(channel);
}
}
3. 跨进程通信(AIDL)
AIDLDemo展示了使用AIDL(Android Interface Definition Language)实现跨进程通信的方法。项目结构包含:
AIDLDemo/
├── IAdditionService.aidl # AIDL接口定义
├── AdditionService.cs # 远程服务实现
├── AdditionServiceBinder.cs # Binder实现
└── Activity1.cs # 客户端调用
核心接口定义:
// IAdditionService.aidl
package com.xamarin.samples.aidldemo;
interface IAdditionService {
int add(int num1, int num2);
}
服务绑定流程:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
// 绑定远程服务
var intent = new Intent(this, typeof(AdditionService));
BindService(intent, serviceConnection, Bind.AutoCreate);
}
private IAdditionService additionService;
private ServiceConnection serviceConnection = new AdditionServiceConnection();
public class AdditionServiceConnection : Java.Lang.Object, IServiceConnection
{
public void OnServiceConnected(ComponentName name, IBinder service)
{
additionService = IAdditionServiceStub.AsInterface(service);
}
public void OnServiceDisconnected(ComponentName name)
{
additionService = null;
}
}
4. 传感器应用开发
AccelerometerPlay示例利用设备加速度传感器实现了物理模拟效果,展示了传感器数据采集与实时处理的完整流程:
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
// 获取传感器管理器
sensorManager = (SensorManager)GetSystemService(SensorService);
// 注册加速度传感器监听
var accelerometer = sensorManager.GetDefaultSensor(SensorType.Accelerometer);
sensorManager.RegisterListener(this, accelerometer, SensorDelay.Game);
}
// 传感器数据回调
public void OnSensorChanged(SensorEvent e)
{
if (e.Sensor.Type == SensorType.Accelerometer)
{
// 获取加速度数据(m/s²)
float x = e.Values[0];
float y = e.Values[1];
float z = e.Values[2];
// 更新物理模拟
simView.UpdateAcceleration(x, y);
}
}
粒子系统物理模拟:
public class ParticleSystem
{
private List<Particle> particles = new List<Particle>();
public void Update(float deltaTime, float gravityX, float gravityY)
{
foreach (var p in particles)
{
// 应用加速度
p.VelocityX += gravityX * deltaTime;
p.VelocityY += gravityY * deltaTime;
// 更新位置
p.X += p.VelocityX * deltaTime;
p.Y += p.VelocityY * deltaTime;
// 边界碰撞检测
CheckBounds(p);
}
}
}
示例项目对比分析
| 项目名称 | 核心技术 | 适用场景 | 难度等级 |
|---|---|---|---|
| Phoneword | 基础UI交互、Intent | 初学者入门 | ★☆☆☆☆ |
| ActivityLifecycle | 生命周期管理、状态保存 | 所有应用必备 | ★★☆☆☆ |
| LocalNotifications | 通知渠道、PendingIntent | 消息提醒功能 | ★★★☆☆ |
| AIDLDemo | AIDL、远程服务 | 跨应用通信 | ★★★★☆ |
| AccelerometerPlay | 传感器、物理模拟 | 游戏、运动类应用 | ★★★★☆ |
| SwitchDemo | 开关控件、事件处理 | 设置界面开发 | ★☆☆☆☆ |
| PopupMenuDemo | 菜单组件、上下文操作 | 交互优化 | ★★☆☆☆ |
高级应用技巧
1. 状态保存最佳实践
在ActivityLifecycle示例中,演示了两种状态保存方式的结合使用:
// 1. 轻量级状态保存(适合基本类型)
protected override void OnSaveInstanceState(Bundle outState)
{
outState.PutInt("click_count", _counter);
base.OnSaveInstanceState(outState);
}
// 2. 持久化存储(适合复杂数据)
protected override void OnPause()
{
base.OnPause();
using var pref = GetPreferences(FileCreationMode.Private);
var editor = pref.Edit();
editor.PutInt("counter", _counter);
editor.Apply(); // 异步提交
}
2. 权限请求处理
LocalNotifications示例展示了Android 6.0+动态权限请求流程:
const string PERMISSION = "android.permission.POST_NOTIFICATIONS";
const int REQUEST_CODE = 1;
// 检查并请求权限
if (CheckSelfPermission(PERMISSION) == Permission.Denied)
{
ActivityCompat.RequestPermissions(this, new[] { PERMISSION }, REQUEST_CODE);
}
// 权限请求回调
public override void OnRequestPermissionsResult(int requestCode,
string[] permissions, Permission[] grantResults)
{
if (requestCode == REQUEST_CODE && grantResults[0] == Permission.Granted)
{
CreateNotification();
}
else
{
Toast.MakeText(this, "通知权限被拒绝", ToastLength.Long).Show();
}
}
项目迁移与现代化
随着Xamarin向.NET MAUI演进,示例项目也展示了迁移到现代.NET的关键步骤:
- 项目文件更新:
<!-- 旧Xamarin项目 -->
<Project Sdk="Xamarin.Android.Sdk">
<!-- 新.NET项目 -->
<Project Sdk="Microsoft.NET.Sdk.Android">
<PropertyGroup>
<TargetFramework>net7.0-android</TargetFramework>
<RootNamespace>MonoDroidSamples</RootNamespace>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
- 命名空间简化:
// 旧代码
using Android.App;
using Android.Widget;
using Android.OS;
// 新代码(隐式导入)
namespace ActivityLifecycle;
[Activity(Label = "Activity A")]
public class MainActivity : Activity
{
// 无需显式using语句
}
总结与展望
monodroid-samples项目提供了从基础到高级的完整Android开发学习路径。通过这些示例,开发者可以掌握:
- 符合Material Design的UI组件开发
- 系统服务(通知、传感器、位置等)集成方法
- 跨进程通信与服务管理
- 状态保存与生命周期管理
随着.NET 8/9对Android平台的持续优化,未来这些示例将进一步整合MAUI的跨平台能力,实现"一次编写,多端运行"。建议开发者重点关注:
- .NET MAUI的Handler架构
- Android 14+新特性适配
- 性能优化(内存管理、渲染优化)
资源获取与交流
- 完整代码:https://gitcode.com/gh_mirrors/mo/monodroid-samples
- 官方文档:https://learn.microsoft.com/zh-cn/dotnet/android/
- 社区论坛:https://developer.android.com/dotnet
如果本文对你有帮助,请点赞👍收藏🌟关注,后续将推出《MAUI跨平台开发实战》系列教程,敬请期待!
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



