use of android.bluetooth.BluetoothServerSocket in project kdeconnect-android by KDE.
the class BluetoothLink method sendPackageInternal.
private boolean sendPackageInternal(NetworkPackage np, final Device.SendPackageStatusCallback callback, PublicKey key) {
try {
BluetoothServerSocket serverSocket = null;
if (np.hasPayload()) {
UUID transferUuid = UUID.randomUUID();
serverSocket = BluetoothAdapter.getDefaultAdapter().listenUsingRfcommWithServiceRecord("KDE Connect Transfer", transferUuid);
JSONObject payloadTransferInfo = new JSONObject();
payloadTransferInfo.put("uuid", transferUuid.toString());
np.setPayloadTransferInfo(payloadTransferInfo);
}
if (key != null) {
try {
np = RsaHelper.encrypt(np, key);
} catch (Exception e) {
callback.onFailure(e);
return false;
}
}
sendMessage(np);
if (serverSocket != null) {
BluetoothSocket transferSocket = serverSocket.accept();
try {
serverSocket.close();
int idealBufferLength = 4096;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && transferSocket.getMaxReceivePacketSize() > 0) {
idealBufferLength = transferSocket.getMaxReceivePacketSize();
}
byte[] buffer = new byte[idealBufferLength];
int bytesRead;
long progress = 0;
InputStream stream = np.getPayload();
while ((bytesRead = stream.read(buffer)) != -1) {
progress += bytesRead;
transferSocket.getOutputStream().write(buffer, 0, bytesRead);
if (np.getPayloadSize() > 0) {
callback.onProgressChanged((int) (100 * progress / np.getPayloadSize()));
}
}
transferSocket.getOutputStream().flush();
stream.close();
} catch (Exception e) {
callback.onFailure(e);
return false;
} finally {
try {
transferSocket.close();
} catch (IOException ignored) {
}
}
}
callback.onSuccess();
return true;
} catch (Exception e) {
callback.onFailure(e);
return false;
}
}
Aggregations