Send string of data received by bluetooth to another activity

0

Hello, I have the following code, and I am looking to send the String with the data I receive by bluetooth "recDataString" to a new Activity, and I do not know how to do it. Thanks.

public class MainActivity extends Activity {

    ProgressBar Progress;
    TextView textView,TextView_Value0,TextView_Value1,textViewProgressBar;
    SeekBar seekBar;
    TextView txtString, txtStringLength;
    Handler bluetoothIn;

    final int handlerState = 0;                      //Indentificador de handler "Proceso segundo plano"
    private BluetoothAdapter btAdapter = null;       // Inicio del Adaptador
    private BluetoothSocket btSocket = null;        // Inicio del Socket de Comunicaciones
    private StringBuilder recDataString = new StringBuilder();      // Inicio de String para datos Recibidos

    private ConnectedThread mConnectedThread;

    // Servicio SPP UUID service  UNIVERSAL **
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    // String de la dirección Mac
    private static String address = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {  // CUANDO SE ABRE LA APP
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        //Vincular objetos a sus respectivas views
        initializeVariables();
        Recive();
        SeekBarFunct();
        btAdapter = BluetoothAdapter.getDefaultAdapter();       // asignar El bluetooth predeterminado del movil
        BtEstado();



    }


    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {

        return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
        //Crea una conexion segura mediante el UUID
     }

    @Override
    public void onResume() {
        super.onResume();

        //Recibe la  MAC  en DeviceListActivity via intent
        Intent intent = getIntent();

        //Coge la direccion mac de DeviceListActivty y la envia al Main via EXTRA
        address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);

        //Crea dispositivos y asigna la mac a cada uno de ellos
        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 conexion del Socket de Bluetooth
        try
        {
            btSocket.connect();
        } catch (IOException e) {
            try
            {
                btSocket.close();
            } catch (IOException e2)
            {
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.start();

    // Manda una x cada vez que se realiza una accion ya que con esto Comprueba que la conexion siga estable
    // En caso de que no esté conectado o se haya caido la conexion y esta escritura no se llegue a realizar
    // cierra la aplicacion mediante el metodo finish() en la FUNCION ESCRITURA BT
    mConnectedThread.write("x");
}

@Override
public void onPause()       // Cuando se sale del Activity
{
    super.onPause();
    try
    {
        //No dejar Sockets de conexion abiertos al salir de la activity por que crashea...
        btSocket.close();
    } catch (IOException e2) {

    }
}

private void SeekBarFunct(){
    seekBar.setMax(9);

    textView.setText("Progreso: " + seekBar.getProgress() + "/" + seekBar.getMax());

    seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
        int progress = 0;

        @Override
        public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
            progress = progresValue;
            mConnectedThread.write(String.valueOf(progress));    // Envia el valor de progresValue
            textView.setText("Progreso: " + progress + "/" + seekBar.getMax());
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
        }
    });
}
private void initializeVariables() {
    seekBar = (SeekBar) findViewById(R.id.seekBar1);
    textView = (TextView) findViewById(R.id.textView1);
    TextView_Value0 = (TextView) findViewById(R.id.TextView_Values0);
    TextView_Value1 = (TextView) findViewById(R.id.TextView_Values1);
    Progress = (ProgressBar) findViewById(R.id.progressBar);
    textViewProgressBar = (TextView) findViewById(R.id.textViewIDProgressBar);


    txtString = (TextView) findViewById(R.id.txtString);
    txtStringLength = (TextView) findViewById(R.id.testView1);
} // INICIALIZA VARIABLES DE OBJETO
private void Recive(){
bluetoothIn = new Handler() {
    public void handleMessage(android.os.Message msg) {
        if (msg.what == handlerState) {
            String readMessage = (String) msg.obj;                                  // msg.arg1 = bytes
            recDataString.append(readMessage);
            int endOfLineIndex = recDataString.indexOf("~");                    // Final de linea ~
            if (endOfLineIndex > 0) {
                String dataInPrint = recDataString.substring(0, endOfLineIndex);
                txtString.setText("Datos recibidos = " + dataInPrint);
                int dataLength = dataInPrint.length();                          // Tamaño de String
                txtStringLength.setText("Tamaño del String = " + String.valueOf(dataLength));
                if (recDataString.charAt(0) == '#') {
                    Value0 = recDataString.substring(1, 5);
                    Value1 = recDataString.substring(6, 10);

                    TextView_Value0.setText("Valor0: " + Value0F + " V");
                    TextView_Value1.setText("Valor1: " + Value1 + "V");
                    Value0F = Float.parseFloat(Value0);
                    Value0F = Value0F * 100;
                    Value0I =(int)(Math.round(Value0F));
                    Value0F = Value0F / 100;

                    int VariableProgressBar= Value0I;
                    Progress.setMax(500);
                    Progress.setProgress(VariableProgressBar);
                    textViewProgressBar.setText("Progreso: " + Progress.getProgress() + "/" + Progress.getMax());
                }

                recDataString.delete(0, recDataString.length());                    //Limpieza de anteriores Datos recibidos
                // strIncom =" ";
                dataInPrint = " ";
            }
        }
    }
};

}     // Check if the BT is on and if you do not ask for permission     private void BtEstado () {

    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);
        }
    }
}



//Crea la nueva clase para la conexion del Socket de comunicacion

private class ConnectedThread extends Thread {
    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    //Crea la conexion del thread en segundo Plano
    public ConnectedThread(BluetoothSocket socket) {
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        try {
            //Crea las "Streams" del Socket de conexion
            tmpIn = socket.getInputStream();
            tmpOut = socket.getOutputStream();
        } catch (IOException e) { }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;
    }


    public void run() {
        byte[] buffer = new byte[256];
        int bytes;

        // Esta leyendo por si hay mensajes que recibir
        while (true) {
            try {
                bytes = mmInStream.read(buffer);            //Lee bytes del buffer de entrada
                String readMessage = new String(buffer, 0, bytes);
                // Envia los bytes obtenidos a la interfaz Activity via handler
                bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
            } catch (IOException e) {
                break;
            }
        }
    }
    //FUNCION ESCRITURA BT
    public void write(String input) {
        byte[] msgBuffer = input.getBytes();           //Convertir String en enteros
        try {
            mmOutStream.write(msgBuffer);                //escribe bytes en el socket BT via outstream
        } catch (IOException e) {
            //Si no puede Realizar la comunicacion Cierra App y muestra Mensaje en Pantalla
            Toast.makeText(getBaseContext(), "La Conexión fallo", Toast.LENGTH_LONG).show();
            finish();

        }
    }
}

}

    
asked by Danielei burru 10.05.2017 в 11:09
source

1 answer

0

I have not read all the code, but I can assure you that this answer will help you in your question and in almost everything.

Activities (Activity) are communicated through Intent , if you need to exchange information with each other, they communicate through the extras that are parameters used by the Intent .

To explain it in an easy way, we will use ActivityOne and ActivityTwo , the first one is the main one.

ActivityOne wants to open ActivityTwo , but wants to send some data.

  

Intent constructor new Intent(Context, Class) to open ActivityTwo

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("mi_extra", "ejemplo");
startActivity(intent);

ActivityTwo have to receive the sent text:

String miExtra = getIntent().getStringExtra("mi_extra");
Log.i("MiExtra", miExtra);

If you want to return a result, you can use this:

Intent intent = new Intent(ActivityOne.this, ActivityTwo.class);
intent.putExtra("mi_extra", "ejemplo");
startActivityForResult(intent, 0);

And in ActivityTwo use this (to return a result:

Intent intent = new Intent();
intent.putExtra("tu_extra", "ejemplo");
setResult(RESULT_OK, intent);

Intercept the result in ActivityOne

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 0) {
        if (resultCode == RESULT_OK) {
            String tuExtra = data.getStringExtra("tu_extra");
            Log.i("TuExtra", tuExtra);
        }
    }
}
    
answered by 12.06.2017 в 19:08