Bluetooth - problem with connection Android, c#, Visual Studio 2015

Hello everybody, I have a problem with set up connection between two devices. Below is my code (I am beginner in android programming). There is one button where on click I read paired devices and show results in listview. Now I can read the name and address selected device, but i have no idea how to connect with selected device. If anybody can help me how to connect with selected device from list (for read/write text data) it will be nice.
thx for any help.
R.

(sorry for my language mistakes)

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

namespace App2
{
[Activity(Label = "xas", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{

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

        SetContentView(Resource.Layout.Main);


        Button btn1 = FindViewById<Button>(Resource.Id.button1);
        TextView txt1 = FindViewById<TextView>(Resource.Id.textView1);
        ListView lsv1 = FindViewById<ListView>(Resource.Id.listView1);

        lsv1.ItemClick += (object sender, Android.Widget.AdapterView.ItemClickEventArgs e) => {
            String selectedFromList = lsv1.GetItemAtPosition(e.Position).ToString();
            txt1.Text = selectedFromList;
        };

        btn1.Click += delegate {


            txt1.Text = "";
            lsv1.Adapter = null;

            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.DefaultAdapter;
            if (mBluetoothAdapter == null)  
            {

            }
            else {
                if (!mBluetoothAdapter.IsEnabled) 
                {

                }
                else
                {

                    var pairedDevices = mBluetoothAdapter.BondedDevices;

                    if (pairedDevices.Count > 0)
                    {

                        string[] tab = new string[pairedDevices.Count];
                        ArrayAdapter mArrayAdapter = new ArrayAdapter(this, 1);
                        int i = 0;
                        foreach (BluetoothDevice device in pairedDevices)
                        {
                            tab[i] = device.Name + "\n" + device.Address;
                            i++;
                        }

                        ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, tab);
                        lsv1.Adapter = adapter;
                    }
                }
            }
        };
    }
}

}

Answers

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    this code could help you

            BluetoothSocket BthSocket = null;
    
            BluetoothAdapter adapter = BluetoothAdapter.DefaultAdapter;
            if(adapter == null)
                System.Diagnostics.Debug.WriteLine("No Bluetooth adapter found.");
    
            if(!adapter.IsEnabled)
                System.Diagnostics.Debug.WriteLine("Bluetooth adapter is not enabled."); 
    
            BluetoothDevice device = null;
    
            foreach (var bd in adapter.BondedDevices) {
                if (bd.Name.StartsWith ("QuickScan")) {
                    device = bd;
                    break;
                }
            }
    
            if (device == null)
                System.Diagnostics.Debug.WriteLine ("Named device not found.");
            else {
                BthSocket = device.CreateRfcommSocketToServiceRecord(UUID.FromString("00001101-0000-1000-8000-00805f9b34fb"));
                if (BthSocket != null) {
    
                    Task.Run (async() => {
                        await BthSocket.ConnectAsync ();
    
                        if(BthSocket.IsConnected){
                            System.Diagnostics.Debug.WriteLine("Connected!");
                            var mReader = new InputStreamReader(BthSocket.InputStream);
                            var buffer = new BufferedReader(mReader);
                            while (true){
    
                                string barcode = await buffer.ReadLineAsync();
                                if(barcode.Length > 0){
                                    System.Diagnostics.Debug.WriteLine("Letto: " + barcode);
                                    Xamarin.Forms.MessagingCenter.Send<App, string> ((App)Xamarin.Forms.Application.Current, "Barcode", barcode);
                                }
                            }
    
                        }
    
                    });
                }
            }
    
  • TherrerTherrer USMember

    hi Alessandro, thank you for your quick answer. I will try use your code in my program as soon as i find free time.
    regards
    R.

  • CherifiAmineCherifiAmine USMember

    Hello Robert, i tried the code Alessandro and it does not work !!!! are you managed to connect with selected device from list?
    Thank you
    And sorry for my language mistakes

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭

    Which is the problem?

  • Haider-MHaider-M USMember

    Hello AlessandroCaliaro,

    I have similar issue with one specific device use android version 4.2.2, it throwing an exception at the following: "await BthSocket.ConnectAsync()", the cached exception message was : "Service discovery failed", bellow are link for the output stack from visual studio starting from the point that task is run, please advise :

    https://justpaste.it/11poj

    the code is working fine on all other android version newer than the one mentioned above..

    Thanks

  • Haider-MHaider-M USMember

    Thank you Alessandro for your quick response..
    It seems that the link you posted was for android studio developers, what is the equivalent for that code in Xamarin ?

    Method m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
    tmp = (BluetoothSocket) m.invoke(device, 1);

    I am trying the GitHub link you post it..
    once again, thank you..

  • AlessandroCaliaroAlessandroCaliaro ITMember ✭✭✭✭✭
    Yes, it is Java code but csharp translation should be easy. Let me know
  • Haider-MHaider-M USMember
    edited December 2016

    GitHub Sample code "TestBth" is failed as well, "if(BthSocket.IsConnected)" result is false , here is the output stack for that :

    smile: 12-24 13:19:13.457 I/BluetoothSocket_MTK(14387): [JSR82] Bluetooth Socket Constructor
    12-24 13:19:13.457 I/BluetoothSocket_MTK(14387): [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
    Thread started: #7
    Thread started: #8
    12-24 13:19:13.484 I/BluetoothSocket_MTK(14387): [JSR82] connect: do SDP
    12-24 13:19:13.499 D/dalvikvm(14387): threadid=14: interp stack at 0x658a1000
    12-24 13:19:13.500 D/dalvikvm(14387): threadid=15: interp stack at 0x658c1000
    12-24 13:19:13.501 D/Mono (14387): [0x670ea3e0] worker starting
    12-24 13:19:15.354 I/BluetoothSocket_MTK(14387): [JSR82] SdpHelper::onRfcommChannelFound: channel=1
    12-24 13:19:15.354 I/BluetoothSocket_MTK(14387): [JSR82] connect: do SDP done; mPort=1
    Thread finished: #8

    while it looping, here is the output result which keep printed repeatedly :

    [0:] Adapter found!!
    [0:] Adapter enabled!
    [0:] Paired devices found: ***XI238
    12-24 13:25:01.955 I/BluetoothSocket_MTK(14387): [JSR82] Bluetooth Socket Constructor
    12-24 13:25:01.955 I/BluetoothSocket_MTK(14387): [JSR82] type=1 fd=-1 auth=false encrypt=false port=-1
    12-24 13:25:01.959 I/BluetoothSocket_MTK(14387): [JSR82] connect: do SDP
    12-24 13:25:01.972 I/BluetoothSocket_MTK(14387): [JSR82] SdpHelper::onRfcommChannelFound: channel=-1
    12-24 13:25:01.974 I/BluetoothSocket_MTK(14387): [JSR82] close
    12-24 13:25:01.974 I/BluetoothSocket_MTK(14387): [JSR82] readLock got.
    12-24 13:25:01.975 I/BluetoothSocket_MTK(14387): [JSR82] Start to aquire writeLock.
    12-24 13:25:01.975 I/BluetoothSocket_MTK(14387): [JSR82] writeLock got.

Sign In or Register to comment.