Blizzhackers

Return of the Jedi

* Login   * Register    * FAQ    * Search

Join us on IRC: #bh@irc.synirc.net (or Mibbit Web IRC)


MuleFactory


It is currently Tue May 21, 2013 8:14 pm


All times are UTC [ DST ]





Post new topic Reply to topic  [ 1 post ] 
Author Message
 Post subject: Android Sockets and Threads
PostPosted: Fri Jun 01, 2012 8:00 pm 
 
User
User

Joined: Wed Jul 09, 2008 4:38 pm
I just started working with Java and the Android SDK and got an app working using sockets. But it seems pretty ugly and I was wondering if there was a better or more elegant way to go about it.

public class HelloAndroidActivity extends Activity {
   
   private TextView textOut, textIn;
   private EditText editOut;
   private Handler mMainHandler, mChildHandler;
   private Socket socket;
   
   /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        textIn = (TextView)findViewById(R.id.textin);
        textOut = (TextView)findViewById(R.id.textout);
        editOut = (EditText)findViewById(R.id.editout);
       
        mMainHandler = new Handler() {
           public void handleMessage(Message msg) {
              textIn.append(msg.obj+"\n");
           }
        };
       
        new ComOutThread().start();
        new ComInThread().start();
       
        Button buttonSend = (Button)findViewById(R.id.send);
        buttonSend.setOnClickListener(new Button.OnClickListener() {
          @Override
          public void onClick(View arg0) {
             //get a recycled message object, send it to comThread
             Message msg = mChildHandler.obtainMessage();
             msg.obj = editOut.getText().toString();
             Log.d("SocketTest", "msg: "+msg.obj);
             mChildHandler.sendMessage(msg);
             
             //update outgoing text
             textOut.append(editOut.getText().toString()+"\n");
          }
        });
    }
   
    public void onDestroy() {
       mChildHandler.getLooper().quit();
       super.onDestroy();
    }
   
    class ComOutThread extends Thread {
       PrintWriter out;
       
       public void run() {
          Looper.prepare();
          try {
             socket = new Socket("192.168.1.160", 4444);
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())));
         } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
          mChildHandler = new Handler() {
             public void handleMessage(Message msg) {
                Log.d("SocketTest", "sending msg: "+msg.obj+"\n");
                out.println(msg.obj);
                out.flush();
             }
          };
          Looper.loop();
       }
    }
   
    class ComInThread extends Thread {
      public void run() {
         String inputLine;
         BufferedReader in = null;
         try {
            while(socket == null) {
               Thread.sleep(200);
            }
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
         } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
         } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
         }
         Log.d("SocketTest", "Input thread started\n");
         try {
            while((inputLine = in.readLine()) != null) {
               Log.d("SocketTest", "getting msg: "+inputLine+"\n");
               Message msg = mMainHandler.obtainMessage();
               msg.obj = inputLine;
               mMainHandler.sendMessage(msg);
            }
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
   }
}


One thing that I thought might help would be to implement my own handler and message queue so the socket communication wouldn't need to be split into two threads, but idk if that would make it any cleaner.

Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 1 post ] 

All times are UTC [ DST ]


Who is online

Users browsing this forum: No registered users and 2 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
Jump to:  
cron