2016-11-23 77 views
-3

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

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

我的插座Thread类是在这里,我得到一个连接的设备(不仅仅是配对)。 现在,我必须将音量上/下的事件发送到其他设备,该设备不运行我的应用程序。

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

}

+2

到目前为止你做了什么?请分享您的代码 – Sachith

+0

Sachith,请找到更新后的代码 –

回答

0

蓝牙发送的原始数据。显然,你必须解析这些不知何故,并转化为您的应用程序中的调用,做一些工作

+0

在这里,我必须发送原始数据,如音量增加/减少事件。怎么做? –