Android socket编程 以非阻塞I/O服务器及Service为例
2010-08-22 04:49:00 来源:WEB开发网{
ServerListener a=new ServerListener();
a.start();
}
//向Server端发送消息
public void SendMessageToServer(String msg)
{
try
{
ByteBuffer bytebuf = ByteBuffer.allocate(1024);
bytebuf = ByteBuffer.wrap(msg.getBytes("UTF-8"));
client.write(bytebuf);
bytebuf.flip();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void shownotification(String tab)
{
NotificationManager barmanager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Notification msg=new Notification(android.R.drawable.stat_notify_chat,"A Message Coming!",System.currentTimeMillis());
PendingIntent contentIntent=PendingIntent.getActivity(this, 0, new Intent(this,YaoChatRoomAndroid.class), PendingIntent.FLAG_ONE_SHOT);
msg.setLatestEventInfo(this,"Message" , "Message:"+tab, contentIntent);
barmanager.notify(0, msg);
}
private class ServerListener extends Thread
{
public void run () {
try {
//无线循环,监听服务器,如果有不为空的信息送达,则更新Activity的UI
while(true)
{
ByteBuffer buf = ByteBuffer.allocate(1024);
client.read(buf);
buf.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer;
charBuffer = decoder.decode(buf);
String result = charBuffer.toString();
if (result.length()>0)
shownotification(result);
}
}
catch (CharacterCodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
更多精彩
赞助商链接