Android - RECIBIR VALOR

 
Vista:

RECIBIR VALOR

Publicado por Marcela Hernandez (1 intervención) el 11/05/2021 01:03:44
Buen día estoy haciendo una aplicación en android studio y java para poder recibir el valor desde un sensor (temperatura) a textView pero no aparece el valor, quisiera saber en donde me estoy equivocando honestamente soy nueva en este lenguaje.

Este es mi código donde se verá el valor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
public class Dispositivos extends AppCompatActivity {
 
    BluetoothAdapter mBluetoothAdapter;
    BluetoothSocket mSocket;
    BluetoothDevice mDevice;
    OutputStream mOutputStream;
    private static final int REGISTER_ANALISIS = 2;
    private TextView nivelGlucosaView;
    private RadioGroup nota1_rdgroup, nota2_rdgroup;
    private String glucosa;
    ToggleButton b = null;
 
 
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispositivos);
 
        nivelGlucosaView = findViewById(R.id.nivelGlucosaView);
        nota1_rdgroup = findViewById(R.id.nota1_rdgroup);
        nota2_rdgroup = findViewById(R.id.nota2_rdgroup);
 
 
 
 
 
        //Conexión/desconexión al Bluetooth
            b = (ToggleButton) findViewById(R.id.toggleButton);
            b.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mSocket != null && mSocket.isConnected()) {
                        ((Button) v).setText("Conectar BT");
                        try {
                            endBT();
                        } catch (IOException e) {
                            showMessage("Error al conectar", Toast.LENGTH_SHORT);
                        }
                    } else {
                        ((Button) v).setText("Desconectar BT");
                        try {
                            startBT();
                        } catch (IOException e) {
                            showMessage("Error al desconectar", Toast.LENGTH_SHORT);
                        }
                    }
                }
            });
 
 
 
                                Intent intent = getIntent();
                                glucosa=intent.getStringExtra("MedidaSangre");
                                    nivelGlucosaView.setText(glucosa);
 
        }
 
        // mas
 
 
    //Busca el dispositivo Bluetooth e inicia la conexión
    @TargetApi(Build.VERSION_CODES.ECLAIR)
    void startBT() throws IOException{
        //Buscar el dispositivo
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if(mBluetoothAdapter==null){
            showMessage ("No existe adaptador bluetooth disponible", Toast.LENGTH_LONG);
            return;
        }
        if (!mBluetoothAdapter.isEnabled()){
            Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBluetooth, 0);
        }
        Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
 
        boolean deviceFound = false;
        for (BluetoothDevice device : pairedDevices){
            if (device.getName().equals("HC-05")){
                showMessage ("Bluetooth disponible: "+ device.getName(), Toast.LENGTH_LONG);
                mDevice = device;
                deviceFound = true;
                break;
            }
        }
        //Si se encuentra, abrir la conexión
        //Si no, mostrar mensaje
        if (deviceFound){
            openBT();
        }else{
            showMessage("No se ha encontrado el dispositivo indicado", Toast.LENGTH_LONG);
        }
 
    }
 
 
 
    //Inicia conexión Bluetooth
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    void openBT() throws IOException{
        //ID estándar
        UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
        mSocket = mDevice.createRfcommSocketToServiceRecord(uuid);
        mSocket.connect();
        mOutputStream = mSocket.getOutputStream();
 
        showMessage ("Bluetooth conectado", Toast.LENGTH_SHORT);
    }
    //Finaliza la conexión Bluetooth
    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    void endBT() throws IOException{
        mOutputStream.close();
        mSocket.close();
 
    }
    //Muestra mensajes en pantalla
    private void showMessage(String msg, int time){
        Toast.makeText(Dispositivos.this, "CONEXION/DESCONECTANDO", Toast.LENGTH_SHORT).show();
    }
    //Envío del estado deseado
    private void sendBT(int i, boolean isOn){
        try{
            String msg = Integer.toString(i)+ (isOn ? "H" : "L");
            msg += "\n";
            mOutputStream.write(msg.getBytes());
            showMessage("Datos enviados", Toast.LENGTH_SHORT);
        }catch (Exception e){
            showMessage("Error en el envío", Toast.LENGTH_SHORT);
        }
    }
    public void onRegistrar(View view) {
        Date currentTime = Calendar.getInstance().getTime();
        int id_nota1=nota1_rdgroup.getCheckedRadioButtonId();
        int id_nota2=nota2_rdgroup.getCheckedRadioButtonId();
        RadioButton nota1_esc_rdbutton = new
                RadioButton(Dispositivos.this);
        RadioButton nota2_esc_rdbutton = new
                RadioButton(Dispositivos.this);
        if(id_nota1!=-1) nota1_esc_rdbutton=findViewById(id_nota1);
        else nota1_esc_rdbutton.setText("");
        if(id_nota2!=-1) nota2_esc_rdbutton=findViewById(id_nota2);
        else nota2_esc_rdbutton.setText("");
 
        Analisis analisis = new Analisis(new
                Date((currentTime.getYear()+1900), currentTime.getMonth(),
                currentTime.getDate(),
                currentTime.getHours(), currentTime.getMinutes()), Integer.valueOf(glucosa),
                nota1_esc_rdbutton.getText().toString(),
                nota2_esc_rdbutton.getText().toString());
        Intent intent = new Intent(Dispositivos.this,CalendarActivity.class);
        intent.putExtra("NewAnalisis", true);
        intent.putExtra("Analisis", analisis);
        startActivityForResult(intent, REGISTER_ANALISIS);
    }
 
}

y este es donde esta el hilo (fue lo que vi en videos )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
package ConexionBT;
 
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
 
import androidx.appcompat.app.AppCompatActivity;
 
import com.example.calcimetro.RegistrarAnalisis;
 
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
 
public class BluetoothConnectionService extends AppCompatActivity{
 
    String glucosa="";
    private static final String TAG = "BluetoothConnectionServ";
    private boolean closeconnection=false;
    private static final String appName = "MYAPP";
    private static final UUID MY_UUID_INSECURE =
            UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
    private UUID deviceUUID;
    private final BluetoothAdapter mBluetoothAdapter;
    Context mContext;
    Context cContext; //context para hacer startActivity una vez recibido un datohb.
    private AcceptThread mInsecureAcceptThread;
    private ConnectThread mConnectThread;
    private ConnectedThread mConnectedThread;
    private BluetoothDevice mmDevice;
    ProgressDialog mProgressDialog;
    public BluetoothConnectionService(Context context, Context
            ccontext) {
        mContext = context;
        cContext=ccontext;
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        start();
        glucosa="";
    }
 
    public BluetoothConnectionService() {
 
        mBluetoothAdapter = null;
    }
 
    public void setCloseconnection(boolean closeconnection) {
        this.closeconnection = closeconnection;
        Log.e(TAG, "close connection set to true");
    }
 
    public void close() {
    }
 
    /*Accept Thread actua como servidor
 crea un ServerSocket y en caso que se conecto otro dispositivo
como cliente, recibe un socket diferente al server socket */
    private class AcceptThread extends Thread {
        private final BluetoothServerSocket mmServerSocket; //Se crea serverSocket
        public AcceptThread(){
            BluetoothServerSocket tmp = null;
            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; //El server socket se ha creado correctamente a partir del UUID
        }
        public void run(){
            Log.d(TAG, "run: AcceptThread Running.");
            BluetoothSocket socket = null;
            try{
                Log.d(TAG, "run: AcceptThread RFCOM server socket start.....");
                socket = mmServerSocket.accept(); //Intenta aceptarcomunicacion de parte del cliente. Si se acepta, se recibe un socket apartir del server socket
                Log.d(TAG, "run: AcceptThread RFCOM server socket accepted connection.");
            }catch (IOException e){
                Log.e(TAG, "run AcceptThread: IOException: " +
                        e.getMessage() );
            }
            if(socket != null){
                connected(socket,mmDevice); //Se dirige aconnecedThread para la transferencia de datos
            }
            Log.i(TAG, "run mAcceptThread ENDS");
        }
        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() );
            }
        }
    }
    /*Este thread actua como conexion como Cliente
     * Se crea un socket y si la conexion es aceptada*/
    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, "run: ConnectThread: Trying to create InsecureRfcommSocket using UUID: "
                        +MY_UUID_INSECURE );
                tmp =
                        mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
            } catch (IOException e) {
                Log.e(TAG, "run: 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: ConnectThread 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: ConnectThread Closing Client Socket.");
                mmSocket.close();
            } catch (IOException e) {
                Log.e(TAG, "cancel: ConnectThread close() of mmSocket failed. " + e.getMessage());
            }
        }
    }
    //Se eliminan los posibles threads existentes para empezar de 0 lacomunicacion
    public synchronized void start() {
        Log.d(TAG, "start method begins");
        // Cancel any thread attempting to make a connection
        if (mConnectThread != null) {
            Log.d(TAG, "start method removes ConnectThread");
            mConnectThread.cancel();
            mConnectThread = null;
        }
        if (mConnectedThread != null) {
            Log.d(TAG, "start method removes ConnectedThread");
            mConnectedThread.cancel();
            mConnectedThread = null;
        }
        if (mInsecureAcceptThread == null) {
            mInsecureAcceptThread = new AcceptThread();
            mInsecureAcceptThread.start();
        }
    }
    public void startClient(BluetoothDevice device,UUID uuid){
        Log.d(TAG, "startClient: Started.");
        mConnectThread = new ConnectThread(device, uuid);
        mConnectThread.start();
    }
    //ConnectThread es el thread final que permite el traspaso de datos.
    private class ConnectedThread extends Thread {
        private BluetoothSocket mmSocket;
        private InputStream mmInStream;
        public ConnectedThread(BluetoothSocket socket) {
            Log.d(TAG, "ConnectedThread: Starting.");
            glucosa="";
            mmSocket = socket; //Se recibe el socket creado previamente por el thread ConnectThread o AcceptThread
            InputStream tmpIn = null;
            try{
                mProgressDialog.dismiss();
            }catch (NullPointerException e){
                e.printStackTrace();
            }
            //Se recibe un inputstream a partir del socket recibido que conecta los dos dispositivos
            try {
                tmpIn = mmSocket.getInputStream();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mmInStream = tmpIn;
        }
        //Este metodo es el responsable de leer el dato desde elglucometro
        public void run(){
            byte[] buffer = new byte[1024]; // buffer para el stream
            int bytes;
            //Se espera a que exista una interrupción para recuperar los datos
            while (true) {
                if(closeconnection){ //booleano que sirve para parar la comunicacion bluetooth
                    cancel();
                }
                //Lectura de input stream
                try {
                    bytes = mmInStream.read(buffer);
                    String incomingMessage = new String(buffer, 0,
                            bytes);
                    Log.d(TAG, "InputStream: " + incomingMessage);
                    glucosa=glucosa+incomingMessage;
                    Log.d(TAG, "Glucosa: " + glucosa);
                    //La llegada de datos es asincrona. Si el dato recibido es mayor a 50 se considera que el dato ha llegado completo.
                    if(Integer.valueOf(glucosa)>5){
                        try {
                            Intent intent = new Intent(cContext,
                                    RegistrarAnalisis.class);
                            intent.putExtra("MedidaSangre", glucosa);
                            cContext.startActivity(intent);
                            glucosa="";
                        } catch (Exception e) {
                            Log.e(TAG, "ConnectedThread_ Error en startActivity Registrar activity. Error: " + e);
                        }
                    }
                } catch (IOException e) {
                    Log.e(TAG, "ConnectedThread: Error reading Input Stream. " + e.getMessage());
                    break;
                }
            }
        }
        //Se cancela la comunicación
        public void cancel() {
            Log.d(TAG, "ConnectedThread cancel method: shutdown connection");
            if(mmInStream!=null){
                try {
                    mmInStream.close();
                    Log.d(TAG, "ConnectedThread cancel method: input stream closed");
                } catch (Exception e) {
                    Log.e(TAG, "ConnectedThread cancel method: Error al cerrar input stream. Error: " +e.getMessage());
                }
                mmInStream=null;
                Log.d(TAG, "ConnectedThread cancel method: input stream is now null");
            }
            if(mmSocket!=null){
                try {
                    mmSocket.close();
                    Log.d(TAG, "ConnectedThread cancel method: socket closed");
                } catch (IOException e) {
                    Log.e(TAG, "ConnectedThread cancel method: Error closing socket. Error: " +e.getMessage());
                }
                mmSocket=null;
            }
        }
    }
    private void connected(BluetoothSocket mmSocket, BluetoothDevice
            mmDevice) {
        Log.d(TAG, "Connected method: Starting.");
        // Start the thread to manage the connection and perform transmissions
        mConnectedThread = new ConnectedThread(mmSocket);
        mConnectedThread.start();
    }
}
Espero me puedan ayudar y haber me explicado bien
Excelente día.
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder