0

Gostaria de enviar o número 1 via bluetooth no android, já fiz a parte de conexão falta enviar
- esse é o código fonte

    public void  conectar(ProgressBar loading, BluetoothSocket socket) { 
        loading.Visibility = Android.Views.ViewStates.Visible;      

        try {

            socket.Connect();

        }
        catch (Exception)
        {
            loading.Visibility = Android.Views.ViewStates.Gone;
            Toast.MakeText(this, "Não foi possivel conectar", ToastLength.Long).Show();


        }
        try
        {
            var output = socket.InputStream;
            loading.Visibility = Android.Views.ViewStates.Gone;

            Toast.MakeText(this, "pode escrever", ToastLength.Long).Show();
            byte[] buffer = new byte[1024];

            output.Write(buffer, 1, 1);

        }
        catch (Exception) { 
        Toast.MakeText(this, "Não foi possivel enviar a mensagem", ToastLength.Long).Show();
        loading.Visibility = Android.Views.ViewStates.Gone;
        }





    }

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

        SetContentView(Resource.Layout.tela);

        BluetoothAdapter adaptador = BluetoothAdapter.DefaultAdapter; // procura o adap. bluetooth 

        TextView aparelho1 = FindViewById<TextView>(Resource.Id.aparelho1);
        TextView aparelhoconfig = FindViewById<TextView>(Resource.Id.aparelhoconfig);
        TextView aparelho2 = FindViewById<TextView>(Resource.Id.aparelho2);
        TextView aparelho2config = FindViewById<TextView>(Resource.Id.aparelho2config);
        RelativeLayout layout1 = FindViewById<RelativeLayout>(Resource.Id.layoutaparelho1);
        RelativeLayout layout2 = FindViewById<RelativeLayout>(Resource.Id.layoutaparelho2);
        ProgressBar loading = FindViewById<ProgressBar>(Resource.Id.progressBar1);

        loading.Visibility = Android.Views.ViewStates.Gone;

        if (adaptador == null)
        {
            Toast.MakeText(this, "Esse aparelho não tem bluetooth", ToastLength.Long).Show();
        }
        else {
            if (adaptador.IsEnabled == true)
            {
                ICollection<BluetoothDevice> aparelhos = adaptador.BondedDevices;
                BluetoothDevice[] apa = new BluetoothDevice[aparelhos.Count];
                ParcelUuid[] chaves;
                BluetoothSocket[] socket = new BluetoothSocket[aparelhos.Count];
                int i = 0;


                foreach (BluetoothDevice aparelho in aparelhos)
                {
                    apa[i] = aparelho;
                    chaves = aparelho.GetUuids();
                    socket[i] = aparelho.CreateInsecureRfcommSocketToServiceRecord(chaves[i].Uuid);
                    i++;

                }
                if (apa.Length > 0)
                {

                    aparelho1.Append(apa[0].Name);
                    aparelhoconfig.Append(apa[0].Address);
                    /// <summary>
                    /// evento ao clicar no outro relative layout1
                    /// </summary>

                    layout1.Click += delegate
                    {
                        Toast.MakeText(this,"clicou",ToastLength.Short).Show();
                        conectar(loading,socket[0]);
                    };
                    //final

                    if (apa.Length > 1)
                    {
                        aparelho2.Append(apa[1].Name);
                        aparelhoconfig.Append(apa[1].Address);
                        /// <summary>
                        /// evento ao clicar no outro relative layout2
                        /// </summary>
                        layout2.Click += delegate
                        {


                        };
                        //final
                    }


                }




            }
            else {
                Toast.MakeText(this, "Ative o bluetooth para continuar", ToastLength.Long).Show();

            }



        }
    }`

1 Resposta 1

1

Quando você conectar com dois (ou mais) dispositivos, cada um terá uma BluetoothSocket conectado. Basicamente você teria que usar o ConnectedThread passando como parâmetro o seu socket, e aí que começa o divertimento. Veja abaixo:

ConnectedThread mConnectedThread = new ConnectedThread(socket);
mConnectedThread.start();

Para ler e gravar dados, é necessário usar read(byte[]) e write(byte[]). Abaixo segue um exemplo básico de como você deve usar, utilizando dois botões:

    btnDesliga.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mConnectedThread.write("0");              
      }
    });

    btnLiga.setOnClickListener(new OnClickListener() {
      public void onClick(View v) {
        mConnectedThread.write("1");
      }
    });

Abraços.

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .