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();
      }
   }
}
 

2 comments:

  1. Is there any way to do this the other way around. Where the wifly module acts as the AP and android connects and sends data to it?

    ReplyDelete
    Replies
    1. This was not possible at the time that I wrote this, but I understand that a new firmware for the Wifly now makes this possible. But I have never tested it, as I am now using the ESP8266 chip for my Wifi projects, which I use as an AP in the way that you describe.

      Delete