I below is my code for receiving Multicast Wifi Data on android. I am using runnables like below to update the GUI but i found thatsome packets are missing. I am using this code to receive count down message but the count down is not continious. I dont know whether packets are lost due to the style of GUI updating or due to some other problem. request you all to give suggestions.
package com.example.cdttiming;
public class MainActivity extends Activity
{
EditText time;
String s;
Button button;
InetAddress ia = null;
byte[] bmessage = new byte[1500];
DatagramPacket dp = new DatagramPacket(bmessage, bmessage.length);
MulticastSocket ms = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
time = (EditText) findViewById(R.id.et_time);
try
{
WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
//wm.setWifiEnabled(true);
WifiManager.MulticastLock multicastLock = wm.createMulticastLock("multicastLock");
multicastLock.setReferenceCounted(true);
multicastLock.acquire();
ia = InetAddress.getByName("226.1.1.1");
try {
ms = new MulticastSocket(4321);
} catch (IOException e) {
e.printStackTrace();
}
try {
ms.joinGroup(ia);
} catch (IOException e) {
e.printStackTrace();
}
ms.setReuseAddress(true);
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public void startProgress(View view) {
Runnable runnable = new Runnable() {
@Override
public void run() {
while(true)
{
try
{
ms.receive(dp);
s = new String(dp.getData(),0,dp.getLength());
}
catch (UnknownHostException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
time.post(new Runnable() {
@Override
public void run() {
time.setText(s);
}
});
} // while
}
};
new Thread(runnable).start();
}
@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;
}
}