I am a new java programmer in Eclipse for Android platform. I am working on an android app which will receive multicast data through wifi interface and display the same in a TextView. The data will be updated every 1 sec.
I have the code as below. But i am facing problem in updating the GUI.in this code the network receive and gui are done in same thread i.e. main thread that's why my application in hanging.
I had tried using AsynchTask but could not succeed because i dont know how exactly to use it.
package com.example.cdttiming; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.UnknownHostException; import android.app.Activity; import android.content.Context; import android.net.wifi.WifiManager; import android.os.Bundle; import android.view.Menu; import android.widget.EditText; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); EditText Seconds; Seconds =(EditText)findViewById(R.id.Seconds); WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE); WifiManager.MulticastLock multicastLock = wm.createMulticastLock("mydebuginfo"); multicastLock.setReferenceCounted(true); multicastLock.acquire(); InetAddress ia = null; byte[] buffer = new byte[65535]; MulticastSocket ms = null; int port = 4321; try { ia = InetAddress.getByName("226.1.1.1"); DatagramPacket dp = new DatagramPacket(buffer, buffer.length,ia,port); ms = new MulticastSocket(port); ms.setReuseAddress(true); ms.joinGroup(ia); while (true) { ms.receive(dp); String s = new String(dp.getData(),0,dp.getLength()); Seconds.setText(s); } } catch (UnknownHostException e) { Seconds.setText(e.getMessage()); } catch (IOException e) { Seconds.setText(e.getMessage()); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } }
Can anyone tell me how to use above code so that I may receive the data every second and display that in the TextView?
Thank u all in advance
Source: http://stackoverflow.com/questions/17631795/continuously-updating-gui-in-java-android
Jeff Bauman cbs news Boston.com NBA Playoffs 2013 Watertown Boston npr Oblivion
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.