Here is the code I use and it works great for me.
On the Android side, I only include the bluetooth file, which should be easy to fit into your application. The main advantage is that after your application launches it by calling btConnect (), everything else will be automatic. It finds and connects to your HC-06 without further "human intervention." And if you turn off “HC-06,” Android will continue to watch “HC-06,” to return to online, and reconnect to it.
The sketch of the Arduino sends a signal once per second. If 10 seconds are missed, Android assumes that the connection is lost and will switch to connection mode.
JAVA ANDROID BLUETOOTH FILE:
package com.exercise.androidanimbuttons; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.IntentFilter; import android.widget.Toast; import android.bluetooth.BluetoothSocket; import android.app.ProgressDialog; import android.os.AsyncTask; import java.io.IOException; import java.io.InputStream; import java.util.UUID; import java.util.Set; import android.os.Handler; public class BlueTooth extends vars { private Set<BluetoothDevice> pairedDevices; String address = null; private ProgressDialog progress = null; BluetoothAdapter myBluetooth = null; BluetoothSocket btSocket = null; InputStream mmInStream = null; private Handler myHandler = new Handler(); byte[] buffer = new byte[25]; int readBytes; files filesI = new files(); Handler btH = new Handler(); static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); private SingBroadcastReceiver mReceiver; Runnable btSearch; void stopDiscovery() { if (myBluetooth.isDiscovering()){ myBluetooth.cancelDiscovery(); } } void findCurrentBT() { if (!myBluetooth.isEnabled()){ Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, 0xDEADBEEF); } if (myBluetooth.isDiscovering()){ myBluetooth.cancelDiscovery(); } closeProgress(); progress = ProgressDialog.show(BlueTooth.this, "Searching for headband...", "MAKE SURE THE HEADBAND IS TURNED ON."); progress.setCanceledOnTouchOutside(true); myBluetooth.startDiscovery(); mReceiver = new SingBroadcastReceiver(); IntentFilter ifilter = new IntentFilter(BluetoothDevice.ACTION_FOUND); this.registerReceiver(mReceiver, ifilter); checkSearch(); } private class SingBroadcastReceiver extends BroadcastReceiver { public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (BluetoothDevice.ACTION_FOUND.equals(action)) { BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE); String derp = device.getName() + " - " + device.getAddress(); ta(derp); Toast.makeText(context, derp, Toast.LENGTH_LONG); if ((device.getName() != null) && (device.getName().indexOf("HC-06") == 0) && (device.getName().length() == 5)) { myBluetooth.cancelDiscovery(); address = device.getAddress(); new ConnectBT().execute(); } } } } private Runnable readBT = new Runnable() { public void run() { int i; int twoByte = 0; short high = 0, low = 0; try { if (mmInStream.available() > 3) { cnt = 0; readBytes = mmInStream.read(buffer); String S = ""; for (i = 0; i < 2; i++) S += String.format("%03d", buffer[i] & 0xFF)+", "; high = (short)(buffer[3] & 0xFF); low = (short)(buffer[2] & 0xFF); twoByte = ((high << 8) | low); S += String.format("%03d", twoByte) + "\r\n"; filesI.writeALine("nights","data12.txt",S); ta(S); } } catch (IOException e) { ta("err:2 " + e.toString()); } if (btSocket.isConnected()) myHandler.postDelayed(this, 100); } }; public void btConnect() { Disconnect(); findCurrentBT(); } public void btOn() { turnOnLed(); } public void btOff() { turnOffLed(); } public void btDisconnect() { Disconnect(); } private void Disconnect() { if (btSocket!=null) { try { btSocket.close(); } catch (IOException e) { msg("Bluetooth Disconnect Error");} } } private void turnOffLed() { if (btSocket!=null) { try { btSocket.getOutputStream().write("TF".toString().getBytes()); } catch (IOException e) { msg("Error"); } } } private void turnOnLed() { int len; byte[] buffer = new byte[400]; if (btSocket!=null) { try { btSocket.getOutputStream().write("TO".toString().getBytes()); len = btSocket.getInputStream().available(); btSocket.getInputStream().read(buffer,0,len); } catch (IOException e) { msg("Error"); } } } private void msg(String s) { Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show(); } void closeProgress() { if (progress != null) progress.dismiss(); } private class ConnectBT extends AsyncTask<Void, Void, Void> { @Override protected void onPreExecute() { closeProgress(); progress = ProgressDialog.show(BlueTooth.this, "Connecting to headband...", ""); progress.setCanceledOnTouchOutside(true); } @Override protected Void doInBackground(Void... devices) { try { if (btSocket == null || (!btSocket.isConnected())) { BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address); btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID); BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); btSocket.connect(); } } catch (IOException e) { } return null; } @Override protected void onPostExecute(Void result) { super.onPostExecute(result); if (!btSocket.isConnected()) { msg("Connection Failed. Is the headband turned on?"); } else { msg("Connected."); try { mmInStream = btSocket.getInputStream(); myHandler.postDelayed(readBT, 1000); } catch (IOException e) { ta("err:1 " + e.toString()); } } closeProgress(); } } int cnt = 0; void checkSearch() { if (btSearch != null) return; btSearch = new Runnable(){@Override public void run(){ if ((btSocket != null) && (btSocket.isConnected())) { cnt--; if (cnt < -10) { cnt = 0; btConnect(); } } else if (myBluetooth.isDiscovering()) { cnt++; } btH.postDelayed(this, 1000); fa(cnt); }}; btH.postDelayed(btSearch,1000); } }
COMPLIANCE WITH ARDUINO ESCHET:
byte mini [4]; int battery; unsigned long mill = millis(); byte moveCnt = 1; int minuteCnt = 0; int lastMove = 0; int moveA, moveB, moveC, LMoveA, LMoveB, LMoveC, totMove, eyes, LEyes, totEyes; int moveUpA = 0; int moveDnA = 1000; int moveUpB = 0; int moveDnB = 1000; int moveUpC = 0; int moveDnC = 1000;