Android WebSocket實現即時通訊功能


最近做這個功能,分享一下。即時通訊(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 (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);//開啟心跳檢測

 

我們打印一下日志,如圖所示

 
 

 

六、服務(Service)保活

如果某些業務場景需要App保活,例如利用這個websocket來做推送,那就需要我們的App后台服務不被kill掉,當然如果和手機廠商沒有合作,要保證服務一直不被殺死,這可能是所有Android開發者比較頭疼的一個事,這里我們只能盡可能的來保證Service的存活。

1、提高服務優先級(前台服務)
前台服務的優先級比較高,它會在狀態欄顯示類似於通知的效果,可以盡量避免在內存不足時被系統回收,前台服務比較簡單就不細說了。有時候我們希望可以使用前台服務但是又不希望在狀態欄有顯示,那就可以利用灰色保活的辦法,如下

  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以上版本會在狀態欄顯示“正在運行”的通知,目前暫時沒有什么好的解決辦法。

2、修改Service的onStartCommand 方法返回值

  @Override
  public int onStartCommand(Intent intent, int flags, int startId) {
      ...
      return START_STICKY;
  }

 

onStartCommand()返回一個整型值,用來描述系統在殺掉服務后是否要繼續啟動服務,START_STICKY表示如果Service進程被kill掉,系統會嘗試重新創建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();
          }
      }
  }

 

獲取電源鎖,保持該服務在屏幕熄滅時仍然獲取CPU時,讓其保持運行。

4、其他保活方式
服務保活還有許多其他方式,比如進程互拉、一像素保活、申請自啟權限、引導用戶設置白名單等,其實Android 7.0版本以后,目前沒有什么真正意義上的保活,但是做些處理,總比不做處理強。這篇文章重點是即時通訊,對於服務保活有需要的可以自行查閱更多資料,這里就不細說了。

 

最后附上這篇文章源碼地址,GitHub:https://github.com/yangxch/WebSocketClient,如果有幫助幫忙點個star吧。

原創不易,轉載請注明出處!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM