Я пытаюсь реализовать удаленную привязку между двумя разными приложениями Android. Первое приложение содержит ClientActivity, которое привязывается к Службе во втором приложении. Предполагается, что служба сгенерирует случайное число и отправит его обратно в действие с помощью Messenger. Однако связь между двумя приложениями не работает должным образом.
APP 1 (клиентское приложение)
class ClientActivity : AppCompatActivity() {< /p>
Код: Выделить всё
private var binding : ActivityMainBinding? = null
private var senderMessenger: Messenger? = null
private var receiverMessenger: Messenger? = null
val RECEIVED_CONST_VALUE = 0
private var isBind = false
private var serviceIntent : Intent? = null
private var serviceConnection: ServiceConnection? = null
inner class MyHolder(val view: TextView) : Handler() {
override fun handleMessage(msg: Message) {
if (msg.what == RECEIVED_CONST_VALUE) {
Log.d("x", "this is calling")
val randomValue = msg.arg1
view.text = "Random no is : $randomValue"
}
super.handleMessage(msg)
}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
serviceIntent = Intent("ars.example.conceptprectice.MyService")
serviceIntent!!.setPackage("ars.example.conceptprectice")
setContentView(binding?.root)
serviceConnection = object : ServiceConnection {
override fun onServiceConnected(name: ComponentName?, serviceBinder: IBinder?) {
Log.d("B", "Service Connected Called")
senderMessenger = Messenger(serviceBinder)
receiverMessenger = Messenger(MyHolder(binding?.text!!))
isBind = true
}
override fun onServiceDisconnected(name: ComponentName?) {
Log.d("A", "Service Disconnected Called")
senderMessenger = null
receiverMessenger = null
isBind = false
}
}
binding?.bind?.setOnClickListener {
bindService(serviceIntent!!, serviceConnection!!, BIND_AUTO_CREATE)
Toast.makeText(this, "Service bound!", Toast.LENGTH_SHORT).show()
}
binding?.unbind?.setOnClickListener {
Toast.makeText(this, "Service unbound!", Toast.LENGTH_SHORT).show()
unbindService(serviceConnection!!)
isBind = false
}
binding?.generate?.setOnClickListener {
if (isBind) {
val message = Message.obtain(null, 0)
message.replyTo = receiverMessenger
try {
senderMessenger?.send(message)
} catch (e: RemoteException) {
Toast.makeText(this, "Something went wrong", Toast.LENGTH_SHORT).show()
}
} else {
Toast.makeText(this, "Service is not bound!", Toast.LENGTH_SHORT).show()
}
}
}
override fun onDestroy() {
serviceConnection = null
super.onDestroy()
}
Код: Выделить всё
class MyService : Service() {
private var isRandomStart = false
private var GET_COUNT = 0
inner class RandomNumberRequestHandler : Handler() {
override fun handleMessage(msg: Message) {
if (msg.what == GET_COUNT) {
val messageSendRandNo = Message.obtain(null, 0)
messageSendRandNo.arg1 = generateRandom()
try {
msg.replyTo.send(messageSendRandNo)
} catch (e: RemoteException) {
Log.d("RE", e.message.toString())
}
}
super.handleMessage(msg)
}
}
private val randomMessageMessenger = Messenger(RandomNumberRequestHandler())
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
isRandomStart = true
Thread {
while (isRandomStart) {
Thread.sleep(1000)
Log.d("IM", "Thread ID: ${Thread.currentThread().id} :: ${generateRandom()}")
}
}.start()
return START_STICKY
}
override fun onDestroy() {
stopRandomGen()
Log.d("IMX", "Service Destroyed")
super.onDestroy()
}
override fun onBind(intent: Intent?): IBinder? {
Log.d("IMX", "Service Bound")
return randomMessageMessenger.binder
}
override fun onUnbind(intent: Intent?): Boolean {
Log.d("IMX", "Service Unbound")
return super.onUnbind(intent)
}
fun generateRandom(): Int = (0..100).random()
fun stopRandomGen() { isRandomStart = false }
}
Код: Выделить всё
The service binds successfully, but the random number is not getting displayed in the TextView.
It seems like the message from the remote service is not reaching the client activity.
Код: Выделить всё
Ensured that both apps are signed with the same key and have the same android:sharedUserId.
Verified that the MyService is declared properly in the AndroidManifest.xml of the service app.
Код: Выделить всё
Подробнее здесь: https://stackoverflow.com/questions/789 ... ementation
Мобильная версия