@LVitA

Как автоматически сопрягать Bluetooth?

Доброго времени суток!
В моем проекте необходимо реализовать автоматическое сопряжение маячка и Android устройства по Bluetooth, в интернете узнал, что это реально сделать методом setPin, но у меня ничего не получается, помогите разобраться пожалуйста!
Android 4.0.4 (HTC Desire S) и модуль Bluetooth HC-05.

информацию нашел по этим ссылкам тут и тут.

Мой код
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.UUID;

public class MainActivity extends AppCompatActivity {

    private Button mRedButton;
    private Button mGreenButton;
    private boolean isRed = false;
    private boolean isGreen = false;

    private BluetoothSocket mClientSocket;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mRedButton   = (Button) findViewById(R.id.red_button);
        mGreenButton = (Button) findViewById(R.id.green_button);

        String enableBT = BluetoothAdapter.ACTION_REQUEST_ENABLE;
        startActivityForResult(new Intent(enableBT), 0);

        BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();

        try{
            BluetoothDevice device = bluetooth.getRemoteDevice("98:D3:32:10:80:73");

            Method convert = device.getClass().getMethod("convertPinToBytes", String.class);

            byte[] pinBytes = (byte[]) convert.invoke(device, "1234");

            Method setPin = device.getClass().getMethod("setPin", byte[].class);
            Boolean success = (Boolean) setPin.invoke(device, pinBytes);

            if (success)
                Toast.makeText(MainActivity.this, "Success to add the PIN.", Toast.LENGTH_SHORT).show();

//            device.getClass().getMethod("setPairingConfirmation", boolean.class).invoke(device, true);
//
//            setBluetoothPairingPin(device, String.valueOf(pin));

            //Инициируем соединение с устройством
            Method m = device.getClass().getMethod(
                    "createRfcommSocket", new Class[] {int.class});

            mClientSocket = (BluetoothSocket) m.invoke(device, 1);
            mClientSocket.connect();

            //В случае появления любых ошибок, выводим в лог сообщение
        } catch (IOException e) {
            Log.d("BLUETOOTH", e.getMessage());
        } catch (SecurityException e) {
            Log.d("BLUETOOTH", e.getMessage());
        } catch (NoSuchMethodException e) {
            Log.d("BLUETOOTH", e.getMessage());
        } catch (IllegalArgumentException e) {
            Log.d("BLUETOOTH", e.getMessage());
        } catch (IllegalAccessException e) {
            Log.d("BLUETOOTH", e.getMessage());
        } catch (InvocationTargetException e) {
            Log.d("BLUETOOTH", e.getMessage());
        }

        Toast.makeText(MainActivity.this, "Конект", Toast.LENGTH_SHORT).show();

        mRedButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Действие при нажатие
                try {
                    OutputStream outStream = mClientSocket.getOutputStream();

                    if(isRed){
                        outStream.write(70);
                        isRed = false;
                    }
                    else
                    {
                        outStream.write(71);
                        isRed = true;
                    }

                } catch (IOException e) {
                    Log.d("BLUETOOTH", e.getMessage());
                }

                Toast.makeText(MainActivity.this, "Красный светодиод", Toast.LENGTH_SHORT).show();
            }
        });

        mGreenButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // Действие при нажатие
                try {
                    OutputStream outStream = mClientSocket.getOutputStream();

                    if(isGreen){
                        outStream.write(60);
                        isGreen = false;
                    }
                    else
                    {
                        outStream.write(61);
                        isGreen = true;
                    }

                } catch (IOException e) {
                    Log.d("BLUETOOTH", e.getMessage());
                }
                Toast.makeText(MainActivity.this, "Зеленый светодиод", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

  • Вопрос задан
  • 443 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы