Как получить сообщение чата в реальном времени с помощью recyclerview в android java

Я реализовал список просмотра чата с помощью recyclerview. Но список не показывает сообщение получателю в реальном времени.

Если я отправляю сообщение, получатель должен получить его в реальном времени. Как я могу заставить это работать.

куда вы отправляете свое сообщение?

Majid Ali 31.03.2021 12:50

Экран чата. Например как WhatsApp. Если я отправляю сообщение, получатель должен получать сообщение в реальном времени. Я использую recyclerview

sejn 31.03.2021 13:02
0
2
45
1

Ответы 1

выполните этот шаг.

Добавьте их в файл build.Gradle вашего модуля приложения:

 dependencies {
    // [...]

    implementation 'com.pusher:pusher-java-client:1.8.0'
    implementation 'com.android.support:recyclerview-v7:28.0.0'
}

Откройте сгенерированный файл activity_main.xml и замените его следующим содержимым:

 <?xml version = "1.0" encoding = "utf-8"?>
<FrameLayout
    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 = ".MainActivity">

    <android.support.v7.widget.RecyclerView
        android:id = "@+id/recyclerViewContents"
        app:layout_constraintTop_toTopOf = "parent"
        android:layout_width = "match_parent"
        android:layout_height = "wrap_content"/>

    <TextView
        android:layout_width = "wrap_content"
        android:layout_height = "wrap_content"
        android:padding = "10dp"
        android:textSize = "16sp"
        app:layout_constraintRight_toRightOf = "parent"
        app:layout_constraintBottom_toBottomOf = "parent"
        android:layout_margin = "16dp"
        android:background = "@drawable/rounded_corner"
        android:textColor = "@android:color/black"
        android:visibility = "gone"
        android:layout_gravity = "right|bottom"
        android:id = "@+id/textViewNewContents" />

</FrameLayout>

**Create a new drawable named rounded_corner and paste this:**

  <?xml version = "1.0" encoding = "utf-8"?>
<shape xmlns:android = "http://schemas.android.com/apk/res/android" >
    <stroke
        android:width = "1dp" />

    <solid android:color = "#ffffff" />

    <padding
        android:left = "1dp"
        android:right = "1dp"
        android:bottom = "1dp"
        android:top = "1dp" />

    <corners android:radius = "5dp" />
</shape>

Затем давайте создадим адаптер для представления ресайклера. Создайте новый класс RecyclerListAdapter и вставьте его:

  import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView

class RecyclerListAdapter(private val listener:OnLastPositionReached): RecyclerView.Adapter<RecyclerListAdapter.ViewHolder>() {

  private val contentList: ArrayList<String> = ArrayList()

  override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
    return ViewHolder(
       LayoutInflater
         .from(parent.context)
         .inflate(android.R.layout.simple_list_item_1, parent, false)
    )
  }

  override fun onBindViewHolder(holder: ViewHolder, position: Int) {
    holder.bind(contentList[position])

    if (position == contentList.size-1){
      listener.lastPositionReached()
    } else {
      listener.otherPosition()
    }
  }

  override fun getItemCount(): Int = contentList.size

  fun addItem(item:String) {
    contentList.add(item)
    notifyDataSetChanged()
  }

  inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    private val userName: TextView = itemView.findViewById(android.R.id.text1)

    fun bind(item: String) = with(itemView) {
      userName.text = item
    }
  }

  interface OnLastPositionReached {
    fun lastPositionReached()
    fun otherPosition()
  }
}

Наконец, откройте MainActivity и настройте его так:

   import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.pusher.client.Pusher
import com.pusher.client.PusherOptions
import kotlinx.android.synthetic.main.activity_main.*
import org.json.JSONObject

class MainActivity : AppCompatActivity(), RecyclerListAdapter.OnLastPositionReached {

  private var count = 0
  private val recyclerListAdapter = RecyclerListAdapter(this)

  private var lastPosition = false
  override fun otherPosition() {
    lastPosition = false
  }

  override fun lastPositionReached() {
    lastPosition = true
    textViewNewContents.visibility = View.GONE
    count = 0
  }

  override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setupClickListeners()
    setupRecyclerView()
    setupPusher()
  }
}

При щелчке по текстовому окну, показывающему количество новых сообщений, он немедленно прокручивается до последних сообщений, устанавливает счетчик на 0 и скрывает текстовое представление.

Следующий метод - это метод setupRecyclerView. Настройте это так:

 private fun setupRecyclerView() {
  with(recyclerViewContents){
    layoutManager = LinearLayoutManager(this@MainActivity)
    adapter = recyclerListAdapter
  }

  recyclerListAdapter.addItem("Hello World")
  recyclerListAdapter.addItem("New article alert!")
  recyclerListAdapter.addItem("Pusher is actually awesome")
  recyclerListAdapter.addItem("Realtime functionality freely provided ")
  recyclerListAdapter.addItem("Checkout pusher.com/tutorials")
  recyclerListAdapter.addItem("You can also checkout blog.pusher.com")
  recyclerListAdapter.addItem("Learn how to update contents properly ")
  recyclerListAdapter.addItem("Hello World")
  recyclerListAdapter.addItem("New article alert!")
  recyclerListAdapter.addItem("Pusher is actually awesome")
  recyclerListAdapter.addItem("Realtime functionality freely provided ")
  recyclerListAdapter.addItem("Checkout pusher.com/tutorials")
  recyclerListAdapter.addItem("You can also checkout blog.pusher.com")
  recyclerListAdapter.addItem("Learn how to update contents properly ")
}

Следующий метод - это метод setupPusher. Настройте это так:

private fun setupPusher() {
  val options = PusherOptions()
  options.setCluster("PUSHER_CLUSTER")

  val pusher = Pusher("PUSHER_KEY", options)
  val channel = pusher.subscribe("my-channel")

  channel.bind("my-event") { channelName, eventName, data ->
    runOnUiThread {  
      if (!lastPosition){
        count ++
        textViewNewContents.text = count.toString()
        textViewNewContents.visibility = View.VISIBLE
        recyclerListAdapter.addItem(JSONObject(data).getString("message"))    
      } else {
        recyclerListAdapter.addItem(JSONObject(data).getString("message"))
        recyclerViewContents.scrollToPosition(recyclerListAdapter.itemCount-1)
      } 
    }
  }

  pusher.connect()
}

теперь это видно.

Я использую Java, а не Kotlin

sejn 31.03.2021 13:47

Могу ли я использовать это в этом толкателе в java

sejn 06.04.2021 10:13

Другие вопросы по теме