如何使用Kotlin构建具有在线状态的Android Messenger应用
by Neo Ighodaro
由新Ighodaro
When building a chat application, it is essential to have an online presence feature. It is essential because your users will like to know when their friends are online, and are more likely to respond to their messages in real time.
構建聊天應用程序時,必須具有在線狀態(tài)功能。 這很重要,因為您的用戶希望知道他們的朋友何時在線,并且更有可能實時響應他們的消息。
In this article, we will be building a messenger app with online presence using Pusher Channels, Kotlin, and Node.js.
在本文中,我們將使用Pusher Channels,Kotlin和Node.js構建具有在線狀態(tài)的Messenger應用程序。
Here is a demo of what we will build:
這是我們將構建的演示:
先決條件 (Prerequisites)
To follow along you need the following requirements:
要遵循,您需要滿足以下要求:
A Pusher Channel app. You can create one here.
Pusher Channel應用。 您可以在此處創(chuàng)建一個。
Android Studio installed on your machine. You can check here for the latest stable version. A minimum of version 3.0 is recommended.
您的計算機上安裝了Android Studio。 您可以在此處查看最新的穩(wěn)定版本。 建議最低版本為3.0。
- Basic knowledge of Android development and the Android Studio IDE. Android開發(fā)和Android Studio IDE的基礎知識。
Basic knowledge of Kotlin. Here are the official docs.
Kotlin的基礎知識。 這是官方文檔 。
Node.js and NPM (Node Package Manager) installed on your machine. Download here.
您的計算機上安裝了Node.js和NPM(節(jié)點程序包管理器)。 在這里下載。
Mongo DB installed on your machine. You can install it following the instructions here.
您的計算機上安裝了Mongo DB。 您可以按照此處的說明進行安裝。
Some familiarity with Android development is also required.
還需要對Android開發(fā)有所了解。
構建后端服務器 (Building the backend server)
Our server will be built using Node.js. To start, create a new project directory:
我們的服務器將使用Node.js構建。 首先,創(chuàng)建一個新的項目目錄:
$ mkdir backend-serverNext, create a new index.js file inside the project directory and paste the following code:
接下來,在項目目錄中創(chuàng)建一個新的index.js文件,并粘貼以下代碼:
// File: ./index.js var express = require('express'); var bodyParser = require('body-parser'); const mongoose = require('mongoose'); var Pusher = require('pusher');var app = express();app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false }));var pusher = new Pusher({ appId: 'PUSHER_APP_ID', key: 'PUSHER_APP_KEY', secret: 'PUSHER_APP_SECRET', cluster: 'PUSHER_APP_CLUSTER' });mongoose.connect('mongodb://127.0.0.1/db');const Schema = mongoose.Schema; const userSchema = new Schema({ name: { type: String, required: true, }, count: {type: Number} });var User = mongoose.model('User', userSchema); userSchema.pre('save', function(next) { if (this.isNew) { User.count().then(res => { this.count = res; // Increment count next(); }); } else { next(); } });module.exports = User;var currentUser;/* ================================= We will add our endpoints here!!! ================================= */var port = process.env.PORT || 5000;app.listen(port);In the snippet above, we initialized Pusher, Express, and MongoDB. We are using Moongose to connect to our MongoDB instance.
在上面的代碼段中,我們初始化了Pusher,Express和MongoDB。 我們正在使用Moongose連接到我們的MongoDB實例。
Replace the PUSHER_APP_* keys with the ones on your Pusher dashboard.
將PUSHER_APP_*鍵替換為Pusher儀表板上的鍵。
Now let’s add our endpoints. The first endpoint we will add will be to log a user in. Paste the code below in your index.js file below the currentUser declaration:
現(xiàn)在讓我們添加端點。 我們將添加的第一個端點將是登錄用戶。將下面的代碼粘貼到index.js文件中的currentUser聲明下方:
// File: ./index.js// [...]app.post('/login', (req,res) => { User.findOne({name: req.body.name}, (err, user) => { if (err) { res.send("Error connecting to database"); }// User exists if (user) { currentUser = user; return res.status(200).send(user) }let newuser = new User({name: req.body.name});newuser.save(function(err) { if (err) throw err; });currentUser = newuser; res.status(200).send(newuser) }); })// [...]This endpoint receives a username with the request, and either creates a new user or returns the data of the existing user.
該端點接收帶有請求的username ,并創(chuàng)建一個新用戶或返回現(xiàn)有用戶的數(shù)據(jù)。
Let’s add the next endpoint below the one above:
讓我們在上面的端點下面添加下一個端點:
// File: ./index.js// [...]app.get('/users', (req,res) => { User.find({}, (err, users) => { if (err) throw err; res.send(users); }); })// [...]This second endpoint fetches all the users from the database and returns them.
第二個端點從數(shù)據(jù)庫中獲取所有用戶并返回它們。
Since we will be using a Pusher presence channel, we need an endpoint to authenticate the user. In the same file, paste this code below the endpoint above:
由于我們將使用Pusher狀態(tài)通道,因此我們需要一個端點來驗證用戶身份。 在同一文件中,將此代碼粘貼到上方端點以下:
// File: ./index.js// [...]app.post('/pusher/auth/presence', (req, res) => { let socketId = req.body.socket_id; let channel = req.body.channel_name;let presenceData = { user_id: currentUser._id, user_info: {count: currentUser.count, name: currentUser.name} };let auth = pusher.authenticate(socketId, channel, presenceData);res.send(auth); });// [...]Since we are going to be using private channels, we need an endpoint for authentication. Add the following endpoint below the endpoint above:
由于我們將使用專用通道,因此我們需要一個端點進行身份驗證。 在上方端點下方添加以下端點:
// File: ./index.js// [...]app.post('/pusher/auth/private', (req, res) => { res.send(pusher.authenticate(req.body.socket_id, req.body.channel_name)); });// [...]Finally, the last endpoint will be to trigger an event `new-message` to a channel. Add the endpoint below the last one:// File: ./index.js// [...]app.post('/send-message', (req, res) => { let payload = {message: req.body.message, sender_id: req.body.sender_id} pusher.trigger(req.body.channel_name, 'new-message', payload); res.send(200); });// [...]After adding all the endpoints, install the necessary npm packages by running this command:
添加所有端點之后,通過運行以下命令來安裝必要的npm軟件包:
$ npm install express body-parser mongoose pusherBefore you run your application, make sure MongoDB is running already using this command:
在運行應用程序之前,請使用以下命令確保MongoDB已經(jīng)在運行:
$ mongod --dbpath C:\MongoDB\data\db # Windows $ mongod --dbpath=/path/to/db/directory # Mac or LinuxNow you can run your application using the command below:
現(xiàn)在,您可以使用以下命令運行您的應用程序:
$ node index.jsYour app will be available here: http://localhost:5000.
您的應用程序將在此處提供: http:// localhost:5000 。
構建我們的Android應用程序 (Building our Android application)
Create your Android project. In the wizard, enter your project name — let’s say MessengerApp.
創(chuàng)建您的Android項目。 在向導中,輸入您的項目名稱-假設為MessengerApp。
Next, enter your package name. You can use a minimum SDK of 19 then choose an Empty Activity.
接下來,輸入您的包裹名稱。 您可以使用最低19的SDK,然后選擇空活動 。
On the next page, change the Activity Name to LoginActivity. After this, Android Studio will build your project for you.
在下一頁上,將“ 活動名稱”更改為LoginActivity 。 之后,Android Studio將為您構建項目。
Now that we have the project, let’s add the required dependencies for our app. Open your app module build.gradle file and add these:
現(xiàn)在我們有了項目,讓我們?yōu)閼贸绦蛱砑颖匦璧囊蕾図棥?打開您的應用程序模塊build.gradle文件并添加以下內容:
// File ../app/build.gradle dependencies { // [...]implementation 'com.android.support:design:28+' implementation 'com.pusher:pusher-java-client:1.6.0' implementation "com.squareup.retrofit2:retrofit:2.4.0" implementation "com.squareup.retrofit2:converter-scalars:2.4.0" implementation 'com.squareup.retrofit2:converter-gson:2.3.0' }Notably, we added the dependencies for Retrofit and Pusher. Retrofit is an HTTP client library used for network calls. We added the design library dependency too as we want to use some classes from it. Sync your gradle files to pull in the dependencies.
值得注意的是,我們添加了Retrofit和Pusher的依賴項。 Retrofit是用于網(wǎng)絡調用的HTTP客戶端庫。 我們還添加了設計庫依賴項,因為我們想使用其中的一些類。 同步gradle文件以獲取依賴項。
Next, let’s prepare our app to make network calls. Retrofit requires an interface to know the endpoints to be accessed.
接下來,讓我們準備應用程序以進行網(wǎng)絡通話。 改造需要一個接口來知道要訪問的端點。
Create a new interface named ApiService and paste this:
創(chuàng)建一個名為ApiService的新接口,并將其粘貼:
// File: ./app/src/main/java/com/example/messengerapp/ApiService.kt import okhttp3.RequestBody import retrofit2.Call import retrofit2.http.Body import retrofit2.http.GET import retrofit2.http.POSTinterface ApiService {@POST("/login") fun login(@Body body:RequestBody): Call<UserModel>@POST("/send-message") fun sendMessage(@Body body:RequestBody): Call<String>@GET("/users") fun getUsers(): Call<List<UserModel>> }Here, we have declared three endpoints. They are for logging in, sending messages, and fetching users.
在這里,我們聲明了三個端點。 它們用于登錄,發(fā)送消息和獲取用戶。
In some of our responses, we return Call<UserModel>. Let’s create the UserModel. Create a new class called UserModel and paste the following:
在某些響應中,我們返回Call<UserMod el>。 讓我們創(chuàng)建e the Use rModel。 創(chuàng)建一個新的類并alled Use rModel并粘貼以下內容:
// File: ./app/src/main/java/com/example/messengerapp/UserModel.kt import com.google.gson.annotations.Expose import com.google.gson.annotations.SerializedNamedata class UserModel(@SerializedName("_id") @Expose var id: String, @SerializedName("name") @Expose var name: String, @SerializedName("count") @Expose var count: Int, var online:Boolean = false)Above, we used a data class so that some other functions required for model classes such as toString and hashCode are added to the class by default.
上面,我們使用了一個數(shù)據(jù)類,以便默認情況下將模型類所需的其他一些功能(例如toString和hashCode添加到該類中。
We are expecting only the values for the id and name from the server. We added the online property so we can update later on.
我們期望服務器僅提供id和name的值。 我們添加了online媒體資源,以便稍后進行更新。
Next, create a new class named RetrofitInstance and paste in the following code:
接下來,創(chuàng)建一個名為RetrofitInstance的新類,并粘貼以下代碼:
// File: ./app/src/main/java/com/example/messengerapp/RetrofitInstance.kt import okhttp3.OkHttpClient import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import retrofit2.converter.scalars.ScalarsConverterFactoryclass RetrofitInstance {companion object { val retrofit: ApiService by lazy { val httpClient = OkHttpClient.Builder() val builder = Retrofit.Builder() .baseUrl("http://10.0.2.2:5000/") .addConverterFactory(ScalarsConverterFactory.create()) .addConverterFactory(GsonConverterFactory.create())val retrofit = builder .client(httpClient.build()) .build() retrofit.create(ApiService::class.java) } } }RetrofitInstance contains a class variable called retrofit. It provides us with an instance for Retrofit that we will reference in more than one class.
RetrofitInstance含有一種稱為類變量retrofit 。 它為我們提供了Retrofit的實例,我們將在多個類中進行引用。
Finally, to request for the internet access permission update the AndroidManifest.xml file like so:
最后,要請求互聯(lián)網(wǎng)訪問權限,請更新AndroidManifest.xml文件,如下所示:
// File: ./app/src/main/ApiService.kt <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.messengerapp"><uses-permission android:name="android.permission.INTERNET" /> [...]</manifest>Now we can make requests using Retrofit.
現(xiàn)在我們可以使用Retrofit發(fā)出請求。
The next feature we will implement is login. Open the already created LoginActivity layout file activity_login.xml file and paste this:
我們將實現(xiàn)的下一個功能是登錄。 打開已經(jīng)創(chuàng)建的LoginActivity布局文件activity_login.xml文件,并將其粘貼:
// File: ./app/src/main/res/layout/activity_login.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="20dp" tools:context=".LoginActivity"><EditText android:id="@+id/editTextUsername" android:layout_width="match_parent" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /><Button android:id="@+id/loginButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="Login" app:layout_constraintTop_toBottomOf="@+id/editTextUsername" /></android.support.constraint.ConstraintLayout>This layout contains an input field to take the username, and a button to make a login request.
此布局包含一個使用用戶名的輸入字段,以及一個進行登錄請求的按鈕。
Next, open the LoginActivity.Kt file and paste in this:
接下來,打開LoginActivity.Kt文件并將其粘貼在其中:
// File: ./app/src/main/java/com/example/messengerapp/LoginActivity.kt import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.util.Log import kotlinx.android.synthetic.main.activity_login.* import okhttp3.MediaType import okhttp3.RequestBody import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Responseclass LoginActivity : AppCompatActivity() {override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) loginButton.setOnClickListener { if (editTextUsername.text.isNotEmpty()) { loginFunction(editTextUsername.text.toString()) } } }private fun loginFunction(name:String) { val jsonObject = JSONObject() jsonObject.put("name", name)val jsonBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), jsonObject.toString() )RetrofitInstance.retrofit.login(jsonBody).enqueue(object:Callback<UserModel> { override fun onFailure(call: Call<UserModel>?, t: Throwable?) { Log.i("LoginActivity",t!!.localizedMessage) }override fun onResponse(call: Call<UserModel>?, response: Response<UserModel>?) { if (response!!.code() == 200) { Singleton.getInstance().currentUser = response.body()!! startActivity(Intent(this@LoginActivity,ContactListActivity::class.java)) finish() } } }) } }In the LoginActivity.Kt file, we set up a listener for our login button so that, when it is clicked, we can send the text to the server for authentication. We also stored the logged in user in a singleton class so that we can access the user’s details later.
在LoginActivity.Kt文件中,我們?yōu)榈卿洶粹o設置了一個偵聽器,以便單擊該按鈕時,可以將文本發(fā)送到服務器進行身份驗證。 我們還將登錄用戶存儲在單例類中,以便以后可以訪問該用戶的詳細信息。
Create a new class called Singleton and paste in this:
創(chuàng)建一個名為Singleton的新類,并粘貼以下內容:
// File: ./app/src/main/java/com/example/messengerapp/RetrofitInstance.kt class Singleton { companion object { private val ourInstance = Singleton() fun getInstance(): Singleton { return ourInstance } } lateinit var currentUser: UserModel }Singletongives us access to the currentUser, which is the logged in user.
Singleton使我們可以訪問currentUser ,即登錄用戶。
Next, let’s create a new activity named ContactListActivity. For now, leave the class empty and open the corresponding layout file named activity_contact_list , and paste in the following:
接下來,讓我們創(chuàng)建一個名為ContactListActivity的新活動。 現(xiàn)在,將類留空,然后打開名為activity_contact_list的相應布局文件,然后粘貼以下內容:
// File: ./app/src/main/res/layout/activity_contact_list.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ContactListActivity"><android.support.v7.widget.RecyclerView android:layout_width="match_parent" android:id="@+id/recyclerViewUserList" android:layout_height="match_parent"/></android.support.constraint.ConstraintLayout>The layout contains a recycler view, which will give us all the lists of our contacts fetched from the database. Since we are displaying items in a list, we will need an adapter class to manage how items are inflated to the layout.
該布局包含一個回收站視圖,該視圖將為我們提供從數(shù)據(jù)庫中獲取的所有聯(lián)系人列表。 由于我們在列表中顯示項目,因此我們將需要一個適配器類來管理項目如何放大到布局。
Create a new class named ContactRecyclerAdapter and paste in this:
創(chuàng)建一個名為ContactRecyclerAdapter的新類,并粘貼以下內容:
// File: ./app/src/main/java/com/example/messengerapp/ContactRecyclerAdapter.kt import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.TextView import java.util.*class ContactRecyclerAdapter(private var list: ArrayList<UserModel>, private var listener: UserClickListener) : RecyclerView.Adapter<ContactRecyclerAdapter.ViewHolder>() {override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.user_list_row, parent, false)) }override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(list[position])override fun getItemCount(): Int = list.sizefun showUserOnline(updatedUser: UserModel) { list.forEachIndexed { index, element -> if (updatedUser.id == element.id) { updatedUser.online = true list[index] = updatedUser notifyItemChanged(index) }} }fun showUserOffline(updatedUser: UserModel) { list.forEachIndexed { index, element -> if (updatedUser.id == element.id) { updatedUser.online = false list[index] = updatedUser notifyItemChanged(index) } } }fun add(user: UserModel) { list.add(user) notifyDataSetChanged() }inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val nameTextView: TextView = itemView.findViewById(R.id.usernameTextView) private val presenceImageView: ImageView = itemView.findViewById(R.id.presenceImageView)fun bind(currentValue: UserModel) = with(itemView) { this.setOnClickListener { listener.onUserClicked(currentValue) } nameTextView.text = currentValue.name if (currentValue.online){ presenceImageView.setImageDrawable(this.context.resources.getDrawable(R.drawable.presence_icon_online)) } else { presenceImageView.setImageDrawable(this.context.resources.getDrawable(R.drawable.presence_icon))}} }interface UserClickListener { fun onUserClicked(user: UserModel) } }This adapter has some overridden methods and some custom methods.
此適配器具有一些替代方法和一些自定義方法。
The onCreateViewHolder inflates how each row will look like. onBindViewHolder binds the data to each item by calling the bind method in the inner ViewHolder class. The getItemCount gives the size of the list.
onCreateViewHolder夸大每一行的外觀。 onBindViewHolder通過調用內部ViewHolder類中的bind方法將數(shù)據(jù)綁定到每個項目。 getItemCount給出列表的大小。
For our custom methods, showUserOffline updates the user and shows when they are offline. While showUserOnline does the opposite. Finally, we have the add method, which adds a new contact to the list and refreshes it.
對于我們的自定義方法, showUserOffline更新用戶并顯示他們何時離線。 而showUserOnline則相反。 最后,我們有add方法,它將新聯(lián)系人添加到列表中并刷新它。
In the adapter class above, we used a new layout named user_list_row. Create a new layout user_list_rowand paste this:
在上面的適配器類中,我們使用了一個名為user_list_row的新布局。 創(chuàng)建一個新的布局user_list_row并將其粘貼:
// File: ./app/src/main/res/layout/user_list_row.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout android:orientation="horizontal" xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="20dp" android:gravity="center" tools:context=".LoginActivity"><ImageView android:id="@+id/presenceImageView" android:layout_width="15dp" android:layout_height="15dp" app:srcCompat="@drawable/presence_icon" /><TextView android:layout_width="match_parent" android:layout_height="wrap_content" tools:text="Neo" android:textSize="20sp" android:layout_marginStart="10dp" android:id="@+id/usernameTextView" app:layout_constraintTop_toBottomOf="@+id/editTextUsername" /></LinearLayout>This layout is the visual representation of how each item on the layout will look like. The layout has an image view that shows the users online status. The layout also has a textview that shows the name of the contact beside the icon. The icons are vector drawables. Let’s create the files.
此布局是布局上每個項目的外觀的直觀表示。 布局具有一個圖像視圖,顯示用戶的在線狀態(tài)。 該布局還具有一個文本視圖,該視圖在圖標旁邊顯示聯(lián)系人的姓名。 圖標是矢量可繪制對象。 讓我們創(chuàng)建文件。
Create a new drawable named presence_icon_online and paste in this:
創(chuàng)建一個新的名為繪制presence_icon_online和粘貼代碼:
// File: ./app/src/main/res/drawable/presence_icon_online.xml <vector android:height="24dp" android:tint="#3FFC3C" android:viewportHeight="24.0" android:viewportWidth="24.0" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z"/> </vector>Create another drawable named presence_icon and paste in this:
創(chuàng)建另一個名為繪制presence_icon和粘貼代碼:
// File: ./app/src/main/res/drawable/presence_icon.xml <vector android:height="24dp" android:tint="#C0C0C6" android:viewportHeight="24.0" android:viewportWidth="24.0" android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M12,2C6.48,2 2,6.48 2,12s4.48,10 10,10 10,-4.48 10,-10S17.52,2 12,2z"/> </vector>Next, open the ContactListActivity class and paste in this:
接下來,打開ContactListActivity類并粘貼:
// File: ./app/src/main/java/com/example/messengerapp/ContactListActivity.kt import android.content.Intent import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.util.Log import com.pusher.client.Pusher import com.pusher.client.PusherOptions import com.pusher.client.channel.PresenceChannelEventListener import com.pusher.client.channel.User import com.pusher.client.util.HttpAuthorizer import kotlinx.android.synthetic.main.activity_contact_list.* import retrofit2.Call import retrofit2.Callback import retrofit2.Responseclass ContactListActivity : AppCompatActivity(), ContactRecyclerAdapter.UserClickListener {private val mAdapter = ContactRecyclerAdapter(ArrayList(), this)override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_contact_list) setupRecyclerView() fetchUsers() subscribeToChannel() }}In ContactListActivity, we initialized the ContactRecyclerAdapter, then called three functions in the onCreate method. Let’s create these new functions.
在ContactListActivity ,我們初始化了ContactRecyclerAdapter ,然后在onCreate方法中調用了三個函數(shù)。 讓我們創(chuàng)建這些新功能。
In the same class, add the following methods:
在同一類中,添加以下方法:
private fun setupRecyclerView() { with(recyclerViewUserList) { layoutManager = LinearLayoutManager(this@ContactListActivity) adapter = mAdapter } }private fun fetchUsers() { RetrofitInstance.retrofit.getUsers().enqueue(object : Callback<List<UserModel>> { override fun onFailure(call: Call<List<UserModel>>?, t: Throwable?) {} override fun onResponse(call: Call<List<UserModel>>?, response: Response<List<UserModel>>?) { for (user in response!!.body()!!) { if (user.id != Singleton.getInstance().currentUser.id) { mAdapter.add(user) } } } }) }private fun subscribeToChannel() {val authorizer = HttpAuthorizer("http://10.0.2.2:5000/pusher/auth/presence") val options = PusherOptions().setAuthorizer(authorizer) options.setCluster("PUSHER_APP_CLUSTER")val pusher = Pusher("PUSHER_APP_KEY", options) pusher.connect()pusher.subscribePresence("presence-channel", object : PresenceChannelEventListener { override fun onUsersInformationReceived(p0: String?, users: MutableSet<User>?) { for (user in users!!) { if (user.id!=Singleton.getInstance().currentUser.id){ runOnUiThread { mAdapter.showUserOnline(user.toUserModel()) } } } }override fun onEvent(p0: String?, p1: String?, p2: String?) {} override fun onAuthenticationFailure(p0: String?, p1: Exception?) {} override fun onSubscriptionSucceeded(p0: String?) {}override fun userSubscribed(channelName: String, user: User) { runOnUiThread { mAdapter.showUserOnline(user.toUserModel()) } }override fun userUnsubscribed(channelName: String, user: User) { runOnUiThread { mAdapter.showUserOffline(user.toUserModel()) } } }) }override fun onUserClicked(user: UserModel) { val intent = Intent(this, ChatRoom::class.java) intent.putExtra(ChatRoom.EXTRA_ID,user.id) intent.putExtra(ChatRoom.EXTRA_NAME,user.name) intent.putExtra(ChatRoom.EXTRA_COUNT,user.count) startActivity(intent) }Replace the PUSHER_APP_* keys with the values on your dashboard.
將PUSHER_APP_*鍵替換為儀表板上的值。
setupRecyclerView assigns a layout manager and an adapter to the recycler view. For a recycler view to work, you need these two things.
setupRecyclerView將布局管理器和適配器分配給回收者視圖。 為了使回收器視圖正常工作,您需要這兩件事。
fetchUsers fetches all the users from the server and displays on the list. It exempts the current user logged in.
fetchUsers從服務器獲取所有用戶,并顯示在列表中。 它免除了當前登錄的用戶。
subcribeToChannel subscribes to a presence channel. When you subscribe to one, the onUsersInformationReceived gives you all the users subscribed to the channel including the current user. So, in that callback, we call the showUserOnline method in the adapter class so that the icon beside the user can be changed to signify that the user is online.
subcribeToChannel訂閱狀態(tài)頻道。 當您訂閱一個頻道時, onUsersInformationReceived會為您訂閱該頻道的所有用戶,包括當前用戶。 因此,在該回調中,我們在適配器類中調用showUserOnline方法,以便可以更改用戶旁邊的圖標以表示該用戶在線。
onUserClicked is called when a contact is selected. We pass the details of the user to the next activity called ChatRoom.
選擇聯(lián)系人時,將調用onUserClicked 。 我們將用戶的詳細信息傳遞給下一個稱為ChatRoom活動。
In the previous snippet, we used an extension function to transform the User object we receive from Pusher to our own UserModel object. Let’s define this extension.
在上一片段中,我們使用了擴展功能將從Pusher接收到的User對象轉換為我們自己的UserModel對象。 讓我們定義這個擴展。
Create a new class called Utils and paste this:
創(chuàng)建一個名為Utils的新類,并將其粘貼:
// File: ./app/src/main/java/com/example/messengerapp/Utils.kt import com.pusher.client.channel.User import org.json.JSONObjectfun User.toUserModel():UserModel{ val jsonObject = JSONObject(this.info) val name = jsonObject.getString("name") val numb = jsonObject.getInt("count") return UserModel(this.id, name, numb) }Now, since we referenced a ChatRoom activity earlier in the onUserClicked method, let’s create it.
現(xiàn)在,由于我們之前在onUserClicked方法中引用了ChatRoom活動,因此讓我們創(chuàng)建它。
Create a new activity called ChatRoom. The activity comes with a layout file activity_chat_room. Paste this into the layout file:
創(chuàng)建一個名為ChatRoom的新活動。 該活動帶有布局文件activity_chat_room 。 將此粘貼到布局文件中:
// File: ./app/src/main/res/layout/activity_chat_room.xml <?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ChatRoom"><android.support.v7.widget.RecyclerView android:id="@+id/recyclerViewChat" android:layout_width="match_parent" android:layout_height="match_parent" /><EditText android:id="@+id/editText" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="16dp" android:hint="Enter a message" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toStartOf="@+id/sendButton" app:layout_constraintStart_toStartOf="parent" /><android.support.design.widget.FloatingActionButton android:id="@+id/sendButton" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="end|bottom" android:layout_margin="16dp" android:src="@android:drawable/ic_menu_send" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" /></android.support.constraint.ConstraintLayout>The layout above contains a recycler view for the chat messages, an edit text to collect new messages, and a floating action button to send the message.
上面的布局包含聊天消息的回收者視圖,用于收集新消息的編輯文本以及用于發(fā)送消息的浮動操作按鈕。
Next, create a new class called ChatRoomAdapter and paste in the following:
接下來,創(chuàng)建一個名為ChatRoomAdapter的新類,并粘貼以下內容:
// File: ./app/src/main/java/com/example/messengerapp/ChatRoomAdapter.kt import android.support.v7.widget.CardView import android.support.v7.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.RelativeLayout import android.widget.TextView import java.util.*class ChatRoomAdapter (private var list: ArrayList<MessageModel>) : RecyclerView.Adapter<ChatRoomAdapter.ViewHolder>() {override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { return ViewHolder(LayoutInflater.from(parent.context) .inflate(R.layout.chat_item, parent, false)) }override fun onBindViewHolder(holder: ViewHolder, position: Int) = holder.bind(list[position])override fun getItemCount(): Int = list.sizefun add(message: MessageModel) { list.add(message) notifyDataSetChanged() }inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) { private val messageTextView: TextView = itemView.findViewById(R.id.text) private val cardView: CardView = itemView.findViewById(R.id.cardView)fun bind(message: MessageModel) = with(itemView) { messageTextView.text = message.message val params = cardView.layoutParams as RelativeLayout.LayoutParams if (message.senderId==Singleton.getInstance().currentUser.id) { params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT) } } } }This adapter works in a similar fashion as the one we created earlier. One difference, though, is that the show online and offline methods are not needed here.
該適配器的工作方式與我們之前創(chuàng)建的適配器類似。 但是,一個區(qū)別是,此處不需要在線和離線顯示方法。
Next, create another class — named MessageMode— and paste in this:
接下來,創(chuàng)建另一個類-名為MessageMode并粘貼以下內容:
// File: ./app/src/main/java/com/example/messengerapp/MessageModel.kt data class MessageModel(val message: String, val senderId: String)The chat_item layout used in the onCreateViewHolder method of the adapter class represents how each layout will look like. Create a new layout called chat_item and paste in this:
適配器類的onCreateViewHolder方法中使用的chat_item布局表示每種布局的外觀。 創(chuàng)建一個名為chat_item的新布局,并粘貼以下內容:
// File: ./app/src/main/res/layout/chat_item.xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_margin="16dp" android:orientation="vertical"><android.support.v7.widget.CardView android:id="@+id/cardView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="start" app:cardCornerRadius="8dp" app:cardUseCompatPadding="true"><LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="start" android:orientation="vertical" android:padding="8dp"><TextView android:id="@+id/text" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical|start" android:layout_marginBottom="4dp" android:textStyle="bold" /></LinearLayout></android.support.v7.widget.CardView></RelativeLayout>更新ChatRoom類 (Updating the ChatRoom class)
Finally, open the ChatRoom activity class and paste in this:
最后,打開ChatRoom活動類并粘貼:
// File: ./app/src/main/java/com/example/messengerapp/ChatRoom.kt import android.app.Activity import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.util.Log import android.view.View import android.view.inputmethod.InputMethodManager import com.pusher.client.Pusher import com.pusher.client.PusherOptions import com.pusher.client.channel.PrivateChannelEventListener import com.pusher.client.util.HttpAuthorizer import kotlinx.android.synthetic.main.activity_chat_room.* import okhttp3.MediaType import okhttp3.RequestBody import org.json.JSONObject import retrofit2.Call import retrofit2.Callback import retrofit2.Response import java.lang.Exception import java.util.*class ChatRoom : AppCompatActivity() {companion object { const val EXTRA_ID = "id" const val EXTRA_NAME = "name" const val EXTRA_COUNT = "numb" }private lateinit var contactName: String private lateinit var contactId: String private var contactNumb: Int = -1 lateinit var nameOfChannel: String val mAdapter = ChatRoomAdapter(ArrayList())override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_chat_room) fetchExtras() setupRecyclerView() subscribeToChannel() setupClickListener() } }In this file, we declared constants used to send data to the activity through intents. We also initialized variables we will use later, like the adapter and the contact details. We then called some additional methods in the onCreatemethod. Let’s add them to theChatRoom class.
在此文件中,我們聲明了用于通過意圖將數(shù)據(jù)發(fā)送到活動的常量。 我們還初始化了稍后將使用的變量,例如適配器和聯(lián)系方式。 然后,我們在onCreate方法中調用了一些其他方法。 讓我們將它們添加到ChatRoom類中。
Add the fetchExtras method defined below to the class. The method gets the extras sent from the chatroom activity.
將下面定義的fetchExtras方法添加到該類中。 該方法獲取聊天室活動發(fā)送的臨時演員。
private fun fetchExtras() { contactName = intent.extras.getString(ChatRoom.EXTRA_NAME) contactId = intent.extras.getString(ChatRoom.EXTRA_ID) contactNumb = intent.extras.getInt(ChatRoom.EXTRA_COUNT) }The next method is setupRecyclerView . This initializes the recycler view with an adapter and a layout manager. Paste this function into the same class as before:
下一個方法是setupRecyclerView 。 這將使用適配器和布局管理器初始化回收器視圖。 將此函數(shù)粘貼到與以前相同的類中:
private fun setupRecyclerView() { with(recyclerViewChat) { layoutManager = LinearLayoutManager(this@ChatRoom) adapter = mAdapter } }The next method is subscribeToChannel . This method subscribes the user to a private channel with the selected contact. Paste the following code into the same class as before:
下一個方法是subscribeToChannel 。 此方法使用所選聯(lián)系人將用戶預訂到私人頻道。 將以下代碼粘貼到與以前相同的類中:
private fun subscribeToChannel() { val authorizer = HttpAuthorizer("http://10.0.2.2:5000/pusher/auth/private") val options = PusherOptions().setAuthorizer(authorizer) options.setCluster("PUSHER_APP_CLUSTER")val pusher = Pusher("PUSHER_APP_KEY", options) pusher.connect()nameOfChannel = if (Singleton.getInstance().currentUser.count > contactNumb) { "private-" + Singleton.getInstance().currentUser.id + "-" + contactId } else { "private-" + contactId + "-" + Singleton.getInstance().currentUser.id }Log.i("ChatRoom", nameOfChannel)pusher.subscribePrivate(nameOfChannel, object : PrivateChannelEventListener { override fun onEvent(channelName: String?, eventName: String?, data: String?) { val obj = JSONObject(data) val messageModel = MessageModel(obj.getString("message"), obj.getString("sender_id"))runOnUiThread { mAdapter.add(messageModel) } }override fun onAuthenticationFailure(p0: String?, p1: Exception?) {} override fun onSubscriptionSucceeded(p0: String?) {} }, "new-message") }Replace the PUSHER_APP_* keys with the values on your dashboard.
將PUSHER_APP_*鍵替換為儀表板上的值。
The code above allows a user to subscribe to a private channel. A private channel requires authorization like the presence channel. However, it does not expose a callback that is triggered when other users subscribe.
上面的代碼允許用戶訂閱私人頻道。 專用頻道需要與狀態(tài)頻道一樣的授權。 但是,它不會公開其他用戶訂閱時觸發(fā)的回調。
Next method to be added is setupClickListener. Paste the method into the same class as before:
下一個要添加的方法是setupClickListener 。 將方法粘貼到與以前相同的類中:
private fun setupClickListener() { sendButton.setOnClickListener{ if (editText.text.isNotEmpty()) { val jsonObject = JSONObject() jsonObject.put("message",editText.text.toString()) jsonObject.put("channel_name",nameOfChannel) jsonObject.put("sender_id",Singleton.getInstance().currentUser.id)val jsonBody = RequestBody.create( MediaType.parse("application/json; charset=utf-8"), jsonObject.toString() )RetrofitInstance.retrofit.sendMessage(jsonBody).enqueue(object: Callback<String>{ override fun onFailure(call: Call<String>?, t: Throwable?) {} override fun onResponse(call: Call<String>?, response: Response<String>?) {} })editText.text.clear() hideKeyBoard() }} }The method above assigns a click listener to the floating action button to send the message to the server. After the message is sent, we clear the text view and hide the keyboard.
上面的方法將單擊偵聽器分配給浮動操作按鈕,以將消息發(fā)送到服務器。 發(fā)送消息后,我們清除文本視圖并隱藏鍵盤。
Add a method to the same class for hiding the keyboard like this:
將方法添加到同一類中以隱藏鍵盤,如下所示:
private fun hideKeyBoard() { val imm = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager var view = currentFocusif (view == null) { view = View(this) }imm.hideSoftInputFromWindow(view.windowToken, 0) }That’s all for the application. Now you can run your application in Android Studio and you should see the application in action.
這就是應用程序的全部內容。 現(xiàn)在,您可以在Android Studio中運行您的應用程序,并且您應該會看到該應用程序的運行情況。
Make sure the Node.js API we built earlier is running before running the Android application.
在運行Android應用程序之前,請確保我們先前構建的Node.js API正在運行。
結論 (Conclusion)
In this article, you have been introduced to some Pusher capabilities such as the private and presence channel.
在本文中,向您介紹了一些Pusher功能,例如專用和狀態(tài)通道。
We learned how to authenticate our users for the various channels.
我們學習了如何驗證各種渠道的用戶身份。
We used these channels to implement a private chat between two persons and an online notification for a contact.
我們使用這些渠道來實現(xiàn)兩個人之間的私人聊天以及聯(lián)系人的在線通知。
The source code to the application built in this article is available on GitHub.
GitHub上提供了本文構建的應用程序的源代碼。
This post first appeared on the Pusher Blog.
這篇文章首先出現(xiàn)在Pusher Blog上 。
翻譯自: https://www.freecodecamp.org/news/how-to-build-an-android-messenger-app-with-online-presence-using-kotlin-fdcb3ea9e73b/
總結
以上是生活随笔為你收集整理的如何使用Kotlin构建具有在线状态的Android Messenger应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到前任住院是什么意思
- 下一篇: 男人做梦梦到女鬼是什么征兆