Wednesday, November 28, 2012

GPS data from Wifly to Android phone (Part 2)

As a proof of concept, I have created a simple app that fetches the last UDP packet received, and displays its contents in a floating message box, each time the button is pressed.



Here is an excerpt of the app's java code that is used for that.

...
public class MainActivity extends Activity {
   ...
   public void sendMessage(View view) {
        new ServerAsyncTask(MainActivity.this).execute();
   }
   ...
   public static class ServerAsyncTask
               extends AsyncTask<Void, String, Void> {
      private Activity act;
      public ServerAsyncTask(Activity _act) {
           this.act = _act;
      }
      @Override
      protected String doInBackground(Void... params) {
         byte[] receiveData = new byte[1024];
         DatagramSocket socket = null;
         try {
            socket = new DatagramSocket(50000);
            socket.setSoTimeout(30000);
            DatagramPacket packet =
               new DatagramPacket(receiveData, receiveData.length);
            socket.receive(packet);
            String contents = new String(packet.getData());
            publishProgress(contents);
            socket.close();
         } catch (SocketException e) {
             socket.close();
         } catch (SocketTimeoutException e) {
             socket.close();
         } catch (IOException e) {
             socket.close();
         }

         return (Void)null;
      }
     
      @Override
      protected void onProgressUpdate(String... str) {
         Toast.makeText(act, str[0], Toast.LENGTH_SHORT).show();
      }
   }
}
 

No comments:

Post a Comment