如何从IntentService收集信息并更新Android UI



我正在学习Android,我被我的服务困住了。

我的应用程序通过Socket连接到我的服务器每X秒,接收一个XML,解析信息,并显示在一个TextView。

我想知道我如何实现一个interservice来做到这一点,以及如何将信息传达给UI。我发现很难看到好的例子。

我很感激你给我的任何帮助。

谢谢!

使用处理程序并从intentservice向父activity发送消息

Parent Activity:

声明处理程序
Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
            Bundle reply = msg.getData();
                            // do whatever with the bundle here
            }
};

调用intentservice:

        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");
        }
    }

最新更新