您好,登錄后才能下訂單哦!
本篇文章為大家展示了怎么在Android中利用WebSocket實(shí)現(xiàn)即時(shí)通訊,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。
WebSocket
WebSocket協(xié)議就不細(xì)講了,感興趣的可以具體查閱資料,簡而言之,它就是一個(gè)可以建立長連接的全雙工(full-duplex)通信協(xié)議,允許服務(wù)器端主動發(fā)送信息給客戶端。
Java-WebSocket框架
對于使用websocket協(xié)議,Android端已經(jīng)有些成熟的框架了,在經(jīng)過對比之后,我選擇了Java-WebSocket這個(gè)開源框架,目前已經(jīng)有五千以上star,并且還在更新維護(hù)中,所以本文將介紹如何利用此開源庫實(shí)現(xiàn)一個(gè)穩(wěn)定的即時(shí)通訊功能。
1、與websocket建立長連接
2、與websocket進(jìn)行即時(shí)通訊
3、Service和Activity之間通訊和UI更新
4、彈出消息通知(包括鎖屏通知)
5、心跳檢測和重連(保證websocket連接穩(wěn)定性)
6、服務(wù)(Service)?;?/p>
一、引入Java-WebSocket
1、build.gradle中加入
implementation "org.java-websocket:Java-WebSocket:1.4.0"
2、加入網(wǎng)絡(luò)請求權(quán)限
<uses-permission android:name="android.permission.INTERNET" />
3、新建客戶端類
新建一個(gè)客戶端類并繼承WebSocketClient,需要實(shí)現(xiàn)它的四個(gè)抽象方法和構(gòu)造函數(shù),如下:
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連接開啟時(shí)調(diào)用,onMessage()方法在接收到消息時(shí)調(diào)用,onClose()方法在連接斷開時(shí)調(diào)用,onError()方法在連接出錯(cuò)時(shí)調(diào)用。構(gòu)造方法中的new Draft_6455()代表使用的協(xié)議版本,這里可以不寫或者寫成這樣即可。
4、建立websocket連接
建立連接只需要初始化此客戶端再調(diào)用連接方法,需要注意的是WebSocketClient對象是不能重復(fù)使用的,所以不能重復(fù)初始化,其他地方只能調(diào)用當(dāng)前這個(gè)Client。
URI uri = URI.create("ws://*******"); JWebSocketClient client = new JWebSocketClient(uri) { @Override public void onMessage(String message) { //message就是接收到的消息 Log.e("JWebSClientService", message); } };
為了方便對接收到的消息進(jìn)行處理,可以在這重寫onMessage()方法。初始化客戶端時(shí)需要傳入websocket地址(測試地址:ws://echo.websocket.org),websocket協(xié)議地址大致是這樣的
ws:// ip地址 : 端口號
連接時(shí)可以使用connect()方法或connectBlocking()方法,建議使用connectBlocking()方法,connectBlocking多出一個(gè)等待操作,會先連接再發(fā)送。
try { client.connectBlocking(); } catch (InterruptedException e) { e.printStackTrace(); }
運(yùn)行之后可以看到客戶端的onOpen()方法得到了執(zhí)行,表示已經(jīng)和websocket建立了連接
5、發(fā)送消息
發(fā)送消息只需要調(diào)用send()方法,如下
if (client != null && client.isOpen()) { client.send("你好"); }
6、關(guān)閉socket連接
關(guān)閉連接調(diào)用close()方法,最后為了避免重復(fù)實(shí)例化WebSocketClient對象,關(guān)閉時(shí)一定要將對象置空。
/** * 斷開連接 */ private void closeConnect() { try { if (null != client) { client.close(); } } catch (Exception e) { e.printStackTrace(); } finally { client = null; } }
二、后臺運(yùn)行
一般來說即時(shí)通訊功能都希望像QQ微信這些App一樣能在后臺保持運(yùn)行,當(dāng)然App?;钸@個(gè)問題本身就是個(gè)偽命題,我們只能盡可能?;?,所以首先就是建一個(gè)Service,將websocket的邏輯放入服務(wù)中運(yùn)行并盡可能?;?,讓websocket保持連接。
1、新建Service
新建一個(gè)Service,在啟動Service時(shí)實(shí)例化WebSocketClient對象并建立連接,將上面的代碼搬到服務(wù)里即可。
2、Service和Activity之間通訊
由于消息是在Service中接收,從Activity中發(fā)送,需要獲取到Service中的WebSocketClient對象,所以需要進(jìn)行服務(wù)和活動之間的通訊,這就需要用到Service中的onBind()方法了。
首先新建一個(gè)Binder類,讓它繼承自Binder,并在內(nèi)部提供相應(yīng)方法,然后在onBind()方法中返回這個(gè)類的實(shí)例。
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; } }
接下來就需要對應(yīng)的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) { //服務(wù)與活動成功綁定 Log.e("MainActivity", "服務(wù)與活動成功綁定"); binder = (JWebSocketClientService.JWebSocketClientBinder) iBinder; jWebSClientService = binder.getService(); client = jWebSClientService.client; } @Override public void onServiceDisconnected(ComponentName componentName) { //服務(wù)與活動斷開 Log.e("MainActivity", "服務(wù)與活動成功斷開"); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); bindService(); } /** * 綁定服務(wù) */ private void bindService() { Intent bindIntent = new Intent(MainActivity.this, JWebSocketClientService.class); bindService(bindIntent, serviceConnection, BIND_AUTO_CREATE); } }
這里首先創(chuàng)建了一個(gè)ServiceConnection匿名類,在里面重寫onServiceConnected()和onServiceDisconnected()方法,這兩個(gè)方法會在活動與服務(wù)成功綁定以及連接斷開時(shí)調(diào)用。在onServiceConnected()首先得到JWebSocketClientBinder的實(shí)例,有了這個(gè)實(shí)例便可調(diào)用服務(wù)的任何public方法,這里調(diào)用getService()方法得到Service實(shí)例,得到了Service實(shí)例也就得到了WebSocketClient對象,也就可以在活動中發(fā)送消息了。
三、從Service中更新Activity的UI
當(dāng)Service中接收到消息時(shí)需要更新Activity中的界面,方法有很多,這里我們利用廣播來實(shí)現(xiàn),在對應(yīng)Activity中定義廣播接收者,Service中收到消息發(fā)出廣播即可。
public class MainActivity extends AppCompatActivity { ... private class ChatMessageReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { String message=intent.getStringExtra("message"); } } /** * 動態(tài)注冊廣播 */ private void doRegisterReceiver() { chatMessageReceiver = new ChatMessageReceiver(); IntentFilter filter = new IntentFilter("com.xch.servicecallback.content"); registerReceiver(chatMessageReceiver, filter); } ... }
上面的代碼很簡單,首先創(chuàng)建一個(gè)內(nèi)部類并繼承自BroadcastReceiver,也就是代碼中的廣播接收器ChatMessageReceiver,然后動態(tài)注冊這個(gè)廣播接收器。當(dāng)Service中接收到消息時(shí)發(fā)出廣播,就能在ChatMessageReceiver里接收廣播了。
發(fā)送廣播:
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,具體布局就不細(xì)說,比較簡單,看下我的源碼就知道了,demo地址我會放到文章末尾。
四、消息通知
消息通知直接使用Notification,只是當(dāng)鎖屏?xí)r需要先點(diǎn)亮屏幕,代碼如下
/** * 檢查鎖屏狀態(tài),如果鎖屏先點(diǎn)亮屏幕 * * @param content */ private void checkLockAndShowNotification(String content) { //管理鎖屏的一個(gè)服務(wù) 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(); //點(diǎn)亮屏幕 wl.release(); //任務(wù)結(jié)束后釋放 } sendNotification(content); } else { sendNotification(content); } } /** * 發(fā)送通知 * * @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) // 設(shè)置該通知優(yōu)先級 .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要保證唯一 }
如果未收到通知可能是設(shè)置里通知沒開,進(jìn)入設(shè)置打開即可,如果鎖屏?xí)r無法彈出通知,可能是未開啟鎖屏通知權(quán)限,也需進(jìn)入設(shè)置開啟。為了保險(xiǎn)起見我們可以判斷通知是否開啟,未開啟引導(dǎo)用戶開啟,代碼如下:
最后加
/** * 檢測是否開啟通知 * * @param context */ private void checkNotification(final Context context) { if (!isNotificationEnabled(context)) { new AlertDialog.Builder(context).setTitle("溫馨提示") .setMessage("你還未開啟系統(tǒng)通知,將影響消息的接收,要去開啟嗎?") .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(); } } /** * 如果沒有開啟通知,跳轉(zhuǎn)至設(shè)置界面 * * @param context */ private void setNotification(Context context) { Intent localIntent = new Intent(); //直接跳轉(zhuǎn)到應(yīng)用通知設(shè)置的代碼: 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跳轉(zhuǎn)到應(yīng)用通知設(shè)置頁面的Action,可考慮跳轉(zhuǎn)到應(yīng)用詳情頁面 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); } /** * 獲取通知權(quán)限,檢測是否開啟了系統(tǒng)通知 * * @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; }
入相關(guān)的權(quán)限
<!-- 解鎖屏幕需要的權(quán)限 --> <uses-permission android:name="android.permission.DISABLE_KEYGUARD" /> <!-- 申請電源鎖需要的權(quán)限 --> <uses-permission android:name="android.permission.WAKE_LOCK" /> <!--震動權(quán)限--> <uses-permission android:name="android.permission.VIBRATE" />
五、心跳檢測和重連
由于很多不確定因素會導(dǎo)致websocket連接斷開,例如網(wǎng)絡(luò)斷開,所以需要保證websocket的連接穩(wěn)定性,這就需要加入心跳檢測和重連。
心跳檢測其實(shí)就是個(gè)定時(shí)器,每個(gè)一段時(shí)間檢測一次,如果連接斷開則重連,Java-WebSocket框架在目前最新版本中有兩個(gè)重連的方法,分別是reconnect()和reconnectBlocking(),這里同樣使用后者。
private static final long HEART_BEAT_RATE = 10 * 1000;//每隔10秒進(jìn)行一次對長連接的心跳檢測 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(); } //定時(shí)對長連接進(jìn)行心跳檢測 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(); }
然后在服務(wù)啟動時(shí)開啟心跳檢測
mHandler.postDelayed(heartBeatRunnable, HEART_BEAT_RATE);//開啟心跳檢測
我們打印一下日志,如圖所示
六、服務(wù)(Service)?;?/strong>
如果某些業(yè)務(wù)場景需要App?;?,例如利用這個(gè)websocket來做推送,那就需要我們的App后臺服務(wù)不被kill掉,當(dāng)然如果和手機(jī)廠商沒有合作,要保證服務(wù)一直不被殺死,這可能是所有Android開發(fā)者比較頭疼的一個(gè)事,這里我們只能盡可能的來保證Service的存活。
1、提高服務(wù)優(yōu)先級(前臺服務(wù))
前臺服務(wù)的優(yōu)先級比較高,它會在狀態(tài)欄顯示類似于通知的效果,可以盡量避免在內(nèi)存不足時(shí)被系統(tǒng)回收,前臺服務(wù)比較簡單就不細(xì)說了。有時(shí)候我們希望可以使用前臺服務(wù)但是又不希望在狀態(tài)欄有顯示,那就可以利用灰色保活的辦法,如下
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; } } //設(shè)置service為前臺服務(wù),提高優(yōu)先級 if (Build.VERSION.SDK_INT < 18) { //Android4.3以下 ,隱藏Notification上的圖標(biāo) startForeground(GRAY_SERVICE_ID, new Notification()); } else if(Build.VERSION.SDK_INT>18 && Build.VERSION.SDK_INT<25){ //Android4.3 - Android7.0,隱藏Notification上的圖標(biāo) Intent innerIntent = new Intent(this, GrayInnerService.class); startService(innerIntent); startForeground(GRAY_SERVICE_ID, new Notification()); }else{ //暫無解決方法 startForeground(GRAY_SERVICE_ID, new Notification()); }
AndroidManifest.xml中注冊這個(gè)服務(wù)
<service android:name=".im.JWebSocketClientService$GrayInnerService" android:enabled="true" android:exported="false" android:process=":gray"/>
這里其實(shí)就是開啟前臺服務(wù)并隱藏了notification,也就是再啟動一個(gè)service并共用一個(gè)通知欄,然后stop這個(gè)service使得通知欄消失。但是7.0以上版本會在狀態(tài)欄顯示“正在運(yùn)行”的通知,目前暫時(shí)沒有什么好的解決辦法。
2、修改Service的onStartCommand 方法返回值
@Override public int onStartCommand(Intent intent, int flags, int startId) { ... return START_STICKY; }
onStartCommand()返回一個(gè)整型值,用來描述系統(tǒng)在殺掉服務(wù)后是否要繼續(xù)啟動服務(wù),START_STICKY表示如果Service進(jìn)程被kill掉,系統(tǒng)會嘗試重新創(chuàng)建Service。
3、鎖屏喚醒
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(); } } }
獲取電源鎖,保持該服務(wù)在屏幕熄滅時(shí)仍然獲取CPU時(shí),讓其保持運(yùn)行。
上述內(nèi)容就是怎么在Android中利用WebSocket實(shí)現(xiàn)即時(shí)通訊,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。