WEB开发网
开发学院手机开发Android 开发 Android socket编程 以非阻塞I/O服务器及Service为... 阅读

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);b

{

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

}

}

}

}

上一页  1 2 3 4 5 6 

Tags:Android socket 编程

编辑录入:coldstar [复制链接] [打 印]
赞助商链接