簡體   English   中英

Xamarin Android藍牙應用程序崩潰

[英]Xamarin Android Bluetooth app crash

我是Android應用程序開發的初學者,我需要制作一個藍牙應用程序才能連接到HC-05模塊。 我的代碼如下:

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();
                }
            }
        }


    }
}

編輯:這是布局:

<?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>

因此,基本上,我使用按鈕來掃描設備,然后在微調器中列出找到的設備,然后將按鈕連接到微調器中選擇的設備。

但是,當我單擊“搜索”按鈕時,出現了未處理的異常,導致應用崩潰。

編輯:這就是我在VS2017調試器中看到的:

調試器的屏幕截圖

任何幫助將不勝感激。 謝謝。

您是否添加了這些

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

在你的清單上?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM