You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android端Xamarin.Forms应用重启触发BluetoothLowEnergyAdapter.Init重复调用异常求助

解决Xamarin.Forms Android应用重启时BLE适配器重复初始化异常

你遇到的问题核心在于BluetoothLowEnergyAdapter.Init()是全局单例初始化方法,整个应用进程生命周期内只能调用一次,但你的MainActivity.OnCreate()在应用关闭后重新打开(或Activity重建)时会再次执行,触发了这个限制,从而抛出异常。

下面给你两个实用的解决方案:

方案一:用静态标记位控制初始化

在MainActivity类中添加一个静态布尔变量,用来记录BLE适配器是否已经完成初始化,只有在未初始化的情况下才调用Init():

public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity 
{
    // 静态标记:记录BLE适配器是否已初始化
    private static bool _bleAdapterInitialized = false;

    protected override void OnCreate(Bundle bundle) {
        base.OnCreate(bundle);
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        DependencyService.Register<ToastNotification>();
        DependencyService.Register<OpenAppAndroid>();
        Forms.Init(this, bundle);

        // 仅当未初始化时执行Init操作
        if (!_bleAdapterInitialized)
        {
            BluetoothLowEnergyAdapter.Init(this);
            _bleAdapterInitialized = true;
        }

        ToastNotification.Init(this, new PlatformOptions() { SmallIconDrawable = Android.Resource.Drawable.IcDialogInfo });
        LoadApplication(new Spirocco.App(BluetoothLowEnergyAdapter.ObtainDefaultAdapter(ApplicationContext)));
        
        // 闹钟相关逻辑保持不变
        NotificationReceiver notificationReceiver = new NotificationReceiver();
        AlarmManager alarmManager = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
        Intent notificationIntent = new Intent(Android.App.Application.Context, notificationReceiver.Class);
        PendingIntent pendingIntent = PendingIntent.GetBroadcast(Android.App.Application.Context, 0, notificationIntent, 0);
        DateTime time = DateTime.Now.AddSeconds(10);
        DateTime baseTime = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
        TimeSpan span = time.ToUniversalTime() - baseTime;
        long timer = (long)span.TotalMilliseconds;
        alarmManager.Set(AlarmType.RtcWakeup, timer, pendingIntent);
    }
}

方案二:利用库自带的初始化状态检查

如果你的BLE库提供了判断初始化状态的属性(比如BluetoothLowEnergyAdapter.IsInitialized),可以直接用它来替代自定义标记,代码会更简洁:

if (!BluetoothLowEnergyAdapter.IsInitialized)
{
    BluetoothLowEnergyAdapter.Init(this);
}

补充说明

Android的进程和Activity生命周期是分开的:

  • 当应用被彻底杀死后重新打开,进程会重启,静态标记位会自动重置,不会影响首次初始化;
  • 如果是Activity因配置变更(比如屏幕旋转)重建,静态标记位会保留,避免重复初始化导致异常。

内容的提问来源于stack exchange,提问作者Tamás Deák

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:56:02