最近作这个功能,分享一下。即时通信(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吧。
原创不易,转载请注明出处!