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")); } }; }
runOnuiThread. ButrunOnuiThreadis a method of activity class. you cannot update ui on the background thread. ui should be updated on the ui threadHandler,runOnUiThread()orAsyncTask.