Unable to understand mHandler.obtainMessage () in bluetooth bluetooth example

I am working on a rfcomm bluetooth connection. There is a line in Android Sample that I cannot understand, and, unfortunately, I could not find a good answer in other questions and resources.

Here is the whole code:

public void run() { byte[] buffer = new byte[1024]; // buffer store for the stream int bytes; // bytes returned from read() // Keep listening to the InputStream until an exception occurs while (true) { try { // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); } catch (IOException e) { break; } } } /* Call this from the main activity to send data to the remote device */ public void write(byte[] bytes) { try { mmOutStream.write(bytes); } catch (IOException e) { } } 

I can not understand this line:

  // Read from the InputStream bytes = mmInStream.read(buffer); // Send the obtained bytes to the UI activity mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer) .sendToTarget(); 

mHandler is not defined in this code, as well as MESSAGE_READ

I do not understand what bytes does?

I think, and as mentioned in the comment, it sends the received bytes to the action that I set as the main activity. Can I make Static TextView in my main activity instead of sendToTarget () to display the received message?

+6
source share
1 answer

The main goal of Handler is to provide an interface between the producer and consumer threads, here, between the user interface thread and the workflow. The implementation of Handler goes to the consumer branch.

In your case, you want to communicate MESSAGE_READ between threads.

Without a handler, you cannot do anything from your main theme of activity.

Therefore, look for mHandler initiation in the main activity.

The default init handler should look like this:

 Handler mHandler = new Handler(){ @Override public void handleMessage(Message msg) { /**/ } }; 

If you use Eclipse, click on your project β†’ Ctrl + H β†’ File Search β†’ "Handler".

Or in Notepad ++ β†’ Serch β†’ Find in Files ....

[EDIT]

 final int MESSAGE_READ = 9999; // its only identifier to tell to handler what to do with data you passed through. // Handler in DataTransferActivity public Handler mHandler = new Handler() { public void handleMessage(Message msg) { switch (msg.what) { case SOCKET_CONNECTED: { mBluetoothConnection = (ConnectionThread) msg.obj; if (!mServerMode) mBluetoothConnection.write("this is a message".getBytes()); break; } case DATA_RECEIVED: { data = (String) msg.obj; tv.setText(data); if (mServerMode) mBluetoothConnection.write(data.getBytes()); } case MESSAGE_READ: // your code goes here 

I am sure you should implement something like:

 new ConnectionThread(mBluetoothSocket, mHandler); 

sources i found here

+7
source

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


All Articles