Skip to content

Instantly share code, notes, and snippets.

@69VR69
Last active March 19, 2019 06:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 69VR69/abc9a6efb513255f109b2a2983670bab to your computer and use it in GitHub Desktop.
Save 69VR69/abc9a6efb513255f109b2a2983670bab to your computer and use it in GitHub Desktop.
package fr.corporation.bapas.bapas;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.UUID;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class ThreadConnection extends MainActivity
{
Button BT_button;
Handler h;
final int RECEIVE_MESSAGE = 1;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder sb = new StringBuilder();
private ConnectedThread mConnectedThread;
private static final String TAG = "bluetooth2";
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static String address = "98:D3:31:FD:13:4C";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bt_connector);
BT_button = findViewById(R.id.BT_button);
// Handler code
h = new Handler() {
@Override
public void publish(LogRecord record) {}
@Override
public void flush() {}
@Override
public void close() throws SecurityException {}
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case RECEIVE_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
BT_button.setEnabled(true);
}
break;
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter();
checkBTState();
BT_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mConnectedThread.write("1");
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
try
{
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return(BluetoothSocket) m.invoke(device, MY_UUID);
}
catch (Exception e)
{
Log.e(TAG, "Could not create Insecure RFComm Connection", e);
}
return device.createRfcommSocketToServiceRecord(MY_UUID);
}
@Override
public void onResume()
{
super.onResume();
// Set up a pointer to the remote node using it's address.
BluetoothDevice device = btAdapter.getRemoteDevice(address);
// Two things are needed to make a connection:
// A MAC address, which we got above.
// A Service ID or UUID. In this case we are using the UUID for SPP.
try
{
btSocket = createBluetoothSocket(device);
}
catch (IOException e)
{
errorExit("In onResume() and socket create failed: " + e.getMessage() + ".");
}
btAdapter.cancelDiscovery();
try
{
btSocket.connect();
Log.d(TAG, "....Connection ok...");
} catch (IOException e)
{
Log.d(TAG, "...Error connect cause: " + e.getMessage() + "...");
try
{
btSocket.close();
Log.d(TAG, "....Socket close...");
}
catch (IOException e2)
{
errorExit("In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
}
@Override
public void onPause()
{
super.onPause();
try
{
btSocket.close();
}
catch (IOException e2)
{
errorExit("In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void checkBTState()
{
// Check for Bluetooth support and then check to make sure it is turned on
// Emulator doesn't support Bluetooth and will return null
if(btAdapter==null)
{
errorExit("Bluetooth not support");
} else {
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
private void errorExit(String message){
Toast.makeText(getBaseContext(), "Fatal Error" + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private class ConnectedThread extends Thread
{
private final OutputStream mmOutStream;
ConnectedThread(BluetoothSocket socket)
{
OutputStream tmpOut = null;
// Get the output stream
// Member streams are final
try
{
tmpOut = socket.getOutputStream();
} catch (IOException ignored) {}
mmOutStream = tmpOut;
}
void write(String message)
{
Log.d(TAG, "... Data to send: " + message + "...");
byte[] msgBuffer = message.getBytes();
try
{
mmOutStream.write(msgBuffer);
Toast.makeText(ThreadConnection.this, "ENVOIE", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment