Xamarin BLE有时仅扫描

时间:2016-08-04 20:13:45

标签: xamarin bluetooth

我创建了简单的Xamarin.Forms蓝牙低能量扫描应用程序。由于我将仅在Android上使用蓝牙,因此我在Android项目的MainActivity.cs中实施了扫描:

namespace BlankAppXamlXamarinForms.Droid
{
    [Activity(Label = "BlankAppXamlXamarinForms", Icon = "@drawable/icon", Theme = "@style/MainTheme", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
    public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity
    {
        private BluetoothManager _manager;
        App app;

        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            app = new App();

            var appContext = Application.Context;
            _manager = (BluetoothManager)appContext.GetSystemService(BluetoothService);
            _manager.Adapter.BluetoothLeScanner.StartScan(new MyScanCallback(app));

            LoadApplication(new App());
        }
    }

    public class MyScanCallback : ScanCallback
    {
        App _app;
        public MyScanCallback(App app) {
            _app = app;
        }

        public override void OnScanResult(ScanCallbackType callbackType, ScanResult result)
        {
            _app.newDevice(result.Device.Name + " - " + result.Device.Address);
        }
    }
}

问题是OnScanResult在应用程序启动后的一小段时间内接收到广告数据包,当我关闭手机显示屏然后再打开它时。同时,应用程序几乎不接收广告包。如何在我的应用程序处于活动状态时一直接收广告包?

1 个答案:

答案 0 :(得分:0)

您正在创建LoadApplication(new App());的两个实例。您应该在app字段中传递LoadApplication(app);而不是OnCreate,而不是OnResume

此外,您可能希望在OnPause中开始扫描并在public class MainActivity : FormsAppCompatActivity { BluetoothManager bleManager; App app; ScanCallback scanCallback; protected override void OnCreate(Bundle bundle) { TabLayoutResource = Resource.Layout.Tabbar; ToolbarResource = Resource.Layout.Toolbar; base.OnCreate(bundle); Forms.Init(this, bundle); app = new App(); bleManager = (BluetoothManager)Application.Context.GetSystemService(BluetoothService); scanCallback = new MyScanCallback(app); LoadApplication(new App()); } protected override void OnResume() { base.OnResume(); bleManager.Adapter.BluetoothLeScanner.StartScan(scanCallback); } protected override void OnPause() { base.OnPause(); bleManager.Adapter.BluetoothLeScanner.StopScan(scanCallback); } } 中停止扫描,而不是在shown.bs.popover中开始扫描,例如:

$('[data-toggle="popover"]').popover({html:true});

$('[data-toggle="popover"]').on('shown.bs.popover', function () {
    $('#Uname').click(function(){
        alert($(this).data('content'));
    });

});
相关问题