项目 基于 Kotlin 和 AndroidX 及 WebSocket 的 IM 项目 本文主要以一个小Demo来初步了解Kotlin编程与Java编程的差异
项目构建 聊天窗口构建 框架引入:BRVAH官网
1 2 implementation 'androidx.recyclerview:recyclerview:1.1.0-beta02' implementation 'com.github.CymChad:BaseRecyclerViewAdapterHelper:2.9.46'
new 对象 在Kotlin中,new Object();
省略为Object()
,也不需要分号全局变量 private lateinit var mContext: Context
全局变量应该用var来定义,其类型写在:之后 lateinit 修饰符:延迟初始化 lateinit 不能用来修饰基本数据类型,因为基本类型的属性在类加载后的准备阶段都会被初始化为默认值
lateinit 不能修饰val变量,只能修饰可变的属性
1 2 private lateinit val etMessage : AppCompatEditText
静态全局变量
1 2 3 4 5 6 7 companion object { const val TAG: String = ChatActivity::class .java .name }
符号 helper!!
意为:helper不做为空校验,如果为空则抛出异常
1 2 3 4 5 val mList: ArrayList<String>? = null Log.d(TAG, "ListSize = ${mList?.size} " ) Log日志:com.yooking.socket.ChatActivity: ListSize = null
构建javabean
1 2 3 class ChatData (private val type: Int ) : MultiItemEntity { var name: String? = "" }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 class ChatData extends MultiItemEntity { private int type; private String name = "" ; public ChatData (int type) { this .type = type; } public void setName (String name) { this .name = name; } public String getName () { return this .name; } }
WebSocketLib构建 框架引入:OkHttp-GithubPage
1 2 3 api 'com.squareup.okhttp3:okhttp:4.0.1' api 'com.squareup.okhttp3:logging-interceptor:4.0.1'
匿名内部类 在kotlin中,匿名内部类和java中的差别不大
1 2 3 4 5 6 7 private var handler: Handlerinit { handler = Handler { send(heartMessage) it.target.sendEmptyMessageDelayed(WHAT_HEART, heartTime) } }
1 2 3 4 5 6 7 8 9 handler = new Handler(){ @override public void handlerMessage (Message msg) { super .handleMessage(msg); send(heartMessage); sendEmptyMessageDelayed(WHAT_HEART, heartTime); } }
静态内部类 由于handler调用外部方法容易造成内存泄漏,所以,静态内部类了解一下:
1 2 3 4 5 6 7 8 9 10 11 companion object { private class WithoutLeakHandler (wsu:WebSocketUtils):Handler(){ private val mWsu:WeakReference<WebSocketUtils> = WeakReference(wsu) override fun handleMessage (msg: Message ?) { super .handleMessage(msg) val webSocketUtils = mWsu.get ()!! webSocketUtils.send(webSocketUtils.heartMessage) msg!!.target.sendEmptyMessageDelayed(WHAT_HEART, webSocketUtils.heartTime) } } }
具体实现请见Demo 聊天代码:Demo