最近作這個功能,分享一下。即時通信(Instant Messaging)最重要的毫無疑問就是即時,不能有明顯的延遲,要實現IM的功能其實並不難,目前有不少第三方,好比極光的JMessage,都比較容易實現。可是若是項目有特殊要求(如不能使用外網),那就得本身作了,因此咱們須要使用WebSocket。java
WebSocket協議就不細講了,感興趣的能夠具體查閱資料,簡而言之,它就是一個能夠創建長鏈接的全雙工(full-duplex)通訊協議,容許服務器端主動發送信息給客戶端。android
對於使用websocket協議,Android端已經有些成熟的框架了,在通過對比以後,我選擇了Java-WebSocket這個開源框架,GitHub地址:https://github.com/TooTallNate/Java-WebSocket,目前已經有五千以上star,而且還在更新維護中,因此本文將介紹如何利用此開源庫實現一個穩定的即時通信功能。git
國際慣例,先上效果圖github
一、與websocket創建長鏈接
二、與websocket進行即時通信
三、Service和Activity之間通信和UI更新
四、彈出消息通知(包括鎖屏通知)
五、心跳檢測和重連(保證websocket鏈接穩定性)
六、服務(Service)保活web
一、build.gradle中加入服務器
implementation "org.java-websocket:Java-WebSocket:1.4.0"
二、加入網絡請求權限微信
<uses-permission android:name="android.permission.INTERNET" />
三、新建客戶端類
新建一個客戶端類並繼承WebSocketClient,須要實現它的四個抽象方法和構造函數,以下:websocket
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()表明使用的協議版本,這裏能夠不寫或者寫成這樣便可。java-web
四、創建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創建了鏈接
五、發送消息
發送消息只須要調用send()方法,以下
if (client != null && client.isOpen()) { client.send("你好"); }
六、關閉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保持鏈接。
一、新建Service
新建一個Service,在啓動Service時實例化WebSocketClient對象並創建鏈接,將上面的代碼搬到服務裏便可。
二、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中的界面,方法有不少,這裏咱們利用廣播來實現,在對應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 (Build.VERSION.SDK_INT <= 8) { localIntent.setAction(Intent.ACTION_VIEW); localIntent.setClassName("com.android.settings", "com.android.setting.InstalledAppDetails"); localIntent.putExtra("com.android.settings.ApplicationPkgName", context.getPackageName()); } } context.startActivity(localIntent); } /** * 獲取通知權限,檢測是否開啓了系統通知 * * @param context */ @TargetApi(Build.VERSION_CODES.KITKAT) private boolean isNotificationEnabled(Context context) { String CHECK_OP_NO_THROW = "checkOpNoThrow"; String OP_POST_NOTIFICATION = "OP_POST_NOTIFICATION"; AppOpsManager mAppOps = (AppOpsManager) context.getSystemService(Context.APP_OPS_SERVICE); ApplicationInfo appInfo = context.getApplicationInfo(); String pkg = context.getApplicationContext().getPackageName(); int uid = appInfo.uid; Class appOpsClass = null; try { appOpsClass = Class.forName(AppOpsManager.class.getName()); Method checkOpNoThrowMethod = appOpsClass.getMethod(CHECK_OP_NO_THROW, Integer.TYPE, Integer.TYPE, String.class); Field opPostNotificationValue = appOpsClass.getDeclaredField(OP_POST_NOTIFICATION); int value = (Integer) opPostNotificationValue.get(Integer.class); return ((Integer) checkOpNoThrowMethod.invoke(mAppOps, value, uid, pkg) == AppOpsManager.MODE_ALLOWED); } catch (Exception e) { e.printStackTrace(); } return false; }
最後加入相關的權限
<!-- 解鎖屏幕須要的權限 --> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <!-- 申請電源鎖須要的權限 --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!--震動權限--> <uses-permission android:name="android.permission.VIBRATE" />
因爲不少不肯定因素會致使websocket鏈接斷開,例如網絡斷開,因此須要保證websocket的鏈接穩定性,這就須要加入心跳檢測和重連。
心跳檢測其實就是個定時器,每一個一段時間檢測一次,若是鏈接斷開則重連,Java-WebSocket框架在目前最新版本中有兩個重連的方法,分別是reconnect()和reconnectBlocking(),這裏一樣使用後者。
private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒進行一次對長鏈接的心跳檢測 private Handler mHandler = new Handler(); private Runnable heartBeatRunnable = new Runnable() { @Override public void run() { if (client != null) { if (client.isClosed()) { reconnectWs(); } } else { //若是client已爲空,從新初始化websocket initSocketClient(); } //定時對長鏈接進行心跳檢測 mHandler.postDelayed(this, HEART_BEAT_RATE); } }; /** * 開啓重連 */ private void reconnectWs() { mHandler.removeCallbacks(heartBeatRunnable); new Thread() { @Override public void run() { try { //重連 client.reconnectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); } } }.start(); }
而後在服務啓動時開啓心跳檢測
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//開啓心跳檢測
咱們打印一下日誌,如圖所示
若是某些業務場景須要App保活,例如利用這個websocket來作推送,那就須要咱們的App後臺服務不被kill掉,固然若是和手機廠商沒有合做,要保證服務一直不被殺死,這多是全部Android開發者比較頭疼的一個事,這裏咱們只能儘量的來保證Service的存活。
一、提升服務優先級(前臺服務)
前臺服務的優先級比較高,它會在狀態欄顯示相似於通知的效果,能夠儘可能避免在內存不足時被系統回收,前臺服務比較簡單就不細說了。有時候咱們但願可使用前臺服務可是又不但願在狀態欄有顯示,那就能夠利用灰色保活的辦法,以下
private final static int GRAY_SERVICE_ID = 1001; //灰色保活手段 public static class GrayInnerService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { startForeground(GRAY_SERVICE_ID, new Notification()); stopForeground(true); stopSelf(); return super.onStartCommand(intent, flags, startId); } @Override public IBinder onBind(Intent intent) { return null; } } //設置service爲前臺服務,提升優先級 if (Build.VERSION.SDK_INT < 18) { //Android4.3如下 ,隱藏Notification上的圖標 startForeground(GRAY_SERVICE_ID, new Notification()); } else if(Build.VERSION.SDK_INT>18 && Build.VERSION.SDK_INT<25){ //Android4.3 - Android7.0,隱藏Notification上的圖標 Intent innerIntent = new Intent(this, GrayInnerService.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); }else{ //暫無解決方法 startForeground(GRAY_SERVICE_ID, new Notification()); }
AndroidManifest.xml中註冊這個服務
<service android:name=".im.JWebSocketClientService$GrayInnerService" android:enabled="true" android:exported="false" android:process=":gray"/>
這裏其實就是開啓前臺服務並隱藏了notification,也就是再啓動一個service並共用一個通知欄,而後stop這個service使得通知欄消失。可是7.0以上版本會在狀態欄顯示「正在運行」的通知,目前暫時沒有什麼好的解決辦法。
二、修改Service的onStartCommand 方法返回值
@Override public int onStartCommand(Intent intent, int flags, int startId) { ... return START_STICKY; }
onStartCommand()返回一個整型值,用來描述系統在殺掉服務後是否要繼續啓動服務,START_STICKY表示若是Service進程被kill掉,系統會嘗試從新建立Service。
三、鎖屏喚醒
PowerManager.WakeLock wakeLock;//鎖屏喚醒 private void acquireWakeLock() { if (null == wakeLock) { PowerManager pm = (PowerManager)this.getSystemService(Context.POWER_SERVICE); wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK|PowerManager.ON_AFTER_RELEASE, "PostLocationService"); if (null != wakeLock) { wakeLock.acquire(); } } }
獲取電源鎖,保持該服務在屏幕熄滅時仍然獲取CPU時,讓其保持運行。
四、其餘保活方式
服務保活還有許多其餘方式,好比進程互拉、一像素保活、申請自啓權限、引導用戶設置白名單等,其實Android 7.0版本之後,目前沒有什麼真正意義上的保活,可是作些處理,總比不作處理強。這篇文章重點是即時通信,對於服務保活有須要的能夠自行查閱更多資料,這裏就不細說了。
最後附上這篇文章源碼地址,GitHub:https://github.com/yangxch/WebSocketClient,若是有幫助幫忙點個star吧。
原創不易,轉載請註明出處!