从服务发送到活动的简单消息服务方活动侧
我试图找到一种方法将整数值从我的服务发送到我的MainActivity,但我无法通过互联网上的教程来弄清楚。我正在使用处理程序来接收我从服务中的线程发送的消息。
我在服务中的线程代码:
private class ServiceThread extends Thread {
@Override
public void run() {
super.run();
try{
Log.i("Service", "TASK PERFORMED");
int x = 0;
for (int i = 0; i < 20; i++){
x += (random.nextInt(20) + 20);
}
theInteger = x/20;
Message msg = Message.obtain();
msg.what = MY_RND_INT;
msg.arg1 = theInteger;
handler.sendMessage(msg);
}catch(Exception e){
e.getMessage();
}
}
}
我尝试接收消息的代码:
public Messenger mMessenger = new Messenger(new IncomingHandler());
class IncomingHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case SimpleService.MY_RND_INT:
rndInt.setText(msg.arg1);
break;
default:
super.handleMessage(msg);
}
}
}