简体   繁体   中英

Xamarin Android Bluetooth app crash

I am a beginner in Android app dev, and I need to make a Bluetooth app to connect to the HC-05 module. My code is as follows:

using System;
using Android.App;
using Android.Widget;
using Android.OS;
using Android.Bluetooth;
using Android.Content;
using Android.Runtime;
using Java.Util;
using Android.Util;

namespace Robot_App
{
    [Activity(Label = "Robot App", MainLauncher = true, Icon = "@drawable/logo", Theme = "@android:style/Theme.Light.NoTitleBar")]
    public class MainActivity : Activity
    {
        BluetoothAdapter myAdapter = BluetoothAdapter.DefaultAdapter;
        private static ArrayAdapter<string> newDevicesAdapter;
        private BluetoothReceiver receiver;

        const int REQUEST_ENABLE_BT = 1;

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

            SetContentView(Resource.Layout.Main);

            var scanButton = FindViewById<Button>(Resource.Id.BT_get_list);
            scanButton.Click += (sender, e) =>
            {
                try
                {
                    if (myAdapter.IsEnabled)
                    {
                        DoDiscovery();
                    }
                    else
                    {
                        Intent enableBTIntent = new Intent(BluetoothAdapter.ActionRequestEnable);
                        StartActivityForResult(enableBTIntent, REQUEST_ENABLE_BT);
                    }
                }
                catch (AndroidException ex)
                {
                    Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
                }
            };

            newDevicesAdapter = new ArrayAdapter<string>(this, Resource.Layout.device_names);
            Spinner newDevicesList = (Spinner)this.FindViewById<Spinner>(Resource.Id.Devices_list);
            newDevicesList.Adapter = newDevicesAdapter;

            receiver = new BluetoothReceiver(this);
            var filter = new IntentFilter(BluetoothDevice.ActionFound);
            RegisterReceiver(receiver, filter);

            filter = new IntentFilter(BluetoothAdapter.ActionDiscoveryFinished);
            RegisterReceiver(receiver, filter);

            myAdapter = BluetoothAdapter.DefaultAdapter;

            BluetoothSocket mySocket;
            UUID my_uuid = UUID.FromString("00001101-0000-1000-8000-00805F9B34FB");

            var connectButton = FindViewById<Button>(Resource.Id.Connect);
            connectButton.Click += (sender, e) =>
            {
                BluetoothDevice selectedDevice = (BluetoothDevice)newDevicesList.SelectedItem;
                if (myAdapter.BondedDevices.Contains(selectedDevice))
                {
                    mySocket = selectedDevice.CreateRfcommSocketToServiceRecord(my_uuid);
                    myAdapter.CancelDiscovery();
                    mySocket.Connect();
                }
                else if (!myAdapter.BondedDevices.Contains(selectedDevice))
                {

                }
            };
        }

        protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
        {
            switch (requestCode)
            {
                case (REQUEST_ENABLE_BT):
                    base.OnActivityResult(requestCode, resultCode, data);
                    if (resultCode == Result.Ok)
                    {
                        DoDiscovery();
                    }
                    else if (resultCode == Result.Canceled)
                    {
                        Toast.MakeText(this, "Please switch on Bluetooth.", ToastLength.Long).Show();
                    }
                    break;
            }
        }

        private void DoDiscovery()
        {
            try
            {
                newDevicesAdapter.Clear();
                myAdapter.StartDiscovery();
                Toast.MakeText(this, "Searching...", ToastLength.Long).Show();
            }
            catch (AndroidException ex)
            {
                Toast.MakeText(this, ex.ToString(), ToastLength.Short).Show();
            }
        }

        public class BluetoothReceiver : BroadcastReceiver
        {
            Activity _controller;

            public BluetoothReceiver(Activity controller)
            {
                _controller = controller;
            }

            public override void OnReceive(Context context, Intent intent)
            {
                string action = intent.Action;
                if (action == BluetoothDevice.ActionFound)
                {
                    BluetoothDevice device = (BluetoothDevice)intent.GetParcelableExtra(BluetoothDevice.ExtraDevice);
                    newDevicesAdapter.Add(device.Name);
                }
                else if (action == BluetoothAdapter.ActionDiscoveryFinished)
                {
                    Toast.MakeText(context, "Finished scanning for devices.", ToastLength.Short).Show();
                }
            }
        }


    }
}

EDIT: Here is the layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout1">
    <LinearLayout
        android:orientation="horizontal"
        android:id="@+id/linearLayout2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <ImageView
            android:src="@drawable/logo"
            android:layout_width="120dp"
            android:layout_height="100dp"
            android:id="@+id/imageView1"
            android:clickable="false"
            android:visibility="visible"
            android:padding="5dp"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:layout_marginTop="5dp" />
        <LinearLayout
            android:orientation="vertical"
            android:layout_width="235.0dp"
            android:layout_height="match_parent"
            android:id="@+id/linearLayout3">
            <TextView
                android:text="Robot"
                android:textAppearance="?android:attr/textAppearanceLarge"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/textView1"
                android:clickable="false"
                android:editable="false"
                android:enabled="true"
                android:longClickable="false"
                android:padding="15dp"
                android:layout_gravity="center"
                android:gravity="center" />
            <TextView
                android:text="Control Panel"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/textView2"
                android:clickable="false"
                android:editable="false"
                android:enabled="true"
                android:longClickable="false"
                android:padding="5dp"
                android:layout_gravity="center"
                android:gravity="center" />
        </LinearLayout>
    </LinearLayout>
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/BT_Connection">
        <TextView
            android:text="Bluetooth Connection"
            android:textAppearance="?android:attr/textAppearanceSmall"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/BT_Connection_tag"
            android:clickable="false"
            android:editable="false"
            android:enabled="true"
            android:longClickable="false"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingTop="50dp"
            android:layout_gravity="center"
            android:gravity="left"
            android:textSize="12dp" />
        <LinearLayout
            android:orientation="horizontal"
            android:minWidth="25px"
            android:minHeight="25px"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout4"
            android:paddingLeft="15dp"
            android:paddingRight="15dp"
            android:paddingTop="5dp"
            android:paddingBottom="5dp"
            android:weightSum="3">
            <Button
                android:text="Search"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/BT_get_list"
                android:clickable="true"
                android:editable="false"
                android:enabled="true"
                android:longClickable="false"
                android:layout_weight="1"
                android:layout_gravity="center" />
            <Button
                android:text="Connect"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/Connect"
                android:clickable="true"
                android:editable="false"
                android:enabled="true"
                android:longClickable="false"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:gravity="center" />
            <Button
                android:text="Disconnect"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/Disconnect"
                android:gravity="center"
                android:layout_weight="1"
                android:layout_gravity="center"
                android:longClickable="false"
                android:enabled="true"
                android:editable="false"
                android:clickable="true" />
        </LinearLayout>
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:id="@+id/linearLayout5"
            android:paddingBottom="5dp"
            android:paddingLeft="15dp"
            android:paddingRight="15dp">
            <Spinner
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:id="@+id/Devices_list"
                android:clickable="true"
                android:longClickable="false"
                android:layout_gravity="center"
                android:layout_weight="1"
                android:tag="Please select a device:" />
        </LinearLayout>
    </LinearLayout>
</LinearLayout>

So basically I'm using a button to scan for devices, then I list the found devices in a spinner, then a button connects to the device selected in the spinner.

However, I'm getting an unhandled exception when I click on the 'Search' button, and the app crashes.

EDIT: This is what I see in the VS2017 debugger:

Screenshot of debugger

Any help will be appreciated. Thanks.

Have you added these

<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />

in your manifest?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM