How to establish connection from android app to other device by Bluetooth Classic HID? - java

I'm an Android-noob and unfortunately I have to create an application that will send and receive data from a device (ESP32) using Bluetooth Classic HID. I am able to find the device but I can't establish the connection in any way. I've been struggling with this for a few days, maybe someone could point me the way?
Android permissions
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
MainActivity class
#SuppressLint({"MissingPermission"})
public class MainActivity extends AppCompatActivity {
public static final String TAG = "MainActivity";
public static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//public static final UUID MY_UUID = UUID.fromString("00001124-0000-1000-8000-00805F9B34FB");
Boolean secured = false;
public BluetoothAdapter mBluetoothAdapter;
public ArrayList<BluetoothDevice> availableDevices = new ArrayList();
public BluetoothDevice connectedDevice;
public String usePin = "";
public static String MY_DEVICE_NAME = "MY_DEVICE";
public static String MY_DEVICE_MAC_ADDRESS = "B4:8A:0A:4E:FF:8E";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
// Device doesn't support Bluetooth
Log.e(TAG, "Device doesn't support Bluetooth");
return;
}
if (!mBluetoothAdapter.isEnabled()) {
// Bluetooth is not enabled, ask the user to enable it
Log.d(TAG, "Bluetooth is not enabled");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
return;
}
mBluetoothAdapter.enable();
}
IntentFilter filter = new IntentFilter("android.bluetooth.device.action.FOUND");
filter.addAction("android.bluetooth.adapter.action.DISCOVERY_FINISHED");
registerReceiver(discoverFinishHandler, filter);
IntentFilter filter2 = new IntentFilter("android.bluetooth.device.action.PAIRING_REQUEST");
registerReceiver(pairRequestHandler, filter2);
// Buttons
Button btnToggle = findViewById(R.id.btnToggle);
btnToggle.setOnClickListener(v -> {
if(mBluetoothAdapter.isDiscovering())
{
Log.e(TAG, "Stop discovering bt devices");
mBluetoothAdapter.cancelDiscovery();
}
else
{
Log.e(TAG, "Start discovering bt devices");
StartDiscovery();
}
});
Button connectToggle = findViewById(R.id.connectToggle);
connectToggle.setOnClickListener(v -> {
Log.e(TAG, "Connecting...");
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
connectedDevice = mBluetoothAdapter.getRemoteDevice(MY_DEVICE_MAC_ADDRESS);
if(connectedDevice != null && connectedDevice.getName() != null)
{
Log.e(TAG, connectedDevice.getName() + " FOUND!");
BluetoothThread bluetoothThread = new BluetoothThread(connectedDevice, secured);
bluetoothThread.start();
}
else
{
Log.e(TAG, "DEVICE NOT FOUND!");
}
});
Button logdevicesButton = findViewById(R.id.logdevicesButton);
logdevicesButton.setOnClickListener(v -> {
Log.e(TAG, "Avaliable devices:");
for (BluetoothDevice device : availableDevices)
{
Log.e(TAG, device.getName() + " | " + device.getAddress());
}
Set<BluetoothDevice> pairedDevices = BluetoothAdapter.getDefaultAdapter().getBondedDevices();
if (pairedDevices.size() < 1) {
Log.e(TAG, "No bonded devieces.");
}
else
{
Log.e(TAG, "Bonded devices:");
if (pairedDevices.size() > 0) {
for (BluetoothDevice d : pairedDevices) {
Log.e(TAG, d.getName() + " | " + d.getAddress());
}
}
}
if (pairedDevices.size() < 1)
{
Log.e(TAG, "No connected devices.");
}
else
{
LogConnectedDevices(BluetoothProfile.GATT, "GATT");
LogConnectedDevices(BluetoothProfile.GATT_SERVER, "GATT SERVER");
}
});
}
public void StartDiscovery() {
availableDevices.clear();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
mBluetoothAdapter.startDiscovery();
Log.e(TAG, "Start Discovery...");
}
public void LogConnectedDevices(Integer profile, String profileName)
{
BluetoothManager bluetoothManager = (BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE);
List<BluetoothDevice> devices = bluetoothManager.getConnectedDevices(profile);
if(devices.size()<1)
{
Log.e(TAG, "No connected devices [" + profileName + "]");
return;
}
Log.e(TAG, "Connected devices [" + profileName + "]:");
for (BluetoothDevice d : devices)
{
Log.e(TAG, d.getName() + " | " + d.getAddress());
}
}
private final BroadcastReceiver discoverFinishHandler = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if ("android.bluetooth.device.action.FOUND".equals(action))
{
BluetoothDevice device = (BluetoothDevice) intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
if (!availableDevices.contains(device))
{
availableDevices.add(device);
Log.e(TAG, "Discover: " + device.getName() + "(" + device.getAddress() + ")");
}
}
else if ("android.bluetooth.adapter.action.DISCOVERY_FINISHED".equals(action))
{
Log.e(TAG, "Discovery Finished ");
}
}
};
private final BroadcastReceiver pairRequestHandler = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
if (!usePin.equals("")) {
String action = intent.getAction();
if (action.equals("android.bluetooth.device.action.PAIRING_REQUEST")) {
try {
Log.e(TAG, "Start Connecting with PIN....");
this.abortBroadcast();
BluetoothDevice device = (BluetoothDevice)intent.getParcelableExtra("android.bluetooth.device.extra.DEVICE");
byte[] pinBytes = usePin.getBytes(StandardCharsets.UTF_8);
device.setPin(pinBytes);
device.setPairingConfirmation(true);
} catch (Exception var6) {
Log.e(TAG, "Error occurs when trying to auto pair");
var6.printStackTrace();
}
}
}
}
};
}
Bluetooth thread
#SuppressLint({"MissingPermission"})
public class BluetoothThread extends Thread {
private BluetoothSocket mSocket;
private InputStream mInStream;
BluetoothDevice mDevice;
public BluetoothThread(final BluetoothDevice device, final Boolean secured) {
BluetoothSocket tmp = null;
mDevice = device;
try {
if(secured)
tmp = device.createRfcommSocketToServiceRecord(MainActivity.MY_UUID);
else
tmp = device.createInsecureRfcommSocketToServiceRecord(MainActivity.MY_UUID);
} catch (IOException e) {
Log.e(MainActivity.TAG, "Socket create() failed", e);
}
mSocket = tmp;
}
public void run() {
Log.e(MainActivity.TAG, mDevice.getName() + " bluetooth thread started");
try {
mSocket.connect();
mInStream = mSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
while (true) {
Log.e(MainActivity.TAG, "reading data...");
try {
Log.e(MainActivity.TAG, "reading data...");
bytes = mInStream.read(buffer);
// Do something with the received data
Log.e(MainActivity.TAG, "recieved data: " + String.valueOf(bytes));
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error reading from input stream", e);
break;
}
}
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error connecting to device", e);
}
}
public void cancel() {
try {
mSocket.close();
} catch (IOException e) {
Log.e(MainActivity.TAG, "Error closing socket", e);
}
}
}

Related

How can i make bluetooth connection in every Activity?

I am developing an app which sends data to the android with Bluetooth. I can send data and see from the ardunio side. I can connect the device but when I go to the another activity in the app connection has been lost. How can I keep connection open? In the Second class I can connected the device and send the data, if I have another activity how can i use active Bluetooth connection and send data?
private String mConnectedDeviceName = null;
private StringBuffer mOutStringBuffer;
private BluetoothAdapter mBluetoothAdapter = null;
private BluetoothChatService mChatService = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
// Get local Bluetooth adapter
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
// If the adapter is null, then Bluetooth is not supported
FragmentActivity activity = getActivity();
if (mBluetoothAdapter == null && activity != null) {
Toast.makeText(activity, "Bluetooth is not available", Toast.LENGTH_LONG).show();
activity.finish();
}
}
#Override
public void onStart() {
super.onStart();
if (mBluetoothAdapter == null) {
return;
}
// If BT is not on, request that it be enabled.
// setupChat() will then be called during onActivityResult
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
// Otherwise, setup the chat session
} else if (mChatService == null) {
setupChat();
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mChatService != null) {
mChatService.stop();
}
}
#Override
public void onResume() {
super.onResume();
if (mChatService != null) {
// Only if the state is STATE_NONE, do we know that we haven't started already
if (mChatService.getState() == BluetoothChatService.STATE_NONE) {
// Start the Bluetooth chat services
mChatService.start();
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container,
#Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_bluetooth_chat, container, false);
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
rad_saat = view.findViewById(R.id.rad_saat);
rad_Co2 = view.findViewById(R.id.rad_CO2);
rad_sicaklik = view.findViewById(R.id.rad_sicaklik);
rad_Manuel = view.findViewById(R.id.rad_manuel);
opn_spinner = view.findViewById(R.id.spn_options);
radioGroup = view.findViewById(R.id.radioGroup);
spnCrd_Options = view.findViewById(R.id.spnCrd_Options);
crd_GonderButton = view.findViewById(R.id.crd_GonderButton);
txt_GonderButton = view.findViewById(R.id.txt_GonderButton);
rad_saat.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButton();
}
});
rad_Co2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButton();
}
});
rad_sicaklik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButton();
}
});
rad_Manuel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButton();
}
});
radioGroup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
checkButton();
}
});
crd_GonderButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
sendButton();
}
});
txt_GonderButton.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View v) {
sendButton();
}
});
}
private void setupChat() {
Log.d(TAG, "setupChat()");
// Initialize the array adapter for the conversation thread
FragmentActivity activity = getActivity();
if (activity == null) {
return;
}
// Initialize the BluetoothChatService to perform bluetooth connections
mChatService = new BluetoothChatService(activity, mHandler);
// Initialize the buffer for outgoing messages
mOutStringBuffer = new StringBuffer();
}
private void ensureDiscoverable() {
if (mBluetoothAdapter.getScanMode() !=
BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
}
}
public void sendMessage(String message) {
// Check that we're actually connected before trying anything
if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
Toast.makeText(getActivity(), R.string.not_connected, Toast.LENGTH_SHORT).show();
return;
}
// Check that there's actually something to send
if (message.length() > 0) {
// Get the message bytes and tell the BluetoothChatService to write
byte[] send = message.getBytes();
mChatService.write(send);
// Reset out string buffer to zero and clear the edit text field
mOutStringBuffer.setLength(0);
}
}
private TextView.OnEditorActionListener mWriteListener
= new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
// If the action is a key-up event on the return key, send the message
if (actionId == EditorInfo.IME_NULL && event.getAction() == KeyEvent.ACTION_UP) {
String message = view.getText().toString();
sendMessage(message);
}
return true;
}
};
private void setStatus(int resId) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(resId);
}
private void setStatus(CharSequence subTitle) {
FragmentActivity activity = getActivity();
if (null == activity) {
return;
}
final ActionBar actionBar = activity.getActionBar();
if (null == actionBar) {
return;
}
actionBar.setSubtitle(subTitle);
}
private void messageHandler()
{
}
public void checkButton(){
saatList = new ArrayList<String>(Arrays.asList(new String[]{"00:00 - 03:00","03:00 -06:00 ","06:00 - 09:00","09:00 - 12:00","12:00 - 15:00","15:00 - 18:00","18:00 - 21:00","21:00 - 00:00"}));
manuelList = new ArrayList<String>(Arrays.asList(new String[]{"KAPALI","AÇIK"}));
if(rad_saat.isChecked()){
atananList = saatList;
spnCrd_Options.setVisibility(View.VISIBLE);
opn_spinner.setVisibility(View.VISIBLE);
}
if(rad_Manuel.isChecked()){
atananList = manuelList;
spnCrd_Options.setVisibility(View.VISIBLE);
opn_spinner.setVisibility(View.VISIBLE);
}
if(rad_Co2.isChecked()){
opn_spinner.setVisibility(View.GONE);
spnCrd_Options.setVisibility(View.GONE);
}
if(rad_sicaklik.isChecked()){
opn_spinner.setVisibility(View.GONE);
spnCrd_Options.setVisibility(View.GONE);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, atananList);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
opn_spinner.setAdapter(adapter);
}
#RequiresApi(api = Build.VERSION_CODES.O)
public void sendButton() {
System.out.println("1. Bluettoth adapter" + mBluetoothAdapter);
modelClass = new ModelClass();
modelClass.setmBluetoothAdapter(mBluetoothAdapter);
modelClass.setmChatService(mChatService);
modelClass.setmConnectedDeviceName(mConnectedDeviceName);
modelClass.setmOutStringBuffer(mOutStringBuffer);
Intent intent = new Intent(getActivity(), SendCordinates.class);
startActivity(intent);
}
/**
* The Handler that gets information back from the BluetoothChatService
*/
private final Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
FragmentActivity activity = getActivity();
switch (msg.what) {
case Constants.MESSAGE_STATE_CHANGE:
switch (msg.arg1) {
case BluetoothChatService.STATE_CONNECTED:
setStatus(getString(R.string.title_connected_to, mConnectedDeviceName));
//textViewReceived.setText("Received:");
break;
case BluetoothChatService.STATE_CONNECTING:
setStatus(R.string.title_connecting);
break;
case BluetoothChatService.STATE_LISTEN:
case BluetoothChatService.STATE_NONE:
setStatus(R.string.title_not_connected);
break;
}
break;
case Constants.MESSAGE_WRITE:
break;
case Constants.MESSAGE_READ:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
receiveBuffer += readMessage;
if(receiveBuffer.contains("\n")) {
receiveBuffer = receiveBuffer.substring(0, receiveBuffer.length() - 1);
messageHandler();
receiveBuffer = "";
}
break;
case Constants.MESSAGE_DEVICE_NAME:
// save the connected device's name
mConnectedDeviceName = msg.getData().getString(Constants.DEVICE_NAME);
if (null != activity) {
Toast.makeText(activity, "Connected to "
+ mConnectedDeviceName, Toast.LENGTH_SHORT).show();
}
break;
case Constants.MESSAGE_TOAST:
if (null != activity) {
Toast.makeText(activity, msg.getData().getString(Constants.TOAST),
Toast.LENGTH_SHORT).show();
}
break;
}
}
};
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CONNECT_DEVICE_SECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, true);
}
break;
case REQUEST_CONNECT_DEVICE_INSECURE:
// When DeviceListActivity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
connectDevice(data, false);
}
break;
case REQUEST_ENABLE_BT:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupChat();
} else {
// User did not enable Bluetooth or an error occurred
Log.d(TAG, "BT not enabled");
FragmentActivity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, R.string.bt_not_enabled_leaving,
Toast.LENGTH_SHORT).show();
activity.finish();
}
}
}
}
private void connectDevice(Intent data, boolean secure) {
// Get the device MAC address
Bundle extras = data.getExtras();
if (extras == null) {
return;
}
String address = extras.getString(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
// Get the BluetoothDevice object
BluetoothDevice device = mBluetoothAdapter.getRemoteDevice(address);
// Attempt to connect to the device
mChatService.connect(device, secure);
}
#Override
public void onCreateOptionsMenu(#NonNull Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.bluetooth_chat, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.secure_connect_scan: {
// Launch the DeviceListActivity to see devices and do scan
Intent serverIntent = new Intent(getActivity(), DeviceListActivity.class);
startActivityForResult(serverIntent, REQUEST_CONNECT_DEVICE_SECURE);
return true;
}
case R.id.discoverable: {
// Ensure this device is discoverable by others
ensureDiscoverable();
return true;
}
}
return false;
}
public class BluetoothChatService {
private static final String TAG = "BluetoothChatService";
private static final String NAME_SECURE = "BluetoothChatSecure";
private static final String NAME_INSECURE = "BluetoothChatInsecure";
private static final UUID MY_UUID_SECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private static final UUID MY_UUID_INSECURE =
UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// Member fields
private final BluetoothAdapter mAdapter;
private final Handler mHandler;
private AcceptThread mSecureAcceptThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private ConnectedThread mConnectedThread;
private int mState;
private int mNewState;
public static final int STATE_NONE = 0; // we're doing nothing
public static final int STATE_LISTEN = 1; // now listening for incoming connections
public static final int STATE_CONNECTING = 2; // now initiating an outgoing connection
public static final int STATE_CONNECTED = 3; // now connected to a remote device
public BluetoothChatService(Context context, Handler handler) {
mAdapter = BluetoothAdapter.getDefaultAdapter();
mState = STATE_NONE;
mNewState = mState;
mHandler = handler;
}
private synchronized void updateUserInterfaceTitle() {
mState = getState();
Log.d(TAG, "updateUserInterfaceTitle() " + mNewState + " -> " + mState);
mNewState = mState;
// Give the new state to the Handler so the UI Activity can update
mHandler.obtainMessage(Constants.MESSAGE_STATE_CHANGE, mNewState, -1).sendToTarget();
}
public synchronized int getState() {
return mState;
}
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
// Cancel any thread currently running a connection
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
// Start the thread to listen on a BluetoothServerSocket
if (mSecureAcceptThread == null) {
mSecureAcceptThread = new AcceptThread(true);
mSecureAcceptThread.start();
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread(false);
mInsecureAcceptThread.start();
}
// Update UI title
updateUserInterfaceTitle();
}
public synchronized void connect(BluetoothDevice device, boolean secure) {
Log.d(TAG, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (mState == STATE_CONNECTING) {
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
mConnectThread = new ConnectThread(device, secure);
mConnectThread.start();
// Update UI title
updateUserInterfaceTitle();
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice
device, final String socketType) {
Log.d(TAG, "connected, Socket Type:" + socketType);
// Cancel the thread that completed the connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
mConnectedThread = new ConnectedThread(socket, socketType);
mConnectedThread.start();
Message msg = mHandler.obtainMessage(Constants.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(Constants.DEVICE_NAME, device.getName());
msg.setData(bundle);
mHandler.sendMessage(msg);
// Update UI title
updateUserInterfaceTitle();
}
public synchronized void stop() {
Log.d(TAG, "stop");
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mConnectedThread != null) {
mConnectedThread.cancel();
mConnectedThread = null;
}
if (mSecureAcceptThread != null) {
mSecureAcceptThread.cancel();
mSecureAcceptThread = null;
}
if (mInsecureAcceptThread != null) {
mInsecureAcceptThread.cancel();
mInsecureAcceptThread = null;
}
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (mState != STATE_CONNECTED) return;
r = mConnectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private void connectionFailed() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Unable to connect device");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
}
private void connectionLost() {
// Send a failure message back to the Activity
Message msg = mHandler.obtainMessage(Constants.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(Constants.TOAST, "Device connection was lost");
msg.setData(bundle);
mHandler.sendMessage(msg);
mState = STATE_NONE;
// Update UI title
updateUserInterfaceTitle();
// Start the service over to restart listening mode
BluetoothChatService.this.start();
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private String mSocketType;
public AcceptThread(boolean secure) {
BluetoothServerSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
try {
if (secure) {
tmp = mAdapter.listenUsingRfcommWithServiceRecord(NAME_SECURE,
MY_UUID_SECURE);
} else {
tmp = mAdapter.listenUsingInsecureRfcommWithServiceRecord(
NAME_INSECURE, MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "listen() failed", e);
}
mmServerSocket = tmp;
mState = STATE_LISTEN;
}
public void run() {
Log.d(TAG, "Socket Type: " + mSocketType +
"BEGIN mAcceptThread" + this);
setName("AcceptThread" + mSocketType);
BluetoothSocket socket;
while (mState != STATE_CONNECTED) {
try {
// This is a blocking call and will only return on a
// successful connection or an exception
socket = mmServerSocket.accept();
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "accept() failed", e);
break;
}
if (socket != null) {
synchronized (BluetoothChatService.this) {
switch (mState) {
case STATE_LISTEN:
case STATE_CONNECTING:
// Situation normal. Start the connected thread.
connected(socket, socket.getRemoteDevice(),
mSocketType);
break;
case STATE_NONE:
case STATE_CONNECTED:
// Either not ready or already connected. Terminate new socket.
try {
socket.close();
} catch (IOException e) {
Log.e(TAG, "Could not close unwanted socket", e);
}
break;
}
}
}
}
Log.i(TAG, "END mAcceptThread, socket Type: " + mSocketType);
}
public void cancel() {
Log.d(TAG, "Socket Type" + mSocketType + "cancel " + this);
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "Socket Type" + mSocketType + "close() of server failed", e);
}
}
}
private class ConnectThread extends Thread {
private final BluetoothSocket mmSocket;
private final BluetoothDevice mmDevice;
private String mSocketType;
public ConnectThread(BluetoothDevice device, boolean secure) {
mmDevice = device;
BluetoothSocket tmp = null;
mSocketType = secure ? "Secure" : "Insecure";
try {
if (secure) {
tmp = device.createRfcommSocketToServiceRecord(
MY_UUID_SECURE);
} else {
tmp = device.createInsecureRfcommSocketToServiceRecord(
MY_UUID_INSECURE);
}
} catch (IOException e) {
Log.e(TAG, "Socket Type: " + mSocketType + "create() failed", e);
}
mmSocket = tmp;
mState = STATE_CONNECTING;
}
public void run() {
Log.i(TAG, "BEGIN mConnectThread SocketType:" + mSocketType);
setName("ConnectThread" + mSocketType);
// Always cancel discovery because it will slow down a connection
mAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
} catch (IOException e2) {
Log.e(TAG, "unable to close() " + mSocketType +
" socket during connection failure", e2);
}
connectionFailed();
return;
}
synchronized (BluetoothChatService.this) {
mConnectThread = null;
}
// Start the connected thread
connected(mmSocket, mmDevice, mSocketType);
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect " + mSocketType + " socket failed", e);
}
}
}
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket, String socketType) {
Log.d(TAG, "create ConnectedThread: " + socketType);
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(TAG, "temp sockets not created", e);
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
mState = STATE_CONNECTED;
}
public void run() {
Log.i(TAG, "BEGIN mConnectedThread");
byte[] buffer = new byte[1024];
int bytes;
// Keep listening to the InputStream while connected
while (mState == STATE_CONNECTED) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
// Send the obtained bytes to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "disconnected", e);
connectionLost();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* #param buffer The bytes to write
*/
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constants.MESSAGE_WRITE, -1, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "close() of connect socket failed", e);
}
}
}
Create an actual service which can be bound from multiple activities.
class BluetoothService : Service() {
private val binder = LocalBinder()
override fun onBind(intent: Intent): IBinder? {
return binder
}
inner class LocalBinder : Binder() {
fun getService() : BluetoothService {
return this#BluetoothService
}
}
}
private var bluetoothService : BluetoothService? = null
private val serviceConnection: ServiceConnection = object : ServiceConnection {
override fun onServiceConnected(componentName: ComponentName, service:IBinder) {
bluetoothService = (service as LocalBinder).getService()
bluetoothService?.let { bluetooth ->
// ...
}
}
override fun onServiceDisconnected(componentName: ComponentName) {
bluetoothService = null
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val serviceIntent = Intent(this, BluetootService::class.java)
bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE)
}
See BLE case for the inspiration.
Have you ever tried to use something like dagger? You can create a repository that you istantiate at the start of application.
Then if you need to use it in activity you can inject it with something like this:
#Inject lateinit var bluetoothRepository: BluetoothRepository

Issue with Bluetooth through transferring data between Android and Arduino

As you can see I made an app which sends data from an Android device to a Bluetooth module. Everything works perfectly except for one little thing: every time I want to open the app I should've already turned on Bluetooth through my phone settings or the app will crash, and I have to reopen it after turning on Bluetooth so it will run properly.
I've designed a Bluetooth click listener button myself but it still crashes while I enable it via button.
Can you help me find the mistake in my code?
public class MainActivity extends AppCompatActivity {
private static final String TAG = "bluetooth1";
Button btnsend ;
EditText edttext ;
Button btnOnOff;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private OutputStream outStream = null;
// SPP UUID service
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// MAC-address of Bluetooth module (you must edit this line)
private static String address = "20:16:06:28:17:83";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnsend = (Button) findViewById(R.id.btnsend);
edttext = (EditText) findViewById(R.id.edttxt);
btnOnOff = (Button) findViewById(R.id.btnOnOff);
btAdapter = BluetoothAdapter.getDefaultAdapter();
btnOnOff.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
if (btAdapter.isEnabled()) {
btAdapter.disable();
Toast.makeText(getApplicationContext(), " Disabling Bluetooth", Toast.LENGTH_SHORT).show();
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,1);
Toast.makeText(getApplicationContext(), " Enabling Bluetooth", Toast.LENGTH_SHORT).show();
}
}
});
edttext.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_VARIATION_PASSWORD);
edttext.setTransformationMethod(new NumericKeyBoardTransformationMethod());
btnsend.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String dataTransmit = edttext.getText().toString();
if (dataTransmit != null) {
sendData(dataTransmit);
} else {
Toast.makeText(getApplicationContext(), "Please type something first", Toast.LENGTH_SHORT).show();
}
}
});
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
if(Build.VERSION.SDK_INT >= 10) {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", new Class[] { UUID.class });
return (BluetoothSocket) m.invoke(device, MY_UUID);
} catch (Exception e) {
Toast.makeText(getBaseContext(), "Could not Insecure", Toast.LENGTH_SHORT).show();
}
}
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 e1) {
errorExit("Fatal Error", "In onResume() and socket create failed: " + e1.getMessage() + ".");
}
btAdapter.cancelDiscovery();
// Establish the connection. This will block until it connects.
Toast.makeText(getBaseContext(), "Connecting", Toast.LENGTH_SHORT).show();
try {
btSocket.connect();
Toast.makeText(getBaseContext(), "Connecting Ok", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onResume() and unable to close socket during connection failure" + e2.getMessage() + ".");
}
}
// Create a data stream so we can talk to server.
try {
outStream = btSocket.getOutputStream();
} catch (IOException e) {
errorExit("Fatal Error", "In onResume() and output stream creation failed:" + e.getMessage() + ".");
}
}
#Override
public void onPause() {
super.onPause();
if (outStream != null) {
try {
outStream.flush();
} catch (IOException e) {
errorExit("Fatal Error", "In onPause() and failed to flush output stream: " + e.getMessage() + ".");
}
}
try {
btSocket.close();
} catch (IOException e2) {
errorExit("Fatal Error", "In onPause() and failed to close socket." + e2.getMessage() + ".");
}
}
private void errorExit(String title, String message) {
Toast.makeText(getBaseContext(), title + " - " + message, Toast.LENGTH_LONG).show();
finish();
}
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("20:16:06:28:17:83"))
msg = msg + ".\n\nUpdate your server address from 20:16:06:28:17:83 to the correct address on line 35 in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
}
You have to check if BT is enabled. Try with this:
protected void checkBTState() {
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBtAdapter == null) {
String message = getResources().getText(R.string.bluetooth_not_supported).toString();
Toast.makeText(getBaseContext(), message, Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
// Prompt user to turn on Bluetooth //
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
Put it in onResume
#Override
public void onResume() {
super.onResume();
checkBTState();
// ...
// some code
// ...
}

Send data from my App android to my Raspberry PI 3

Hi i am actually working on app to send command line on the terminal of my Raspberry PI 3.
I wouldlike when i press the button save for example to send the command "ls" to my RPI3.
Acutally, I've got some problem with my object BluetoothconnectionService.
I think I can't send data because my object is not declared on my activity "Accueil" ? `
BluetoothConnectionService.java :
public class BluetoothConnectionService {
private static final String TAG = "BluetoothConnectionServ";
private static final String appName = "MYAPP";
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
private final BluetoothAdapter mBluetoothAdapter;
private ConnectedThread mConnectedThread;
private AcceptThread mInsecureAcceptThread;
private ConnectThread mConnectThread;
private BluetoothDevice mmDevice;
private UUID deviceUUID;
ProgressDialog mProgressDialog;
Context mContext;
public BluetoothConnectionService(Context context) {
mContext = context;
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
start();
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket mmServerSocket;
private BluetoothSocket socket = null;
private InputStream mmInStream;
private String device;
public AcceptThread(){
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try{
tmp = mBluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(appName, MY_UUID_INSECURE);
Log.d(TAG, "AcceptThread: Setting up Server using: " + MY_UUID_INSECURE);
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
mmServerSocket = tmp;
}
public void run(){
Log.d(TAG, "run: AcceptThread Running.");
BluetoothSocket socket = null;
try{
// This is a blocking call and will only return on a
// successful connection or an exception
Log.d(TAG, "run: RFCOM server socket start.....");
socket = mmServerSocket.accept();
Log.d(TAG, "run: RFCOM server socket accepted connection.");
}catch (IOException e){
Log.e(TAG, "AcceptThread: IOException: " + e.getMessage() );
}
//talk about this is in the 3rd
if(socket != null){
connected(socket,mmDevice);
}
Log.i(TAG, "END mAcceptThread ");
}
public void cancel() {
Log.d(TAG, "cancel: Canceling AcceptThread.");
try {
mmServerSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: Close of AcceptThread ServerSocket failed. " + e.getMessage() );
}
}
}
private class ConnectThread extends Thread {
private BluetoothSocket mmSocket;
public ConnectThread(BluetoothDevice device, UUID uuid) {
Log.d(TAG, "ConnectThread: started.");
mmDevice = device;
deviceUUID = uuid;
}
public void run(){
BluetoothSocket tmp = null;
Log.i(TAG, "RUN mConnectThread ");
// Get a BluetoothSocket for a connection with the
// given BluetoothDevice
try {
Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
+MY_UUID_INSECURE );
tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
} catch (IOException e) {
Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket " + e.getMessage());
}
mmSocket = tmp;
// Always cancel discovery because it will slow down a connection
mBluetoothAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
// This is a blocking call and will only return on a
// successful connection or an exception
mmSocket.connect();
Log.d(TAG, "run: ConnectThread connected.");
} catch (IOException e) {
// Close the socket
try {
mmSocket.close();
Log.d(TAG, "run: Closed Socket.");
} catch (IOException e1) {
Log.e(TAG, "mConnectThread: run: Unable to close connection in socket " + e1.getMessage());
}
Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " + MY_UUID_INSECURE );
}
//will talk about this in the 3rd video
connected(mmSocket,mmDevice);
}
public void cancel() {
try {
Log.d(TAG, "cancel: Closing Client Socket.");
mmSocket.close();
} catch (IOException e) {
Log.e(TAG, "cancel: close() of mmSocket in Connectthread failed. " + e.getMessage());
}
}
}
public synchronized void start() {
Log.d(TAG, "start");
// Cancel any thread attempting to make a connection
if (mConnectThread != null) {
mConnectThread.cancel();
mConnectThread = null;
}
if (mInsecureAcceptThread == null) {
mInsecureAcceptThread = new AcceptThread();
mInsecureAcceptThread.start();
}
}
public void startClient(BluetoothDevice device,UUID uuid){
Log.d(TAG, "startClient: Started.");
//initprogress dialog
mProgressDialog = ProgressDialog.show(mContext,"Connecting Bluetooth"
,"Please Wait...",true);
mConnectThread = new ConnectThread(device, uuid);
mConnectThread.start();
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(TAG, "ConnectedThread: Starting.");
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
int error=2;
int i;
//dismiss the progressdialog when connection is established
try{
mProgressDialog.dismiss();
error=1;
}catch (NullPointerException e){
e.printStackTrace();
error=0;
}
try {
tmpIn = mmSocket.getInputStream();
tmpOut = mmSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run(){
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.read(buffer);
final String strReceived = new String(buffer,0,bytes);
final String strByteCnt = String.valueOf(bytes) + "bytes received. \n";
// Send the obtained bytes to the UI activity
} catch (IOException e) {
Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
break;
}
}
}
//Call this from the main activity to send data to the remote device
public void write(byte[] bytes) {
try {
mmOutStream.write(bytes);
} catch (IOException e) {
Log.e(TAG, "write: Error writing to output stream. " + e.getMessage() );
}
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
private void connected(BluetoothSocket mmSocket, BluetoothDevice mmDevice) {
Log.d(TAG, "connected: Starting.");
// Start the thread to manage the connection and perform transmissions
mConnectedThread = new ConnectedThread(mmSocket);
mConnectedThread.start();
}
public void write(byte[] out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
Log.d(TAG, "write: Write Called.");
//perform the write
mConnectedThread.write(out);
}
}
MainActivity.java :`
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener{
// variables
private static final String TAG = "MainActivity";
private Uri[] mFileUris = new Uri[10];
private static final UUID MY_UUID_INSECURE = UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66");
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
// Bluetooth object
BluetoothAdapter mBluetoothAdapter;
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// variables button
Button btnStartConnection;
Button scan;
// Image button
ImageButton btnONOFF;
// Variables affichages
StringBuilder messages;
ListView lvNewDevices;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Constructor
mBTDevices = new ArrayList<>();
messages = new StringBuilder();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
// list findViewbyID
btnONOFF = (ImageButton) findViewById(R.id.bluetooth_on_off);
scan = (Button) findViewById(R.id.scan);
btnStartConnection = (Button) findViewById(R.id.Connect);
lvNewDevices = (ListView) findViewById(R.id.lvNewDevices);
// divers
registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(MainActivity.this);
// ON/OFF BLUETOOTH
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
enableDisableBT();
}
});
// SCAN
scan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnDiscover();
btnEnableDisable_Discoverable();
}
});
// CONNECTION
btnStartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startConnection();
}
});
}
// 4 BroadcastReceiver
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mBroadcastReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
// When discovery finds a device
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
switch(state){
case BluetoothAdapter.STATE_OFF:
Log.d(TAG, "onReceive: STATE OFF");
break;
case BluetoothAdapter.STATE_TURNING_OFF:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING OFF");
break;
case BluetoothAdapter.STATE_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE ON");
break;
case BluetoothAdapter.STATE_TURNING_ON:
Log.d(TAG, "mBroadcastReceiver1: STATE TURNING ON");
break;
}
}
}
};
private final BroadcastReceiver mBroadcastReceiver2 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED)) {
int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE, BluetoothAdapter.ERROR);
switch (mode) {
//Device is in Discoverable Mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Enabled.");
break;
//Device not in discoverable mode
case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Able to receive connections.");
break;
case BluetoothAdapter.SCAN_MODE_NONE:
Log.d(TAG, "mBroadcastReceiver2: Discoverability Disabled. Not able to receive connections.");
break;
case BluetoothAdapter.STATE_CONNECTING:
Log.d(TAG, "mBroadcastReceiver2: Connecting....");
break;
case BluetoothAdapter.STATE_CONNECTED:
Log.d(TAG, "mBroadcastReceiver2: Connected.");
break;
}
}
}
};
private BroadcastReceiver mBroadcastReceiver3 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
Log.d(TAG, "onReceive: ACTION FOUND.");
if (action.equals(BluetoothDevice.ACTION_FOUND)){
BluetoothDevice device = intent.getParcelableExtra (BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
Log.d(TAG, "onReceive: " + device.getName() + ": " + device.getAddress());
mDeviceListAdapter = new DeviceListAdapter(context, R.layout.device_adapter_view, mBTDevices);
lvNewDevices.setAdapter(mDeviceListAdapter);
}
}
};
/**
* Broadcast Receiver that detects bond state changes (Pairing status changes)
*/
private final BroadcastReceiver mBroadcastReceiver4 = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if(action.equals(BluetoothDevice.ACTION_BOND_STATE_CHANGED)){
BluetoothDevice mDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
//3 cases:
//case1: bonded already
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDED){
Log.d(TAG, "BroadcastReceiver: BOND_BONDED.");
//inside BroadcastReceiver4
mBTDevice = mDevice;
}
//case2: creating a bone
if (mDevice.getBondState() == BluetoothDevice.BOND_BONDING) {
Log.d(TAG, "BroadcastReceiver: BOND_BONDING.");
}
//case3: breaking a bond
if (mDevice.getBondState() == BluetoothDevice.BOND_NONE) {
Log.d(TAG, "BroadcastReceiver: BOND_NONE.");
}
}
}
};
//create method for starting connection
public void startConnection(){
startBTConnection(mBTDevice,MY_UUID_INSECURE);
goToAcceuil();
}
public void startBTConnection(BluetoothDevice device, UUID uuid){
Log.d(TAG, "startBTConnection: Initializing RFCOM Bluetooth Connection.");
mBluetoothConnection.startClient(device,uuid);
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable() {
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover() {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
mBTDevice = mBTDevices.get(i);
mBluetoothConnection = new BluetoothConnectionService(MainActivity.this);
}
}
public void goToAcceuil (){
Intent intent = new Intent (this,Accueil.class);
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("mBTDevice",mBTDevice);
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
startActivity(intent);
}
protected void onDestroy() {
Log.d(TAG, "onDestroy: called.");
super.onDestroy();
unregisterReceiver(mBroadcastReceiver1);
unregisterReceiver(mBroadcastReceiver2);
unregisterReceiver(mBroadcastReceiver3);
unregisterReceiver(mBroadcastReceiver4);
}
}
Accueil.java :
public class Accueil extends AppCompatActivity {
// Bluetooth
BluetoothConnectionService mBluetoothConnection;
BluetoothDevice mBTDevice;
// String
String name_device1;
String adress_device1;
String freq_value1;
String item_spin1;
String item_spin;
// Image Button
ImageButton btn_back;
ImageButton btn_accueil;
ImageButton btn_voice;
ImageButton btn_scan;
ImageButton btn_settings;
// Button
Button btn_send_freq;
// Textview
TextView name_device;
TextView adress_device;
// Edit Text
EditText freq_value;
// List
ArrayAdapter<String> adapter;
List<String> list;
// Spinner
Spinner spinner1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accueil);
// Variables from other activity
name_device1= getIntent().getStringExtra("DEVICE_NAME");
adress_device1=getIntent().getStringExtra("DEVICE_ADRESS");
mBTDevice=getIntent().getExtras().getParcelable("mBTDevice");
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
freq_value1=getIntent().getStringExtra("VALUE_FREQ");
item_spin1=getIntent().getStringExtra("VALUE_SPIN");
// findView by ID
name_device= (TextView) findViewById(R.id.name_device2);
adress_device= (TextView) findViewById(R.id.adress_device2);
btn_back = (ImageButton) findViewById(R.id.back1);
btn_accueil = (ImageButton) findViewById(R.id.accueil1);
btn_voice = (ImageButton) findViewById(R.id.voice1);
btn_scan = (ImageButton) findViewById(R.id.scan1);
btn_settings= (ImageButton) findViewById(R.id.settings1);
btn_send_freq = (Button) findViewById(R.id.send_freq1);
freq_value = (EditText) findViewById(R.id.value_freq1);
spinner1=(Spinner) findViewById(R.id.spinner_freq);
// SetText
name_device.setText(name_device1);
adress_device.setText(adress_device1);
freq_value.setText(freq_value1);
// Spinner
list=new ArrayList<String>();
list.add("MHz");
list.add("GHz");
adapter= new ArrayAdapter<String>(this,R.layout.spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner1.setAdapter(adapter);
btn_send_freq.setOnClickListener(new View.OnClickListener() { // Bouton Save
#Override
public void onClick(View view) {
send_freq();
}
});
btn_back.setOnClickListener(new View.OnClickListener() { // Bouton RETOUR
#Override
public void onClick(View view) {
gotoBack();
}
});
btn_accueil.setOnClickListener(new View.OnClickListener() { // Bouton ACCUEIL
#Override
public void onClick(View view) {
gotoAccueil();
}
});
btn_voice.setOnClickListener(new View.OnClickListener() { // Bouton VOICE
#Override
public void onClick(View view) {
gotoVoice();
}
});
btn_scan.setOnClickListener(new View.OnClickListener() { // Bouton SCAN
#Override
public void onClick(View view) {
gotoScan();
}
});
btn_settings.setOnClickListener(new View.OnClickListener() { // Bouton SETTINGS
#Override
public void onClick(View view) {
gotoSettings();
}
});
}
// Fonction
public void send_freq()
{
byte[] bytesToSend="sudo rm azertyy".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
// Fonctions onglets
public void gotoBack() // Onglet PRECEDENT
{
Intent intent = new Intent (this,MainActivity.class);
startActivity(intent);
}
public void gotoAccueil() // Onglet ACCUEIL
{
Intent intent = new Intent (this,Accueil.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoVoice() // Onglet VOICE
{
Intent intent = new Intent (this,voice.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoScan() // Onglet SCAN
{
Intent intent = new Intent (this,Scan.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
public void gotoSettings() // Onglet SETTINGS
{
Intent intent = new Intent (this,connection.class);
// get selected vale and start new activity
item_spin= spinner1.getSelectedItem().toString();
intent.putExtra("DEVICE_NAME", mBTDevice.getName());
intent.putExtra("DEVICE_ADRESS", mBTDevice.getAddress());
intent.putExtra("VALUE_FREQ", freq_value.getText().toString());
intent.putExtra("VALUE_SPIN", item_spin);
intent.putExtra("mBTDevice",mBTDevice);
startActivity(intent);
}
}
With this function, I wouldlike to send "ls" on the terminal of my RPI3 :`
public void send_freq()
{
byte[] bytesToSend="ls".getBytes();
mBluetoothConnection.write(bytesToSend);
byte[] NewLine = "\n".getBytes();
mBluetoothConnection.write(NewLine);
}
But I don't understand, I have some error like that :enter image description here
I tried to resolve that with Parcelable, but no sucess... enter image description here
So my code does not work. My app crash all time...
Thanks for any help !
From my understanding you have a button inside your MainActivity.java that opens another Activity (Accueil.java) via an Intent. And in doing so, you are sending an Intent with extras to transfer data between them.
An Intent can only take an object as an extra if it implements the Parcelable interface.
Here you attempted to add BluetoothConnectionService that does not implement Parcelable.
You commented it out because it was giving you the error you showed in the screenshot.
//intent.putExtra("mBluetoothConnection",mBluetoothConnection);
Which means inside of Accueil.java your mBluetoothConnection will be null causing your app to crash.
//mBluetoothConnection=getIntent().getExtras().getParcelable("mBluetoothConnection");
Solutions to this problem would be to either
Find a way to make BluetoothConnectionService implement Parcelable
If possible, re-instantiate BluetoothConnectionService.

Bluetooth Connection between LeJOS EV3 and Android

I'm having trouble connecting my smartphone to my EV3 over bluetooth using an app.
My situation:
I'm developing an App to send simple Strings to the EV3 which runs with leJOS 0.9.1-aplu11.
My Problem is, I'm not really familiar with Bluetooth, so my app or my receiver-software doesn't work as well.
My goal:
My goal is to create a Listener on the EV3 which is permanant listening for Strings from the app and an App that sends the strings when I press a button.
I hope you can help me.
I'm from germany so don't wonder about my beautifull writing skills!
Here is my Code:
App:
public class MainActivity extends AppCompatActivity {
private final static String TAG = "MainActivity";
private BluetoothAdapter mBluetoothAdapter;
private static BluetoothDevice mDevice;
private Button mSendBN;
private final static String MY_UUID = "00001101-0000-1000-8000-00805f9b34fb";
private static BluetoothSocket mSocket = null;
private static String mMessage = "Stop";
private static PrintStream sender;
private void findBrick() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter
.getBondedDevices();
for (BluetoothDevice device : pairedDevices) {
if (device.getName().equals("EV3"))
this.mDevice = device;
}
}
private void initBluetooth() {
Log.d(TAG, "Checking Bluetooth...");
if (mBluetoothAdapter == null) {
Log.d(TAG, "Device does not support Bluetooth");
mSendBN.setClickable(false);
} else {
Log.d(TAG, "Bluetooth supported");
}
if (!mBluetoothAdapter.isEnabled()) {
mSendBN.setClickable(false);
Log.d(TAG, "Bluetooth not enabled");
} else {
Log.d(TAG, "Bluetooth enabled");
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Toast.makeText(this, "SpeechRecognizer gestartet", Toast.LENGTH_SHORT).show();
setContentView(R.layout.activity_main);
mSendBN = (Button) findViewById(R.id.button);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
initBluetooth();
findBrick();
if (mDevice == null) {
mSendBN.setClickable(false);
Toast.makeText(this, "No Devices found or BT disabled", Toast.LENGTH_SHORT).show();
Log.d("onC", "Connected to " + mDevice);
}
try {
createSocket();
} catch (IOException e) {
e.printStackTrace();
}
startService();
}
private void startService() {
if (PermissionHandler.checkPermission(this, PermissionHandler.RECORD_AUDIO)) {
Intent i = new Intent(this, BackgroundRecognizerService.class);
startService(i);
}
}
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == PermissionHandler.RECORD_AUDIO && grantResults.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
startService();
}
}
}
public static void onSend(View view) throws IOException {
try {
OutputStream os = mSocket.getOutputStream();
sender = new PrintStream(os);
Log.d("onSend", "Message = " + mMessage);
sender.println(mMessage);
sender.flush();
Log.d("onSend", "Message sent");
mSocket.close();
Log.d("onSend", "Socket closed");
} catch (IllegalStateException | NullPointerException e) {
e.printStackTrace();
}
}
public void createSocket() throws IOException {
try {
UUID uuid = UUID.fromString(MY_UUID);
mSocket = mDevice.createRfcommSocketToServiceRecord(uuid);
} catch (IOException e) {
e.printStackTrace();
}
Log.d("createSocket", "Adapter");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mSocket.connect();
OutputStream os = mSocket.getOutputStream();
sender = new PrintStream(os);
Log.d("createSocket", "Fertig, " + "Socket: " + mSocket + " Sender: " + sender + " OutputStream: " + os + " mDevice: " + mDevice.getName());
}
protected void onDestroy() {
super.onDestroy();
Log.d("onDestroy", "App beendet");
try {
mSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
Log.d("onDestroy", "App vollständig beendet");
}
}
EV3:
public class BTJ {
public static void main(String[] args) {
BTConnector connector = new BTConnector();
System.out.println("0. Auf Signal warten");
NXTConnection conn = connector.waitForConnection(0, NXTConnection.RAW);
InputStream is = conn.openInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String message = "";
while (true){
System.out.println("1. Schleife gestartet");
message = "";
try {
message = br.readLine();
System.out.println("2. Message: " + message);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}
}
I have the answer..!
public class BTJ {
public static void main(String[] args) {
BTConnector connector = new BTConnector();
System.out.println("0. Auf Signal warten");
NXTConnection conn = connector.waitForConnection(0, NXTConnection.RAW);
InputStream is = conn.openInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is), 1);
String message = "";
while (true){
System.out.println("1. Schleife gestartet");
message = "";
try {
message = br.readLine();
System.out.println("2. Message: " + message);
} catch (IOException e) {
e.printStackTrace(System.out);
}
}
}

outtring initated in BluetoothcommandService.java

I, will be asking how to combine/fuse 2 java files if,the outstring was initiated in the BluetoothcommandService.java file I will be editing my Post sir and post my MainActivity.java file and BluetoothCommandService.java file..I just doent know how to combine it..
this is the MainActivity.java
public class MainActivity extends Activity {
//public class MainActivity extends Activity implements OnClickListener {
BluetoothAdapter BTAdapter;
BluetoothDevice BTDevice;
private TextView title;
private static final int REQUEST_DEVICE_CONNECT = 1;
private static final int REQUEST_ENABLE_BLUETOOTH = 2;
private BluetoothCommandService commandService = null;
private String connectedDeviceName = null;
//Message types sent from the Handler
public static final int MESSAGE_STATE_CHANGE = 1;
public static final int MESSAGE_READ = 2;
public static final int MESSAGE_WRITE = 3;
public static final int MESSAGE_DEVICE_NAME = 4;
public static final int MESSAGE_TOAST = 5;
public static final int RECIEVE_MESSAGE = 6;
//Will be used in BluetoothCommandSrvice jave file
public static final String TOAST = "toast";
public static final String DEVICENAME = "device name";
//#######for the controller
public static final String tagStateCTRL = "Controller";
private OutputStream outStream = null;
private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
private static String address = "00:00:00:00:00:00"; // Insert your bluetooth devices MAC address
private StringBuilder sb = new StringBuilder();
Button btn_d1_on, btn_d1_off;
//for changing the device_1 name
TextView device1;
Button change;
EditText renameDevice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main); gi move sa ubos sa request window
// Set up the window layout
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.activity_main);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
title = (TextView) findViewById(R.id.title_left_text); // Set up the custom title
title.setText(R.string.app_name); // Set up the custom title
title = (TextView) findViewById(R.id.title_right_text); // Set up the custom title
//Button openButton = (Button)findViewById(R.id.open);
//##########for the controller
btn_d1_on = (Button) findViewById(R.id.device1_on);
btn_d1_off = (Button) findViewById(R.id.device1_off);
//########for changing the device_1 name
device1 = (TextView)findViewById(R.id.device1);
change = (Button)findViewById(R.id.buttonTest);
renameDevice = (EditText)findViewById(R.id.editTest);
change.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
String change_device1 = renameDevice.getText().toString();
device1.setText(change_device1);
}
});
// AUTO REQUEST OF ENABLING THE BLUETOOTH
BTAdapter = BluetoothAdapter.getDefaultAdapter();
//A code that will detect if BT is enabled otherwise will require it.
if (BTAdapter == null)
{
//Toast.makeText(context, text, duration)
Toast.makeText(this, "No Bluetooth adapter is available.", Toast.LENGTH_LONG).show();
finish();
return;
}
//##########for the controller
btn_d1_on.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("1");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show()
btn_d1_on.setEnabled(false);
sendData("1");
}
});
//##########for the controller
btn_d1_off.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
//sendData("0");
//Toast msg = Toast.makeText(getBaseContext(), "The device is now On", Toast.LENGTH_SHORT);
//msg.show();
btn_d1_off.setEnabled(false);
sendData("0");
}
});
}
#Override
protected void onStart() {
super.onStart();
//Requesting Bluetooth automatically when its not yet enabled.
if (!BTAdapter.isEnabled())
{
Intent enableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableIntent, 0);
startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
}
else
{
if (commandService == null)
setupCommand();
}
}
//if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
//{
//Intent discoverableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
//discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 500);
//startActivity(discoverableIntent);
//}
#Override
protected void onResume() {
super.onResume();
if (commandService != null)
{
if (commandService.getState() == BluetoothCommandService.stateNothing)
{
commandService.start();
}
}
}
private void setupCommand()
{
commandService = new BluetoothCommandService(this, bluetoothHandler);
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (commandService != null)
commandService.stop();
}
private void ensureDiscoverable()
{
//Get the current Bluetooth scan mode of the local Bluetooth adapter. The Bluetooth scan mode determines if the local adapter is connectable and/or discoverable from remote Bluetooth devices.
if (BTAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE)
{
Intent ensureDiscoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
ensureDiscoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(ensureDiscoverableIntent);
}
}
//This gets information back from the "BluetoothChatService"/"BluetoothCommandService"
//#SuppressLint("HandlerLeak")
//private final Handler bluetoothHandler = new Handler(new Handler.Callback()
#SuppressLint("HandlerLeak")
public final Handler bluetoothHandler = new Handler()
{
#Override
public void handleMessage(android.os.Message msg)
{
switch (msg.what)
{
case MESSAGE_STATE_CHANGE:
switch (msg.arg1)
{
case BluetoothCommandService.stateConnected:
title.setText(R.string.title_connectedTo);
title.append(connectedDeviceName);
break;
case BluetoothCommandService.stateConnecting:
title.setText(R.string.title_connecting);
break;
case BluetoothCommandService.stateListen:
case BluetoothCommandService.stateNothing:
title.setText(getString(R.string.title_notConnected));
break;
}
break;
case MESSAGE_DEVICE_NAME:
connectedDeviceName = msg.getData().getString(DEVICENAME);
Toast.makeText(getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT).show();
break;
case MESSAGE_TOAST:
Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
break;
case RECIEVE_MESSAGE: // if receive message
byte[] readBuf = (byte[]) msg.obj;
String strIncom = new String(readBuf, 0, msg.arg1); // create string from bytes array
sb.append(strIncom); // append string
int endOfLineIndex = sb.indexOf("\r\n"); // determine the end-of-line
if (endOfLineIndex > 0) { // if end-of-line,
//String sbprint = sb.substring(0, endOfLineIndex); // extract string
sb.delete(0, sb.length()); // and clear
//txtArduino.setText("Data from Arduino: " + sbprint); // update TextView
//1/4/14
btn_d1_on.setEnabled(true);
btn_d1_off.setEnabled(true);
}
//Log.d(TAG, "...String:"+ sb.toString() + "Byte:" + msg.arg1 + "...");
break;
}
//return false;
}
};
//});
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_DEVICE_CONNECT:
// When DeviceList Activity returns with a device to connect
if (resultCode == Activity.RESULT_OK) {
// Get the device MAC address
String address = data.getExtras()
.getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
// Get the BLuetoothDevice object
BluetoothDevice device = BTAdapter.getRemoteDevice(address);
// Attempt to connect to the device
commandService.connect(device);
}
break;
case REQUEST_ENABLE_BLUETOOTH:
// When the request to enable Bluetooth returns
if (resultCode == Activity.RESULT_OK) {
// Bluetooth is now enabled, so set up a chat session
setupCommand();
} else {
// User did not enable Bluetooth or an error occured
Toast.makeText(this, R.string.notEnabledBluetooth, Toast.LENGTH_SHORT).show();
finish();
}
}
}
#Override
//Creating an Option Menu for connectivity and discoverability of a BT device
public boolean onCreateOptionsMenu(Menu menu)
{
//MenuInflater is a class
MenuInflater OptionMenu = getMenuInflater();
//OptionMenu.inflate(menuRes, menu)
OptionMenu.inflate(R.menu.main, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.connect:
Intent serverIntent = new Intent(this, DeviceList.class);
//this.startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
return true;
case R.id.discoverable:
ensureDiscoverable();
return true;
//case R.id.abouts:
//Intent intentabouts = new Intent(this,abouts.class);
//return true;
//default:
//return super.onOptionsItemSelected(item);
}
return false;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
{
commandService.write(BluetoothCommandService.VOL_UP);
return true;
}
else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
{
commandService.write(BluetoothCommandService.VOL_DOWN);
return true;
}
return super.onKeyDown(keyCode, event);
}
//#########################################
private void sendData(String message)
//public void sendData(String message)
{
byte[] msgBuffer = message.getBytes();
Log.d(tagStateCTRL, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
}
catch (IOException e){
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address in the java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + myUUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}
private void errorExit(String title, String message){
Toast msg = Toast.makeText(getBaseContext(),
title + " - " + message, Toast.LENGTH_SHORT);
msg.show();
finish();
}
//#########################################
}
This is the BluetoothCommanService.java
public class BluetoothCommandService {
private final BluetoothAdapter BTAdapter;
private final Handler bluetoothHandler;
private int connectionState;
private ConnectThread connectThread;
//private ConnectedThread connectedThread;
public ConnectedThread connectedThread;
//***Added 12/27/13
private AcceptThread mainAcceptThread;
//connection states of the Bluetooth
public static final int stateNothing = 0; //doing nothing
public static final int stateListen = 1; //listening for incoming connections
public static final int stateConnecting = 2; //initiating an outgoing connection
public static final int stateConnected = 3;
//constants that indicate command to computer
public static final int exitCMD = -1;
public static final int VOL_UP = 1;
public static final int VOL_DOWN = 2;
private static final boolean D = true;
private static final String tagState = "BluetoothCommandService";
//universally unique identifier (UUID)
//The intent of UUIDs is to enable distributed systems to uniquely identify information without significant central coordination
//private static final UUID myUUID = UUID.fromString("04c6093b-0000-1000-8000-00805f9b34fb");
private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
//Name for the SDP (don;t know what is it) record when creating server socket
private static final String name = "BluetoothCommand";
public BluetoothCommandService(Context context, Handler handler) { // context == UI Activity Context && handler == send message back to the UI Activity
BTAdapter = BluetoothAdapter.getDefaultAdapter();
connectionState = stateNothing;
bluetoothHandler = handler;
}
private synchronized void setState(int state) { // state == current connection state; an integer
if (D) Log.d(tagState, "setState() " + connectionState + " -> " + state);
connectionState = state;
//Give the new state to the Handler so that the UI Activity can update
//bluetoothHandler.obtainMessage(what, arg1, arg2)
bluetoothHandler.obtainMessage(MainActivity.MESSAGE_STATE_CHANGE, state, -1).sendToTarget();
}
public synchronized int getState() { //return the current connection state
return connectionState;
}
public synchronized void start() {
if (D) Log.d(tagState, "start");
// Cancel any thread attempting to make a connection
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
// Start the thread to listen on a BluetoothServerSocket
if (mainAcceptThread == null)
{
mainAcceptThread = new AcceptThread();
mainAcceptThread.start();
}
setState(stateListen);
}
//device == the BluetoothDevice to connect
public synchronized void connect(BluetoothDevice device) {
if (D) Log.d(tagState, "connect to: " + device);
// Cancel any thread attempting to make a connection
if (connectionState == stateConnecting) {
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
// Cancel the accept thread because we only want to connect to one device
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
// Start the thread to connect with the given device
connectThread = new ConnectThread(device);
connectThread.start();
setState(stateConnecting);
}
public synchronized void connected(BluetoothSocket socket, BluetoothDevice device) {
if (D) Log.d(tagState, "connected");
// Cancel the thread that completed the connection
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
// Cancel any thread currently running a connection
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
// Start the thread to manage the connection and perform transmissions
connectedThread = new ConnectedThread(socket);
connectedThread.start();
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_DEVICE_NAME);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.DEVICENAME, device.getName());
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
setState(stateConnected);
}
public synchronized void stop() {
if (D) Log.d(tagState, "stop");
if (connectThread != null)
{
connectThread.cancel();
connectThread = null;
}
if (connectedThread != null)
{
connectedThread.cancel();
connectedThread = null;
}
if (mainAcceptThread != null)
{
mainAcceptThread.cancel();
mainAcceptThread = null;
}
setState(stateNothing);
}
public void write(byte[] out) {
ConnectedThread r;
synchronized (this) {
if (connectionState != stateConnected) return;
r = connectedThread;
}
r.write(out);
}
public void write(int out) {
// Create temporary object
ConnectedThread r;
// Synchronize a copy of the ConnectedThread
synchronized (this) {
if (connectionState != stateConnected) return;
r = connectedThread;
}
// Perform the write unsynchronized
r.write(out);
}
private void connectionFailed() {
setState(stateListen);
// Send a failure message back to the Activity
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Unable to connect device");
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
}
/**
* Indicate that the connection was lost and notify the UI Activity.
*/
private void connectionLost() {
setState(stateListen);
Message msg = bluetoothHandler.obtainMessage(MainActivity.MESSAGE_TOAST);
Bundle bundle = new Bundle();
bundle.putString(MainActivity.TOAST, "Device connection was lost");
msg.setData(bundle);
bluetoothHandler.sendMessage(msg);
}
private class ConnectThread extends Thread {
private final BluetoothSocket connectThread_socket;
private final BluetoothDevice connectThread_device;
public ConnectThread(BluetoothDevice device) {
connectThread_device = device;
BluetoothSocket tmp = null;
//Get a BluetoothSocket for a connection w/ the given BT device
//try {
//catch (IOException e) {
//Log.e(tag, msg, tr)
//Log.e(tagState, "create() failed", e);}
//Added 12/28/13
Method m;
try {
m = device.getClass().getMethod("createRfcommSocket", new Class[] {int.class});
tmp = (BluetoothSocket) m.invoke(device, 1);
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchMethodException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
connectThread_socket = tmp;
}
public void run() {
Log.i(tagState, "BEGIN ConnectThread");
setName("ConnectThread");
BTAdapter.cancelDiscovery();
// Make a connection to the BluetoothSocket
try {
connectThread_socket.connect();}
catch (IOException e) {
connectionFailed();
try {
connectThread_socket.close();
} catch (IOException e2) {
Log.e(tagState, "Unable to close() socket during connection failure", e2);
}
BluetoothCommandService.this.start();
return;
}
// Reset the ConnectThread because we're done
synchronized (BluetoothCommandService.this) {
connectThread = null;
}
// Start the connected thread
connected(connectThread_socket, connectThread_device); //ERROR: will still create "connected"
}
public void cancel() {
try {
connectThread_socket.close();
} catch (IOException e) {
Log.e(tagState, "close() of connect socket failed", e);
}
}
}
private class ConnectedThread extends Thread {
private final BluetoothSocket connectedThread_socket;
private final InputStream connectedThread_inStream;
private final OutputStream connectedThread_outStream;
public ConnectedThread(BluetoothSocket socket) {
Log.d(tagState, "create ConnectedThread");
connectedThread_socket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
Log.e(tagState, "temp sockets not created", e);
}
connectedThread_inStream = tmpIn;
connectedThread_outStream = tmpOut;
}
public void run() {
Log.i(tagState, "BEGIN ConnectedThread");
byte[] buffer = new byte[1024]; // WALA JUD KO KASABOT ANI MAN :D
while (true) {
try {
int bytes = connectedThread_inStream.read(buffer);
bluetoothHandler.obtainMessage(MainActivity.MESSAGE_READ, bytes, -1, buffer)
.sendToTarget();
} catch (IOException e) {
Log.e(tagState, "disconnected", e);
connectionLost(); //ERROR: will still create "private void CONNECTIONLOST"
break;
}
}
}
public void write(byte[] buffer) {
try {
connectedThread_outStream.write(buffer);
} catch (IOException e) {
Log.e(tagState, "Exception during write", e);
}
}
public void write(int out) {
try {
connectedThread_outStream.write(out);
} catch (IOException e) {
Log.e(tagState, "Exception during write", e);
}
}
public void cancel() {
try {
connectedThread_outStream.write(exitCMD);
connectedThread_socket.close();
} catch (IOException e) {
Log.e(tagState, "close() of connect socket failed", e);
}
}
}
private class AcceptThread extends Thread {
// The local server socket
private final BluetoothServerSocket acceptThread_ServerSocket;
public AcceptThread() {
BluetoothServerSocket tmp = null;
// Create a new listening server socket
try {
tmp = BTAdapter.listenUsingRfcommWithServiceRecord(name, myUUID);
} catch (IOException e) {
Log.e(tagState, "listen() failed", e);
}
acceptThread_ServerSocket = tmp;
}
public void run() {
if (D) Log.d(tagState, "BEGIN mainAcceptThread" + this);
setName("AcceptThread");
BluetoothSocket socket = null;
while (connectionState != stateConnected) {
try {
socket = acceptThread_ServerSocket.accept();
} catch (IOException e) {
Log.e(tagState, "accept() failed", e);
break;
}
if (socket != null) {
synchronized (BluetoothCommandService.this) {
switch (connectionState) {
case stateListen:
case stateConnecting:
connected(socket, socket.getRemoteDevice());
break;
case stateNothing:
case stateConnected:
try {
socket.close();
} catch (IOException e) {
Log.e(tagState, "Could not close unwanted socket", e);
}
break;
}
}
}
}
if (D) Log.i(tagState, "END mainAcceptThread");
}
public void cancel() {
if (D) Log.d(tagState, "cancel " + this);
try {
acceptThread_ServerSocket.close();
} catch (IOException e) {
Log.e(tagState, "close() of server failed", e);
}
}
}
}

Categories