Bluetooth in ActivityMain for different Fragments

0

I have an application that uses TabbedActivity with 3 Fragments where the intention is to show data received by bluetooth.

My idea is to put in the main class the reception of the data that I will keep in Lists and those Lists to pass them to the Fragments. But the application stops after making connection with the BT device, it does not reach the activity of the Tab.

I had a single activity application where I received the data and showed it:

public class UserInterfaz extends AppCompatActivity {

Button IdDesconectar;
TextView IdTemp, IdHum, IdDosisA, IdDosisB, IdDosisP;

Handler bluetoothIn;
final int handlerState = 0;
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder DataStringIN = new StringBuilder();
private ConnectedThread MyConexionBT;

private String dataInPrint = null;

private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

private static String address = null;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_user_interfaz);

    IdDesconectar=(Button)findViewById(R.id.IdDesconectar);
    IdDosisA=(TextView)findViewById(R.id.IdDosisA);
    IdDosisB=(TextView)findViewById(R.id.IdDosisB);
    IdDosisP=(TextView)findViewById(R.id.IdDosisP);
    IdHum=(TextView)findViewById(R.id.IdHum);
    IdTemp=(TextView)findViewById(R.id.IdTemp);

    bluetoothIn = new Handler() {
        public void handleMessage(android.os.Message msg) {

            if (msg.what == handlerState) {
                String readMessage = (String) msg.obj;
                DataStringIN.append(readMessage);

                int startOfLineIndex, endOfLineIndex, IndexHum, IndexTemp, IndexA, IndexB, IndexP;
                endOfLineIndex = DataStringIN.indexOf("#");

                if (endOfLineIndex > 0) {
                    startOfLineIndex = DataStringIN.indexOf("&");
                    IndexHum = DataStringIN.indexOf("H");
                    IndexTemp = DataStringIN.indexOf("T");
                    IndexA = DataStringIN.indexOf("A");
                    IndexB = DataStringIN.indexOf("B");
                    IndexP = DataStringIN.indexOf("P");

                    dataInPrint = DataStringIN.substring(startOfLineIndex+1, IndexHum);
                    IdHum.setText(dataInPrint + " %RH");//<-<- PARTE A MODIFICAR >->->

                    dataInPrint = DataStringIN.substring(IndexHum+1, IndexTemp);
                    IdTemp.setText(dataInPrint + " °C");//<-<- PARTE A MODIFICAR >->->

                    dataInPrint = DataStringIN.substring(IndexTemp+1, IndexA);
                    IdDosisA.setText(dataInPrint);//<-<- PARTE A MODIFICAR >->->

                    dataInPrint = DataStringIN.substring(IndexA+1, IndexB);
                    IdDosisB.setText(dataInPrint);//<-<- PARTE A MODIFICAR >->->

                    dataInPrint = DataStringIN.substring(IndexB+1, IndexP);
                    IdDosisP.setText(dataInPrint);//<-<- PARTE A MODIFICAR >->->

                    DataStringIN.delete(0, DataStringIN.length());
                }
            }
        }
    };

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    VerificarEstadoBT();

    IdDesconectar.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (btSocket!=null)
            {
                try {btSocket.close();}
                catch (IOException e)
                { Toast.makeText(getBaseContext(), "Error", Toast.LENGTH_SHORT).show();;}
            }
            finish();
        }
    });
}


private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
{
    //crea un conexion de salida segura para el dispositivo
    //usando el servicio UUID
    return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}

@Override
public void onResume()
{
    super.onResume();
    //Consigue la direccion MAC desde DeviceListActivity via intent
    Intent intent = getIntent();
    //Consigue la direccion MAC desde DeviceListActivity via EXTRA
    address = intent.getStringExtra(DispositivosBT.EXTRA_DEVICE_ADDRESS);//<-<- PARTE A MODIFICAR >->->
    //Setea la direccion MAC
    BluetoothDevice device = btAdapter.getRemoteDevice(address);

    try
    {
        btSocket = createBluetoothSocket(device);
    } catch (IOException e) {
        Toast.makeText(getBaseContext(), "La creacción del Socket fallo", Toast.LENGTH_LONG).show();
    }
    // Establece la conexión con el socket Bluetooth.
    try
    {
        btSocket.connect();
    } catch (IOException e) {
        try {
            btSocket.close();
        } catch (IOException e2) {}
    }
    MyConexionBT = new ConnectedThread(btSocket);
    MyConexionBT.start();
}

//Comprueba que el dispositivo Bluetooth Bluetooth está disponible y solicita que se active si está desactivado
private void VerificarEstadoBT() {

    if(btAdapter==null) {
        Toast.makeText(getBaseContext(), "El dispositivo no soporta bluetooth", Toast.LENGTH_LONG).show();
    } else {
        if (btAdapter.isEnabled()) {
        } else {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }
    }
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    return super.onTouchEvent(event);
}

//Crea la clase que permite crear el evento de conexion
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;

        // Se mantiene en modo escucha para determinar el ingreso de datos
        while (true) {
            try {
                bytes = mmInStream.read(buffer);
                String readMessage = new String(buffer, 0, bytes);
                // Envia los datos obtenidos hacia el evento via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
}
}

So just pass the methods to the class of the Tabs and save the data in Lists. But it stops ...

Where would it be best to place these methods? Thanks!

    
asked by Ilse Lopez 05.12.2018 в 20:32
source

0 answers