Android 应用侦听传入 TCP/IP 消息的最佳方式是啥?
Posted
技术标签:
【中文标题】Android 应用侦听传入 TCP/IP 消息的最佳方式是啥?【英文标题】:What's the best way for an Android app to listen for incomming TCP/IP messages?Android 应用侦听传入 TCP/IP 消息的最佳方式是什么? 【发布时间】:2012-04-09 00:51:15 【问题描述】:我想编写一个应用程序,只要它在服务器范围内(在同一个 WiFi 网络上),它就会监听警报消息。最好的方法是什么?
我是否应该简单地编写一个充当 TCP/IP 服务器的服务,当它接收到消息时,让它们生成 android 通知?还是有更好的方法来做到这一点?
我需要这个应用程序在 Android 运行时一直运行。 如何确保我的“侦听器”服务始终运行?
提前谢谢..
莱夫斯特
【问题讨论】:
它会耗尽电池电量。使用 C2DM... 【参考方案1】:我有同样的问题...我想使用彗星,但我没有太多时间研究它..
你可以在这里看到一些示例.. http://blogs.webtide.com/dyu/entry/android_chat_using_jetty_cometd
我选择了无限循环进行通信
这是我的代码..
public class ServerActivity extends Activity
private TextView serverStatus;
// default ip
public static String SERVERIP = "10.0.2.15";
// designate a port
public static final int SERVERPORT = 12345;
private Handler handler = new Handler();
private ServerSocket serverSocket;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.server);
serverStatus = (TextView) findViewById(R.id.server_status);
SERVERIP = getLocalIpAddress();
Thread fst = new Thread(new ServerThread());
fst.start();
public class ServerThread implements Runnable
String line = "";
public void run()
try
if (SERVERIP != null)
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText("Listening on IP: " + SERVERIP);
);
serverSocket = new ServerSocket(SERVERPORT);
while (true)
// listen for incoming clients
Socket client = serverSocket.accept();
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText("Connected.");
);
try
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
// byte[] resultBuff = new byte[0];
// byte[] buff = new byte[1024];
// int k = -1;
// while((k = client.getInputStream().read(buff, 0, buff.length)) > -1)
// byte[] tbuff = new byte[resultBuff.length + k]; // temp buffer size = bytes already read + bytes last read
// System.arraycopy(resultBuff, 0, tbuff, 0, resultBuff.length); // copy previous bytes
//System.arraycopy(buff, 0, tbuff, resultBuff.length, k); // copy current lot
//resultBuff = tbuff; // call the temp buffer as your result buff
//
//System.out.println(resultBuff.length + " bytes read.");
while ((line = in.readLine()) != null)
Log.d("ServerActivity", line);
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText(line);
);
break;
catch (Exception e)
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText("Oops. Connection interrupted. Please reconnect your phones.");
);
e.printStackTrace();
else
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText("Couldn't detect internet connection.");
);
catch (Exception e)
handler.post(new Runnable()
@Override
public void run()
serverStatus.setText("Error");
);
e.printStackTrace();
【讨论】:
以上是关于Android 应用侦听传入 TCP/IP 消息的最佳方式是啥?的主要内容,如果未能解决你的问题,请参考以下文章