|
5 | 5 | */
|
6 | 6 | package com.example.util.simpletimetracker.data
|
7 | 7 |
|
| 8 | +import android.content.Context |
8 | 9 | import com.example.util.simpletimetracker.wear_api.WearActivity
|
| 10 | +import com.example.util.simpletimetracker.wear_api.WearCommunicationAPI |
9 | 11 | import com.example.util.simpletimetracker.wear_api.WearCurrentActivity
|
10 | 12 | import com.example.util.simpletimetracker.wear_api.WearRequests
|
11 | 13 | import com.example.util.simpletimetracker.wear_api.WearSettings
|
12 | 14 | import com.example.util.simpletimetracker.wear_api.WearTag
|
13 |
| -import com.example.util.simpletimetracker.wear_api.WearCommunicationAPI |
| 15 | +import com.google.android.gms.wearable.MessageClient |
| 16 | +import com.google.android.gms.wearable.Wearable |
14 | 17 | import com.google.gson.Gson
|
15 | 18 | import com.google.gson.reflect.TypeToken
|
| 19 | +import dagger.hilt.android.qualifiers.ApplicationContext |
16 | 20 | import javax.inject.Inject
|
| 21 | +import javax.inject.Singleton |
17 | 22 |
|
| 23 | +@Singleton |
18 | 24 | class WearRPCClient @Inject constructor(
|
| 25 | + @ApplicationContext private val context: Context, |
19 | 26 | private val messenger: Messenger,
|
20 | 27 | ) : WearCommunicationAPI {
|
21 | 28 |
|
22 | 29 | private val gson = Gson()
|
| 30 | + private var listener: MessageClient.OnMessageReceivedListener? = null |
23 | 31 |
|
24 | 32 | override suspend fun ping(message: String): String {
|
25 | 33 | val response: String? = messenger
|
@@ -65,6 +73,28 @@ class WearRPCClient @Inject constructor(
|
65 | 73 | return response ?: throw WearRPCException("No response")
|
66 | 74 | }
|
67 | 75 |
|
| 76 | + fun addListener( |
| 77 | + onDataChanged: () -> Unit, |
| 78 | + ) { |
| 79 | + listener = MessageClient.OnMessageReceivedListener { |
| 80 | + if (it.path == WearRequests.DATA_UPDATED) { |
| 81 | + val response: String? = it.data.let(::mapFromBytes) |
| 82 | + if (response == WearRequests.DATA_UPDATED_CURRENT_ACTIVITIES) { |
| 83 | + onDataChanged() |
| 84 | + } |
| 85 | + } |
| 86 | + } |
| 87 | + listener?.let { |
| 88 | + Wearable.getMessageClient(context).addListener(it) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + fun removeListener() { |
| 93 | + listener?.let { |
| 94 | + Wearable.getMessageClient(context).removeListener(it) |
| 95 | + } |
| 96 | + } |
| 97 | + |
68 | 98 | private fun <T> mapToBytes(data: T): ByteArray {
|
69 | 99 | return gson.toJson(data).toByteArray()
|
70 | 100 | }
|
|
0 commit comments