How to add a toast method inside a thread. I want to debug by replacing the system.out with a toast method to display results to the display.
I know that using the application Context from within the thread, like so: Toast.makeText(getApplicationContext(), "help", Toast.LENGTH_LONG).show(); will not work.
I don't know how to use the Runnable with the Toast call and calling runOnUiThread(runnable) from the Thread
Could someone help me out.
public class NetworkServer extends Thread
{
DatagramSocket mSocket = null;
boolean isFinish = false;
private SimplestPossibleActivity activity;
public NetworkServer(SimplestPossibleActivity activity)
{
this.activity = activity;
}
public void run()
{
try
{
Log.d("UDP", "Listening");
mSocket = new DatagramSocket( 2010); //4444
mSocket.setBroadcast(true);
while (!isFinish)
{
Log.d("UDP", "C: socket create success");
byte[] recvbuffer = new byte[12];
DatagramPacket packet = new DatagramPacket(recvbuffer,recvbuffer.length);
Log.d("UDP", "receiving...");
mSocket.receive(packet);
Log.d("UDP", "received packet");
ByteBuffer bb = ByteBuffer.allocate(recvbuffer.length).order(ByteOrder.LITTLE_ENDIAN);
bb.put(recvbuffer);
bb.rewind();
//System.out.println(bb.getFloat());
//System.out.println(bb.getFloat());
//System.out.println(bb.getFloat());
Bundle data = new Bundle();
data.putFloat("latitude", bb.getFloat());
data.putFloat("longitude", bb.getFloat());
data.putFloat("altitude", bb.getFloat());
Message msgHandle = new Message();
msgHandle.setData(data);
mhandler.sendMessage(msgHandle);
} //end while
} catch (Exception e) {
Log.e("UDP", "C: Error", e);
}
}
private Handler mhandler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
Bundle data = msg.getData();
Log.d("NetworkServer","adding position" + "lat = " + data.getFloat("latitude") +
"lon = " + data.getFloat("longitude") +
"alt = " + data.getFloat("altitude"));
activity.addPosition(data.getFloat("latitude"),
data.getFloat("longitude"),
data.getFloat("altitude"));
}
};
}
Use library Xdroid:
dependencies {
compile 'com.shamanland:xdroid-toaster:0.2.4'
}
There are quite good approaches:
Context
variable is not required.runOnUiThread()
is not required.Just invoke the single method!
// using the resource string
Toaster.toast(R.string.my_msg);
// or hard-coded string
Toaster.toast("Hello Xdroid!");
There are more examples here: https://github.com/shamanland/xdroid-toaster-example
You can do it like thisHandler handler = new Handler(); //Before your Thread
//Within your thread
handler.post(new Runnable(){
public void run() {
Toast.makeText(getApplicationContext(), "help", Toast.LENGTH_LONG).show();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With