This question has already been answered:

Hello.

It is necessary to transfer the data received via UART to the Activity. This can be done by creating a stream in the Activity in which to organize a while (!isInterrupted()) and read data from the UART buffer. After that, by calling the UI thread Activity - MainActivity.this.runOnUiThread(new Runnable() , perform the necessary actions with this Activity. But if we call other Activities from the main Activity, then the organized stream does not allow to transfer data to the newly created Activity. If I I understand correctly, in order for the data from the stream to be transferred to any Activity, the stream must be created not in the Activity, but in the Service.

Question: did the UART send data, in the stream (which is created in Servce) you need to transfer data to the Activity, which is now active, how can this be done and is it done in general?

Reported as a duplicate by Visman , Nick Volynkin , Aslan Kussein , pavlofff , Aries 29 Oct '15 at 4:58 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

1 answer 1

In each Activity, create a Handler. In the onResume () method of this Activity, bindService () does this. There, one of the parameters is interface ServiceConnection. Implement it at least with the same Activity. Implement the onServiceConnected () method in it. In this callback one of the parameters comes Service itself. So call this Service with your own setHandler () method. Pass there the Handler that is in the current Activity. But the incoming data on the UART throw in the Service on this Handler. By the way, Handler traditionally works in the main thread, so no runOnUiThread will need to be executed.