2016-11-23 72 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

在這裏,我必須發送原始數據,如音量增加/減少事件。怎麼做? –