您好,登錄后才能下訂單哦!
今天就跟大家聊聊有關怎么在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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。