在android中通过蓝牙发送事件

时间:2016-11-23 11:50:31

标签: android events bluetooth

我在两部手机之间创建了一个蓝牙连接(配对设备没有我的应用程序)。如何将事件发送到手机,如屏幕锁定/音量增加

BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); if (bluetoothAdapter.isEnabled()){ handler.sendEmptyMessageDelayed(connectionCheckTimeout,30000); BluetoothReciever bluetoothReciever = new BluetoothReciever(); bluetoothReciever.registerBluetoothRecieverForConnection(this,this); SocketThread socketThread = SocketThread.getInstance(); socketThread.registerBluetoothRecieverForCommunication(this,this); Thread thread = new Thread(socketThread); thread.start(); }

我的套接字线程类在这里,我正在获得一个连接的设备(不仅仅是配对)。 现在我必须将音量增大/减小等事件发送到不运行我的应用程序的其他设备。

public class SocketThread implements Runnable {
private static SocketThread ourInstance = new SocketThread();
BluetoothAdapter bluetoothAdapter;
BluetoothDevice device;
BluetoothSocket bluetoothSocket;
static BluetoothSocketListener bluetoothSocketListener;
public static SocketThread getInstance() {
    return ourInstance;
}

private SocketThread() {
}

@Override
public void run() {

    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    device = connectedDevice(bluetoothAdapter);
    if (device!=null){
       // Toast.makeText(getApplicationContext(),"connected to "+device.getName(),Toast.LENGTH_SHORT).show();
        if (bluetoothSocketListener!=null) {
            bluetoothSocketListener.deviceIsConnected(device,bluetoothSocket);
        }

        try {
            bluetoothSocket.getOutputStream().flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }else{
        if (bluetoothSocketListener!=null) {
            bluetoothSocketListener.deviceIsNotConnected();
        }
    }

}

private BluetoothDevice connectedDevice(BluetoothAdapter bluetoothAdapter){
    if (bluetoothAdapter == null)
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (bluetoothAdapter.getBondedDevices().size() == 0)
        return null;
    //now create socket to all paired devices. Check if connected. then return true
    Set<BluetoothDevice> btDevices = bluetoothAdapter.getBondedDevices();

    for (BluetoothDevice device : btDevices){
        Log.d("main activity"," trying to create socket for paired device "+device.getName());
        try {
            bluetoothSocket
                    = device.createRfcommSocketToServiceRecord(device.getUuids()[0].getUuid());
            bluetoothSocket.connect();
            if (bluetoothSocket.isConnected()){
                return device;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;
}

public void registerBluetoothRecieverForCommunication(Context context, BluetoothSocketListener bluetoothSocketListener){
    this.bluetoothSocketListener = bluetoothSocketListener;
}

}

1 个答案:

答案 0 :(得分:0)

蓝牙发送原始数据。显然,你必须以某种方式解析那些并转换成你的应用程序中的调用,做一些工作