In Android Framework, Handler are used to send messages to and receive messages from MessageQueue.
I have the following programs that implements 2 handler classes MySensor and MyReceiver (both inherit android handler). Their instances are created on different threads.
MySensor
invokes sendMessage()
to send the message to MessageQueue.
MyReceiver
invokes handleMessage()
to retrieve the message from MessageQueue.
A Looper that both MySensor
and MyReceiver
are bounded with
will processes the messages.
"bounded with" is the word I got from some blogs that explain this concept.
#include <iostream>
#include <android/looper.h>
#include <android/handler.h>
#include <thread>
using namespace android;
enum EventType {
DIAGNOSTIC_SIGNAL,
CONTROL_SIGNAL,
STOP_SIGNAL
};
class MySensor : public Handler {
public:
MySensor(sp<Looper> looper) : Handler(looper) {}
void sendSignal(EventType event, int data) {
Message msg = obtainMessage(event, data);
sendMessage(msg);
}
};
class MyReceiver : public Handler {
public:
MyReceiver(sp<Looper> looper) : Handler(looper) {}
void handleMessage(const Message& msg) {
EventType event = (EventType) msg.what;
int data = msg.arg1;
switch (event) {
case DIAGNOSTIC_SIGNAL:
std::cout << "Received DIAGNOSTIC_SIGNAL with data: " << data << std::endl;
break;
case CONTROL_SIGNAL:
std::cout << "Received CONTROL_SIGNAL with data: " << data << std::endl;
break;
case STOP_SIGNAL:
std::cout << "Received STOP_SIGNAL with data: " << data << std::endl;
break;
default:
std::cout << "Received unknown signal with data: " << data << std::endl;
break;
}
}
};
void runSensor(sp<Looper> looper) {
MySensor sensor(looper);
sensor.sendSignal(DIAGNOSTIC_SIGNAL, 123);
sensor.sendSignal(CONTROL_SIGNAL, 456);
sensor.sendSignal(STOP_SIGNAL, 789);
}
void runReceiver(sp<Looper> looper) {
MyReceiver receiver(looper);
looper->pollOnce(-1);
}
int main() {
sp<Looper> looper = new Looper(false);
std::thread sensorThread(runSensor, looper);
std::thread receiverThread(runReceiver, looper);
sensorThread.join();
receiverThread.join();
return 0;
}
However, I don't understand:
- How can MySensor and MyReceiver be bounded to the Looper, which is actually created on main thread?
- How can we be sure the correct MyReceiver would receive the message ?
- I also see that in some code, people use
msg->sendToTarget
instead ofsendMessage(msg)
. What are differences between the two functions?
p.s: the program is written by chatGPT AI. I also asked the AI the same questions but I trust human more.