I am trying to find a way to send a message from the a seperate thread to the UI Thread, is that possible? The thread has not been launched from the MainActivity but from a service, does it make any difference.
Thanks in advance for you help.
Here is the thread from where i would like to send the message i receive to the UI Thread
import java.io.BufferedReader;
import java.io.IOException;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
public class Receive_Client implements Runnable {
private BufferedReader in;
private String message=null;
// The Bundle will hold the String "Location or message" and will transmit it to the handler in the mainActivity
private String[] messageArray=new String[3];
Bundle messageBundle=new Bundle();
// corresponds to the message that will be exchange it with the UIThread Handler
private Message Message;
public Receive_Client(BufferedReader in) {
this.in=in;
}
@Override
public void run() {
// If isRunning is at false the Thread have to stop
while(isRunning.get()){// error here---------->
try{
while (isPausing.get() && (isRunning.get())) {//here also -------->
// Pausing the Thread to relax the CPU
Thread.sleep(2000);
}
if ((message=in.readLine())!=null){
//message=in.readLine();
Log.d(MainActivity.TAG, "the server say"+message);
// Sending the message to the Handle (the method handler.obtainMessage is more efficient
// rather than using a message from zero, optimizing the message pool to the handler)
// message instanciation
messageArray=message.split(",");
Message=handler.obtainMessage(); //---------> the handler also
// Adding data to transmit to handler via Bundle
messageBundle.putStringArray(RECEIVE_LOCATION, messageArray);// the key is not recognized too----->
//adding the bundle to the message
Message.setData(messageBundle);
//send the message
handler.sendMessage(Message);
}
}catch (IOException e){
Log.d(MainActivity.TAG, e.getMessage());}
}
}
}