开发者

Android App, and socket

I want to implement an android app which could communicate with a Server via internet. Since everytime the Android app connects to Server, there will be a connection established, and Android app will maintain this connection for the purpose of receiving msgs from Server. However, at the same time the Android app has to deal with User inputs, so these two tasks have to run concurrently that needs to realize by two Threads. I do not have experience about multi-threads 开发者_高级运维programming. any suggestions? Thanks. leon.


The user interface is being handled by the main thread, so really you just have to set up one thread handling the networking (in fact, on 3.0 and on opening a socket connection from the main thread will throw an exception!).

Set up and maintain the connection to the server using an AsyncTask - this is a fairly easy way of doing multi threading. Take a look at this documentation: http://developer.android.com/resources/articles/painless-threading.html


Did you try to put the server interaction into a thread? This should be no problem at all

 Thread thread = new Thread(this){
    public void run() {
        // do your server interaction
    }
  }
  thread.start();


You may want to consider Google's Cloud To Device Messaging (C2DM). They manage to keep a connection open to a device for long periods and will push your server notifications to any android device. I believe its still currently in the 'labs' stage though.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜