Bluetooth clossing connectors when using voice recognition

I applied this tutorial on my APP, but I made a lot of changes .... I created TabLayoutso I did (I don’t think it’s a good idea, well, it’s not because it doesn’t work :)) for every fragment that I copied, pasted the tutorial code (I created sockets to connect to mine Bluetooth, I create a connection to the device ...), and when I tested it with only one Activity, it worked fine ... but when I added it TabLayout, it started working. I think that I could do all the code Bluetoothon Activity, and then work with objects of this Activity(from FragmentI mean ...) the problem is that on onPause()I have this:

@Override
public void onPause() {
    super.onPause();
    Toast.makeText(getActivity(), "onPause", Toast.LENGTH_SHORT).show();
        try {
            btSocket.close();
        } catch (IOException e2) {

        }
}

And every time I use this:

private void startVoiceRecognitionActivity(){
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, getString(R.string.VoiceControllerText));
    startActivityForResult(intent, REQUEST_CODE);
}

onPause(), , Bluetooth. btSocket.close();, , socket is closed, Tab ( 2), socket.close() Tab?....

, /, Bluetooth - , onPause() Tab .

, , , Bluetooth ( Fragment, ....) ... UUID ...

, , , .

.

Activity, MainActivity the MAC address :

Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
i.putExtra(EXTRA_DEVICE_ADDRESS, address);
i.putExtra("name", name);
startActivity(i);

DeviceListActivity...

, , - MainActivity, Bluetooth, Fragments ...

Fragment, ( ):

Atributes

//Sending info
Handler bluetoothIn;
private ConnectedThread mConnectedThread;
final int handlerState = 0;                        //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
private static String address="";

in onCreate() :

btAdapter = BluetoothAdapter.getDefaultAdapter();// get Bluetooth adapter
    if (btAdapter == null) {
        Toast.makeText(getActivity(), getString(R.string.BtNotSupported), Toast.LENGTH_SHORT).show();
    }
checkBTState();

socket

private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}

onResume()

@Override
public void onResume() {
    super.onResume();
    //Get MAC del intent
    Intent intent = getActivity().getIntent();
    address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
    //Creates a device with the MAC from DeviceListActivity
    if(btAdapter!=null) {
        BluetoothDevice device = btAdapter.getRemoteDevice(address);

        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            ShowSnack(getString(R.string.SocketCreationFailed), Color.RED);
        }
        //Trying to connect
        try {
            btSocket.connect();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {
            }
        }
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();
    }  
    else{
        ShowSnack(getString(R.string.toast_bt_unavailable), Color.RED);
    }
}

onPause()

  @Override
public void onPause() {
    super.onPause();
    try {
        //Close socket if leaves the Activity
        btSocket.close();
    } catch (IOException e2) {

    }
}

, , , Bluetooth .

private void checkBTState() {

    if (btAdapter == null) {
        ShowSnack(getString(R.string.toast_bt_unavailable), Color.RED);
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

ConnectedThread Bluetooth.

private class ConnectedThread extends Thread {
 private final InputStream mmInStream;
 private final OutputStream mmOutStream;
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;
        try {
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
        }
        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }
    public void run() {
        byte[] buffer = new byte[256];
        int bytes;
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //read bytes from input buffer
                String readMessage = new String(buffer, 0, bytes);
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }

    //Send stuff to Bluetooth
    public void write(char input) {
        try {
            mmOutStream.write(input);
        } catch (IOException e) {

        }
    }
}

, , , Fragment, , ... , Voice recognision... - Bluetooth, .. , , , , .

+1
1

, , , , Bluetooth . , , Activity ( onPause() onResume()) . , , , Bluetooth. Activity, , Bluetooth.

, , Service Bluetooth.

public class BluetoothService extends Service {
    public static final String BLUETOOTH_SERIAL_UUID = "00001101-0000-1000-8000-00805F9B34FB";
    private BluetoothSocket mSocket;
    private String mAddress = "bluetooth_mac_address_here";

    public void onCreate() {
        //Set up Bluetooth socket.
        BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
        if(btAdapter.isEnabled()) {
            BluetoothDevice btDevice = btAdapter.getRemoteDevice(mAddress);
            mSocket = btDevice.createRfcommSocketToServiceRecord(BLUETOOTH_SERIAL_UUID);
            btAdapter.cancelDiscovery();
            mSocket.connect();
        }
    }
}

mSocket . bluetooth mSocket.getInputStream() mSocket.getOutputStream() / . , , , Activity . .

BluetoothService onStartCommand():

public class BluetoothService extends Service {
...
public static final String ACTION_SEND_DATA = "send_data";
public static final String ACTION_RECEIVED_DATA = "received_data";
public static final String EXTRA_BLUETOOTH_DATA = "bluetooth_data";

public int onStartCommand(Intent intent, int flags, int startId) {
    //Register a BroadcastReceiver to handle "send" requests.
    LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Parse your data to send from the intent.
            if(intent.getAction().equals(ACTION_SEND_DATA)) {
                byte[] data = intent.getByteArrayExtra(EXTRA_BLUETOOTH_DATA);
                //Send the data over the Bluetooth Socket.
                try {
                    mSocket.getOutputStream().write(data);
                } catch(IOException ioe) {
                    //This might happen if you try to write to a closed connection.
                    ioe.printStackTrace();
                }
            }
        }
        return Service.START_STICKY;
    }
}

Activity , . . , LocalBroadcastReceiver . , BroadcastReceiver, , , . , , , (, ), . , :

public class MyActivity extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        ...
        String myString = "This is some data I want to send!";
        //Create an intent with action saying to send data
        //with the byte[] of data you want to send as an extra.
        Intent sendIntent = new Intent(BluetoothService.ACTION_SEND_DATA);
        sendIntent.putExtra(BluetoothService.EXTRA_BLUETOOTH_DATA, myString.getBytes());
        //Sends the intent to any BroadcastReceivers that have registered receivers for its action.
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }
}

, , , . , , . TransferManager , InputStream BluetoothSocket.

=============================================== ===========================

, , Bluetooth. , , , . , , Activities, . , , . , , , , , Bluetooth ( ), , Service. , Thread BluetoothService:

public class BluetoothService extends Service {
    ...
    public void onCreate() {...}
    public int onStartCommand(...) {...}

    public static class ReceiveThread extends Thread {
        private boolean isRunning;
        private InputStream mBluetoothInputStream;

        public ReceiveThread(InputStream bluetoothInputStream) {
            mBluetoothInputStream = bluetoothInputStream;
            isRunning = true;
        }

        @Override
        public void run() {
            BufferedReader bufferedReader = new BufferedReader(
                    new InputStreamReader(mBluetoothInputStream));
            String line;
            while(isRunning) {
                try {
                    //This is the line that blocks until a newline is read in.
                    line = bufferedReader.readLine();
                } catch(IOException ioe) {
                    //This happens if the InputStream is closed.
                    ioe.printStackTrace();
                    //Stop the thread from looping.
                    isRunning = false;
                }

                //Make sure our line in isn't null or blank.
                if(line == null || line.equals("") {
                    continue; //Start again at top of while loop.
                }

                //Notify your Activity about the new data.
                Intent receivedIntent = new Intent(BluetoothService.this, MyActivity.class);
                receivedIntent.setAction(ACTION_RECEIVED_DATA);
                receivedIntent.putExtra(EXTRA_BLUETOOTH_DATA);
                LocalBroadcastManager.getInstance(BluetoothService.this).sendBroadcast(receivedIntent);

                try {
                    //This is an arbitrary sleep time just to prevent
                    //this from looping without any restriction.
                    Thread.sleep(20);
                } catch(InterruptedException e) {
                    //This happens if the Thread is interrupted for any reason.
                    e.printStackTrace();
                    isRunning = false;
                }
            }
        }
    }
}

, ReceiveThread, onStartCommand() :

ReceiveThread receiver = new ReceiveThread(mSocket.getInputStream());
receiver.start();

- . BroadcastReceiver, , . Activity onCreate():

public void onCreate() {
    ...
    LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            //Get your data out of the intent.
            byte[] data = intent.getByteArrayExtra(BluetoothService.EXTRA_BLUETOOTH_DATA);
        }
    }, new IntentFilter(BluetoothService.ACTION_RECEIVED_DATA));
}

onReceive() , BluetoothService ReceiveThread Bluetooth. (, / ). , BufferedReader ReceiveThread Reader.

EDIT:

, write, , , . , Activity, . , , , Activity, , . , public class MyActivity extends Activity. , Android "" , onReceive() onStartCommand() , , OutputStream .

, return Service.START_STICKY onStartCommand() . , write, , LocalBroadcastManager.

+2

Source: https://habr.com/ru/post/1627399/


All Articles