无法显示和检测蓝牙设备

时间:2017-12-26 22:38:45

标签: c# bluetooth xamarin.android

using Android.App;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Android.Content;
using Android.Views;

namespace BluetoothBLE
{
[Activity(Label = "BluetoothBLE", MainLauncher = true)]
public class MainActivity : Activity
{
    //Local Bluetooth adapter
    private BluetoothAdapter bluetoothAdapter = null;

    //Return Intent extra
    public const string Extra_Device_Address = "device_address";

    //Members Field
    private static ArrayAdapter<string> Device;

    protected override void OnCreate(Bundle savedInstanceState) 
    {
        base.OnCreate(savedInstanceState);

        // Set our view from the "main" layout resource
        SetContentView(Resource.Layout.Main);

        //Get our UI controls from the loaded layout
        TextView Text = FindViewById<TextView>(Resource.Id.BluetoothDevices);
        TextView Device_Name = FindViewById<TextView>(Resource.Id.DeviceName);
        Button Scan = FindViewById<Button>(Resource.Id.Scan);
        TextView NewDevice = FindViewById<TextView>(Resource.Id.NewDevice);
        ListView List = FindViewById<ListView>(Resource.Id.ListBluetooth);

        //Initialize array adapters
        Device = new ArrayAdapter<string>(this, Resource.Layout.Main);

        //Testing Faced
        Scan.Click += (sender, e) =>
        {
            if (bluetoothAdapter.IsEnabled == true)
            {
                Toast.MakeText(Application, "Start scanning",      ToastLength.Short).Show();
                DoDiscovery();
                (sender as View).Visibility = ViewStates.Visible;
                if(Device.Count != 0)
                {
                    NewDevice.Text = Device.GetItem(0).ToString();
                }
                else
                {
                    NewDevice.Text = "Device is not recorded";
                }
                Toast.MakeText(Application, "Device found", ToastLength.Short).Show();
            }
            else
            {
                Toast.MakeText(Application, "Please enable bluetooth", ToastLength.Short).Show();
            }

        };

        //Find and set up the ListView for newly discovered devices.
        List.Adapter = Device;
        List.ItemClick += DeviceListClick;

        //Register for broadcasts when a device is discovered
        Receiver receiver = new Receiver();
        var filter = new IntentFilter(BluetoothDevice.ActionFound);
        RegisterReceiver(receiver, filter);

        //Register for broadcasts when discovery is finished
        filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished);
        RegisterReceiver(receiver, filter);

        bluetoothAdapter = BluetoothAdapter.DefaultAdapter; //Get Loacl Bluetooth Adapter

        if (bluetoothAdapter == null)
        {
            Toast.MakeText(this, "Bluetooth is not Supported.", ToastLength.Long).Show();
            Finish();
            return;
        }

        //Display the Name of local bluetooth
        Device_Name.Text = bluetoothAdapter.Name;

    }

    protected override void OnResume()
    {
        base.OnResume();
        //RegisterReceiver(bluetooth, new IntentFilter(""));
    }

    protected override void OnPause()
    {
        base.OnPause();
        //UnregisterReceiver(bluetooth);
    }

    void DeviceListClick (object sender, AdapterView.ItemClickEventArgs args)
    {
        // Cancel discovery because it's costly and we're about to connect
        bluetoothAdapter.CancelDiscovery();

        //Get the device MAC address, which is the last 17 chars in the View
        var info = (args.View as TextView).Text.ToString();
        var address = info.Substring(info.Length - 17);

        //Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.PutExtra(Extra_Device_Address, address);

        //Set result and finish this Activity
        SetResult(Result.Ok, intent);
        Finish();
    }

    private void DoDiscovery()
    {
        //Indicate scanning in the title
        SetProgressBarIndeterminateVisibility(true);
        SetTitle(Resource.String.scanning);

        //Turn on sub-title for new devices
        FindViewById<View>(Resource.Id.NewDevice).Visibility = ViewStates.Visible;

        //If we're already discovering, stop it
        if (bluetoothAdapter.IsDiscovering)
        {
            bluetoothAdapter.CancelDiscovery();
        }

        //Request disccover from BluetoothAdapter
        bluetoothAdapter.StartDiscovery();
    }

    public class Receiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            string action = intent.Action;

            // When discovery finds a device
            if (action == BluetoothDevice.ActionFound)
            {
                // Get the BluetoothDevice object from the Intent
                BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                // If it's already paired, skip it, because it's been listed already
                if(device.BondState != Bond.Bonded)
                {
                    Device.Add(device.Name + "\n" + device.Address);
                }
                // When discovery is finished, change the Activity title
                else if(Device.Count == 0)
                {
                    Device.Add("Empty");
                }
            }
        }
    }
  }
}

测试我的代码,我发现我的应用程序无法检测蓝牙设备,也无法显示它们。我上网查找要遵循的示例,没有发现任何错误。任何帮助将不胜感激。抱歉,如果我犯了小错误,这是我第一次尝试使用Xamarin创建Android应用程序。

0 个答案:

没有答案