今天就跟大家聊聊有关怎么在Android应用中实现一个实时通信功能,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。
实现原理
就是将发送端,接收端分别放进一个线程去运行,然后利用线程通信类handler来进行线程间的通信,实现界面的通信
实现代码:
权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"></uses-permission> <uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission> <uses-permission android:name="android.permission.INTERNET"/>
Layout
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" tools:context="com.ysp.asus.experiment_02.MainActivity" android:weightSum="10"> <Button android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="#03A9F4" android:textColor="#FFFFFFFF" android:textSize="30sp" android:text="IP" android:id="@+id/myIP"/> <!--点击开始聊天--> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:weightSum="10"> <!--IP--> <EditText android:layout_width="match_parent" android:layout_height="match_parent" android:layout_weight="1" android:id="@+id/IP" android:hint="请写入对方通讯地址IP" /> </LinearLayout> <!--显示聊天记录--> <EditText android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="7" android:gravity="top" android:editable="false" android:scrollbars="vertical" android:id="@+id/receiveMessage"/> <!--用于写入发送信息和按钮--> <LinearLayout android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1"> <EditText android:layout_width="0dp" android:layout_weight="8" android:layout_height="match_parent" android:hint="填写要发送的信息" android:id="@+id/message"/> <Button android:layout_width="0dp" android:layout_weight="2" android:layout_height="match_parent" android:text="发送消息" android:background="#03A9F4" android:textColor="#FFFFFFFF" android:id="@+id/sendMessage"/> </LinearLayout> </LinearLayout>
客户端类
package com.ysp.asus.experiment_02; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.Socket; import java.net.UnknownHostException; /** * Created by asus on 2017/3/16. */ public class ChatClient { public Socket requestSocket(String host) throws UnknownHostException,IOException{ Socket socket=new Socket(host,5000); return socket; } public void sendMsg(Socket socket,String msg)throws IOException{ BufferedWriter writer=new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()) ); writer.write(msg.replace("\n","")+"\n"); writer.flush(); } public String receiveMsg(Socket socket)throws IOException{ BufferedReader reader=new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String txt=reader.readLine(); return txt; } }
服务端类
package com.ysp.asus.experiment_02; import android.os.Handler; import android.os.Message; import android.util.Log; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; /** * Created by asus on 2017/3/16. */ public class ChatServer extends Thread { public ChatServer() throws IOException { createSocket(); } public void run(){ Socket client; String txt; Log.i("信息","成功开始服务器,端口为:"+PORT); try{ while (true){ client=ResponseSocket(); while(true){ txt=ReceiveMsg(client); System.out.println(txt); Message message1 = new Message(); message1.obj =txt+"\n"; com.ysp.asus.experiment_02.MainActivity.handler.sendMessage(message1); if(true) break; } // CloseSocket(client); } }catch (IOException e){ } } private Handler mHandler = new Handler(){ public void handleMessage(Message msg) { }; }; public ServerSocket server=null; private int PORT =5000; private BufferedWriter writer; private BufferedReader reader; public void createSocket() throws IOException{ server=new ServerSocket(PORT,100); } public Socket ResponseSocket() throws IOException{ Socket client =server.accept(); return client; } public void CloseSocket(Socket socket) throws IOException{ reader.close(); socket.close(); server.close(); } public void sendMsg(Socket socket,String string)throws IOException{ writer=new BufferedWriter( new OutputStreamWriter(socket.getOutputStream()) ); writer.write("msg"+string); writer.flush(); } public String ReceiveMsg(Socket socket) throws IOException{ reader=new BufferedReader( new InputStreamReader(socket.getInputStream()) ); String txt ="对方:"+reader.readLine(); return txt; } }
MainActivity类
package com.ysp.asus.experiment_02; import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.text.ClipboardManager; import android.util.Log; import android.view.View; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import java.io.IOException; import java.net.Socket; import static com.ysp.asus.experiment_02.R.id.receiveMessage; public class MainActivity extends AppCompatActivity { final ChatServer chatServer=null; static String text=""; static EditText receivemessage=null; final ChatClient chatClient = new ChatClient(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 定义相关的变量 receivemessage=(EditText) findViewById(receiveMessage); final EditText message=(EditText)findViewById(R.id.message); final EditText IP = (EditText)findViewById(R.id.IP); final Button sendmessage = (Button)findViewById(R.id.sendMessage); final Button myIP =(Button) findViewById(R.id.myIP); // 获取wifi下的IP地址并显示 //获取wifi服务 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); //判断wifi是否开启 if (!wifiManager.isWifiEnabled()) { wifiManager.setWifiEnabled(true); } WifiInfo wifiInfo = wifiManager.getConnectionInfo(); int ipAddress = wifiInfo.getIpAddress(); String ip = intToIp(ipAddress); myIP.setText(ip); // 点击实现复制内容到粘贴板 myIP.setClickable(true); myIP.setOnClickListener(new Button.OnClickListener() { public void onClick(View arg0) { ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); // 将文本内容放到系统剪贴板里。 cm.setText(myIP.getText().toString()); } }); // 初始化看是服务器 try{ ChatServer chatServer=new ChatServer(); chatServer.start(); }catch(IOException e){ Log.e("错误","开启服务器失败"); e.printStackTrace(); } // 点击按钮发送数据给相应的IP地址 sendmessage.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { HideKeyboard(sendmessage); new Thread(new Runnable() { @Override public void run() { try { Socket socket=chatClient.requestSocket(IP.getText().toString()); chatClient.sendMsg(socket,message.getText().toString()); Message message1 = new Message(); message1.obj ="自己: "+message.getText().toString()+"\n"; handler.sendMessage(message1); }catch (IOException e){ Log.e("错误","发送失败"); } } }).start(); } }); } public static Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { super.handleMessage(msg); Log.i("信息","其他线程发过来:"+msg); text+=msg.obj.toString(); receivemessage.setText(text); receivemessage.setSelection(receivemessage.getText().length(), receivemessage.getText().length()); } }; // 用于将结果以IP的形式放出 private String intToIp(int i) { return (i & 0xFF ) + "." + ((i >> 8 ) & 0xFF) + "." + ((i >> 16 ) & 0xFF) + "." + ( i >> 24 & 0xFF) ; } //隐藏虚拟键盘 public static void HideKeyboard(View v) { InputMethodManager imm = ( InputMethodManager ) v.getContext( ).getSystemService( Context.INPUT_METHOD_SERVICE ); if ( imm.isActive( ) ) { imm.hideSoftInputFromWindow( v.getApplicationWindowToken( ) , 0 ); } } }
看完上述内容,你们对怎么在Android应用中实现一个实时通信功能有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。