我正在学习 Android,但我坚持使用我的服务。
我的应用程序每隔 X 秒通过 Socket 连接到我的服务器,接收 XML,解析信息并显示在 TextView 中。
我想知道如何实现 IntenService 来执行此操作以及如何将信息传达给 UI。我发现很难看到好的例子。
我很感激你能给我的任何帮助。
谢谢!
我正在学习 Android,但我坚持使用我的服务。
我的应用程序每隔 X 秒通过 Socket 连接到我的服务器,接收 XML,解析信息并显示在 TextView 中。
我想知道如何实现 IntenService 来执行此操作以及如何将信息传达给 UI。我发现很难看到好的例子。
我很感激你能给我的任何帮助。
谢谢!
使用处理程序并从意图服务向父活动发送消息
家长活动:
声明处理程序
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
Bundle reply = msg.getData();
// do whatever with the bundle here
}
};
调用意图服务:
Intent intent = new Intent(this, IntentService1.class);
intent.putExtra("messenger", new Messenger(handler));
startService(intent);
内部IntentService:
Bundle bundle = intent.getExtras();
if (bundle != null) {
Messenger messenger = (Messenger) bundle.get("messenger");
Message msg = Message.obtain();
msg.setData(bundle); //put the data here
try {
messenger.send(msg);
} catch (RemoteException e) {
Log.i("error", "error");
}
}