[Android Software Development] Geeks Empire:
Bluetooth [Data Transferring]

​

Using Bluetooth can be so Helpful in many cases.

Send to & Receive Data from many devices. SmartPhone,any Bluetooth stations & etc.

But If you want to have control of what happen with data sharing with Bluetooth you must learn How to Transfer Data through Bluetooth Socket. For many simple cases Android Provided Intent base Bluetooth Sharing But It is not enough. So I will write here how to use Bluetooth for both situation.

### Let Start Coding ###
​

Additionally in this tutorial you will learn How to access Files & Converting to byteArray.

. from Bottom to Top /Watch Client

Start New Project & Leave everything to default.

After Sync Gradle Open AndroidManifest.xml to Add Permissions.

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/> //to Enable/Disable Bluetooth
<uses-permission android:name="android.permission.BLUETOOTH"/>

Also for Android API 23+ you should ask for Runtime Permission too.

if(Build.VERSION.SDK_INT >= 23) {
String[] Permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.BLUETOOTH, Manifest.permission.BLUETOOTH_ADMIN};
requestPermissions(Permissions, 10296);
}

Then Open your Bluetooth Activity and Add this Code.

Here is Simple Way to Share File using Bluetooth. Like other Intent sharing Just Invoke its intent-filter

Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setType("text/plain");//define type
File f = new File(Environment.getExternalStorageDirectory(), "DIR_TO_FILE");
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(f));
startActivity(intent);

Little More Complex Way is to use Bluetooth Socket.

It finds List of All Paired Bluetooth Devices.

BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
// Loop through paired devices
for (BluetoothDevice device : pairedDevices) {
// Add the name and address to an array adapter to show in a ListView
System.out.println(device.getName() + "\n" + device.getAddress() + "\n\n");
}
}

to connect to another device you need to have its MacAddress.

String macAddress = new BluetoothDevice().getAddress();
BluetoothDevice [COLOR=Red][B]device [/B][/COLOR]= mBluetoothAdapter.getRemoteDevice(macAddress);

After this you should invoke instance of Socket to start Connection.

NOTE: Nothing should define on Main View. In other hand you have to use Thread(); for background Process.

Connecting [B]connectThread [/B]= new Connecting([COLOR=Red][B]device [/B][/COLOR]/*Pass Device Information to Thread()*/);
[B]connectThread[/B].start();

private class Connecting extends Thread {
private final BluetoothSocket [COLOR=Red]bluetoothSocket [/COLOR];
private final BluetoothDevice bluetoothDevice ;
private String mSocketType;

public ConnectThread(BluetoothDevice device) {
bluetoothDevice = device;
[B]BluetoothSocket [/B][COLOR=Red]tmp [/COLOR]= null;

try {
[COLOR=Red]tmp [/COLOR]= device.createRfcommSocketToServiceRecord(MY_UUID_SECURE);
catch (IOException e) {e.printStackTrace();}
[COLOR=Red]bluetoothSocket [/COLOR]= tmp;
}

public void run() {
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
[COLOR=Red][B]bluetoothSocket.connect();[/B][/COLOR]
} catch (IOException e) {
try {
[COLOR=Red]bluetoothSocket[/COLOR].close();
} catch (IOException e2) {e2.printStackTrace();break;}
return;
}
[COLOR=RoyalBlue][B]//Handle Actions After Connecting.
//Ask to Write & Read Socket Data
// SO HERE you should start another Thread(); to handle [COLOR=Red]Write/Read[/COLOR] Process
[/B][/COLOR][COLOR=RoyalBlue][B][COLOR=Red][COLOR=SeaGreen]globalConnectedThread [/COLOR]= new ConnectedThread(socket, socketType).start();[/COLOR][/B][/COLOR][COLOR=RoyalBlue][COLOR=Black]//pass the socket Information[/COLOR][/COLOR]}
public void cancel() {
try {
bluetoothSocket.close();
} catch (IOException e) {e.printStackTrace();}
}
}

So Check this snippet Carefully and Read Comments

private class ConnectedThread extends Thread {
private final BluetoothSocket [B]mmSocket[/B];
private final InputStream [COLOR=Red][B]mmInStream[/B][/COLOR];
private final OutputStream [COLOR=Red][B]mmOutStream[/B][/COLOR];

public ConnectedThread(BluetoothSocket socket, String socketType) {
[B]mmSocket [/B]= socket;[COLOR=Red] //you call it on Connecting thread after successful connecting process So pass the socket to this thread[/COLOR]
InputStream [B]tmpIn [/B]= null;
OutputStream [B]tmpOut [/B]= null;

// Get the BluetoothSocket input and output streams
try {
tmpIn = [B]socket[/B].getInputStream();
tmpOut = [B]socket[/B].getOutputStream();
} catch (IOException e) {}
[COLOR=Red][B]mmInStream [/B][/COLOR]= tmpIn;
[COLOR=Red][B]mmOutStream [/B][/COLOR]= tmpOut;
}

public void run() {
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (/*define indicator to check if sockets are connected you can do it by using a integer or boolean var*/) {
try {
// Read from the InputStream in loop until connection not lost
bytes = [B]mmInStream[/B].[B][COLOR=Red]read([COLOR=Black]buffer[/COLOR])[/COLOR][/B];
// Send the obtained bytes to the UI Activity OR SAVE Data
//so we call a function save data to file.
saveFile("name_of_file");
//pass read data to views
} catch (IOException e) {
// Start the service over to restart listening mode
this.start();
break;
}
}
}

public void [B]write[/B](byte[] buffer) {//next snippet will show how to use it.
try {
[B]mmOutStream[/B].[COLOR=Red][B]write([COLOR=Black]buffer[/COLOR])[/B][/COLOR];
// Share the sent message back to the UI Activity
} catch (IOException e) {}
}
public void cancel() {
try {
[B]mmSocket[/B].close();
} catch (IOException e) {}
}
}

To Write to Socket from File you must read content of File (that is why we got permission for reading sdcard) and convert it to array of byte and pass to socket. So define ConnectedThread and call write(byte[]) function

ConnectedThread connectedThread = [COLOR=SeaGreen][B]globalConnectedThread[/B][/COLOR];//this is the value defined after socket connected.
byte[] sendData = [B]readFile[/B]("file_name_on_sdcard").getBytes();//Check out next snippet for readFile Function
[B]connectedThread.[COLOR=Red]write[/COLOR](sendData);[/B]

This Function to read simple text file from sdcard

public String [B]readFile[/B](String fileName){
String temp = "";

File G = new File(Environment.getExternalStorageDirectory(), fileName);
if(!G.exists()){
System.out.println(fileName + " NOT FOUND");
}
else{
try{
BufferedReader br = new BufferedReader(new FileReader(G));

int c;
temp = "";
while((c = br.read()) != -1){
temp = temp + Character.toString((char)c);
}
}
catch(Exception e){e.printStackTrace();}
}

return temp;//content of file
}

In other hand you must Handle read data on socket and save it.

public void [B]saveFile[/B](String fileName, String content){
File G = new File(Environment.getExternalStorageDirectory(), fileName);

try {
FileOutputStream fOut = new FileOutputStream(G);
fOut.write((content).getBytes());

fOut.flush();
fOut.close();
}
catch (IOException e) {
e.printStackTrace();
}
}

NOTE: As you may realized this tutorial contained functionality for both Client & Server Side of Bluetooth connection.

So when compiled your test app, install it on 2 devices & pair them.

Download SourceCode & Enjoy

Don't forget to Hit Thanks

​