最近做這個功能,分享一下。即時通訊(Instant Messaging)最重要的毫無疑問就是即時,
不能有明顯的延遲,要實現IM的功能其實並不難,目前有很多第三方,比如極光的JMessage,都比較容易實現。
但是如果項目有特殊要求(如不能使用外網),那就得自己做了,所以我們需要使用WebSocket。
WebSocket
WebSocket協議就不細講了,感興趣的可以具體查閱資料,簡而言之,
它就是一個可以建立長連接的全雙工(full-duplex)通信協議,允許服務器端主動發送信息給客戶端。
Java-WebSocket框架
對於使用websocket協議,Android端已經有些成熟的框架了,在經過對比之后,我選擇了Java-WebSocket這個開源框架,
GitHub地址:https://github.com/TooTallNate/Java-WebSocket,目前已經有五千以上star,並且還在更新維護中,
所以本文將介紹如何利用此開源庫實現一個穩定的即時通訊功能。
效果圖
國際慣例,先上效果圖




文章重點
1、與websocket建立長連接
2、與websocket進行即時通訊
3、Service和Activity之間通訊和UI更新
4、彈出消息通知(包括鎖屏通知)
5、心跳檢測和重連(保證websocket連接穩定性)
6、服務(Service)保活
一、引入Java-WebSocket
1、build.gradle中加入
implementation "org.java-websocket:Java-WebSocket:1.4.0"
2、加入網絡請求權限
<uses-permission android:name="android.permission.INTERNET" />
3、新建客戶端類
新建一個客戶端類並繼承WebSocketClient,需要實現它的四個抽象方法和構造函數,如下:
public class JWebSocketClient extends WebSocketClient { public JWebSocketClient(URI serverUri) { super(serverUri, new Draft_6455()); } @Override public void onOpen(ServerHandshake handshakedata) { Log.e("JWebSocketClient", "onOpen()"); } @Override public void onMessage(String message) { Log.e("JWebSocketClient", "onMessage()"); } @Override public void onClose(int code, String reason, boolean remote) { Log.e("JWebSocketClient", "onClose()"); } @Override public void onError(Exception ex) { Log.e("JWebSocketClient", "onError()"); } }
其中onOpen()方法在websocket連接開啟時調用,onMessage()方法在接收到消息時調用,onClose()方法在連接斷開時調用,
onError()方法在連接出錯時調用。構造方法中的new Draft_6455()代表使用的協議版本,這里可以不寫或者寫成這樣即可。
4、建立websocket連接
建立連接只需要初始化此客戶端再調用連接方法,需要注意的是WebSocketClient對象是不能重復使用的,所以不能重復初始化,其他地方只能調用當前這個Client。
URI uri = URI.create("ws://*******"); JWebSocketClient client = new JWebSocketClient(uri) { @Override public void onMessage(String message) { //message就是接收到的消息 Log.e("JWebSClientService", message); } };
為了方便對接收到的消息進行處理,可以在這重寫onMessage()方法。初始化客戶端時需要傳入websocket地址(測試地址:ws://echo.websocket.org),websocket協議地址大致是這樣的
ws:// ip地址 : 端口號
連接時可以使用connect()方法或connectBlocking()方法,建議使用connectBlocking()方法,connectBlocking多出一個等待操作,會先連接再發送。
try { client.connectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); }
運行之后可以看到客戶端的onOpen()方法得到了執行,表示已經和websocket建立了連接

5、發送消息
發送消息只需要調用send()方法,如下
if (client != null && client.isOpen()) { client.send("你好"); }
6、關閉socket連接
關閉連接調用close()方法,最后為了避免重復實例化WebSocketClient對象,關閉時一定要將對象置空。
/** * 斷開連接 */ private void closeConnect() { try { if (null != client) { client.close(); } } catch (Exception e) { e.printStackTrace(); } finally { client = null; } }
二、后台運行
一般來說即時通訊功能都希望像QQ微信這些App一樣能在后台保持運行,當然App保活這個問題本身就是個偽命題,我們只能盡可能保活,
所以首先就是建一個Service,將websocket的邏輯放入服務中運行並盡可能保活,讓websocket保持連接。
1、新建Service
新建一個Service,在啟動Service時實例化WebSocketClient對象並建立連接,將上面的代碼搬到服務里即可。
2、Service和Activity之間通訊
由於消息是在Service中接收,從Activity中發送,需要獲取到Service中的WebSocketClient對象,所以需要進行服務和活動之間的通訊,這就需要用到Service中的onBind()方法了。
首先新建一個Binder類,讓它繼承自Binder,並在內部提供相應方法,然后在onBind()方法中返回這個類的實例。
public class JWebSocketClientService extends Service { private URI uri; public JWebSocketClient client; private JWebSocketClientBinder mBinder = new JWebSocketClientBinder(); //用於Activity和service通訊 class JWebSocketClientBinder extends Binder { public JWebSocketClientService getService() { return JWebSocketClientService.this; } } @Override public IBinder onBind(Intent intent) { return mBinder; } }
接下來就需要對應的Activity綁定Service,並獲取Service的東西,代碼如下
public class MainActivity extends AppCompatActivity { private JWebSocketClient client; private JWebSocketClientService.JWebSocketClientBinder binder; private JWebSocketClientService jWebSClientService; private ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { //服務與活動成功綁定 Log.e("MainActivity", "服務與活動成功綁定"); binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder; jWebSClientService = binder.getService(); client = jWebSClientService.client; } @Override public void onServiceDisconnected(ComponentName componentName) { //服務與活動斷開 Log.e("MainActivity", "服務與活動成功斷開"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService(); } /** * 綁定服務 */ private void bindService() { Intent bindIntent = new Intent(MainActivity.this, JWebSocketClientService.class); bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE); } }
這里首先創建了一個ServiceConnection匿名類,在里面重寫onServiceConnected()和onServiceDisconnected()方法,
這兩個方法會在活動與服務成功綁定以及連接斷開時調用。在onServiceConnected()首先得到JWebSocketClientBinder的實例,
有了這個實例便可調用服務的任何public方法,這里調用getService()方法得到Service實例,
得到了Service實例也就得到了WebSocketClient對象,也就可以在活動中發送消息了。
三、從Service中更新Activity的UI
當Service中接收到消息時需要更新Activity中的界面,方法有很多,這里我們利用廣播來實現,
在對應Activity中定義廣播接收者,Service中收到消息發出廣播即可。
public class MainActivity extends AppCompatActivity { ... private class ChatMessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String message=intent.getStringExtra("message"); } } /** * 動態注冊廣播 */ private void doRegisterReceiver() { chatMessageReceiver = new ChatMessageReceiver(); IntentFilter filter = new IntentFilter("com.xch.servicecallback.content"); registerReceiver(chatMessageReceiver, filter); } ... }
上面的代碼很簡單,首先創建一個內部類並繼承自BroadcastReceiver,也就是代碼中的廣播接收器ChatMessageReceiver,
然后動態注冊這個廣播接收器。當Service中接收到消息時發出廣播,就能在ChatMessageReceiver里接收廣播了。
發送廣播:
client = new JWebSocketClient(uri) { @Override public void onMessage(String message) { Intent intent = new Intent(); intent.setAction("com.xch.servicecallback.content"); intent.putExtra("message", message); sendBroadcast(intent); } };
獲取廣播傳過來的消息后即可更新UI,具體布局就不細說,比較簡單,看下我的源碼就知道了,demo地址我會放到文章末尾。
四、消息通知
消息通知直接使用Notification,只是當鎖屏時需要先點亮屏幕,代碼如下
/** * 檢查鎖屏狀態,如果鎖屏先點亮屏幕 * * @param content */ private void checkLockAndShowNotification(String content) { //管理鎖屏的一個服務 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE); if (km.inKeyguardRestrictedInputMode()) {//鎖屏 //獲取電源管理器對象 PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE); if (!pm.isScreenOn()) { @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "bright"); wl.acquire(); //點亮屏幕 wl.release(); //任務結束后釋放 } sendNotification(content); } else { sendNotification(content); } } /** * 發送通知 * * @param content */ private void sendNotification(String content) { Intent intent = new Intent(); intent.setClass(this, MainActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationManager notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = new NotificationCompat.Builder(this) .setAutoCancel(true) // 設置該通知優先級 .setPriority(Notification.PRIORITY_MAX) .setSmallIcon(R.mipmap.ic_launcher) .setContentTitle("昵稱") .setContentText(content) .setVisibility(VISIBILITY_PUBLIC) .setWhen(System.currentTimeMillis()) // 向通知添加聲音、閃燈和振動效果 .setDefaults(Notification.DEFAULT_VIBRATE | Notification.DEFAULT_ALL | Notification.DEFAULT_SOUND) .setContentIntent(pendingIntent) .build(); notifyManager.notify(1, notification);//id要保證唯一 }
如果未收到通知可能是設置里通知沒開,進入設置打開即可,如果鎖屏時無法彈出通知,可能是未開啟鎖屏通知權限,也需進入設置開啟。
為了保險起見我們可以判斷通知是否開啟,未開啟引導用戶開啟,代碼如下:
/** * 檢測是否開啟通知 * * @param context */ private void checkNotification(final Context context) { if (!isNotificationEnabled(context)) { new AlertDialog.Builder(context).setTitle("溫馨提示") .setMessage("你還未開啟系統通知,將影響消息的接收,要去開啟嗎?") .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setNotification(context); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); } } /** * 如果沒有開啟通知,跳轉至設置界面 * * @param context */ private void setNotification(Context context) { Intent localIntent = new Intent(); //直接跳轉到應用通知設置的代碼: if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { localIntent.setAction("android.settings.APP_NOTIFICATION_SETTINGS"); localIntent.putExtra("app_package", context.getPackageName()); localIntent.putExtra("app_uid", context.getApplicationInfo().uid); } else if (android.os.Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) { localIntent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); localIntent.addCategory(Intent.CATEGORY_DEFAULT); localIntent.setData(Uri.parse("package:" + context.getPackageName())); } else { //4.4以下沒有從app跳轉到應用通知設置頁面的Action,可考慮跳轉到應用詳情頁面 localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); if (Build.VERSION.SDK_INT >= 9) { localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS"); localIntent.setData(Uri.fromParts("package", context.getPackageName(), null)); } else if (