How to Collect info from IntentService and Update Android UI

断了今生、忘了曾经 提交于 2019-11-27 12:02:38

问题


I'm learning Android and I'm stuck with my service.

My application connects via Socket to my server every X seconds, receives an XML, parses the information and it's shows in a TextView.

I'd like to know how can I implement an IntenService to do this and how to communicate the info to the UI. I'm finding very hard to see good examples.

I appreciate any help you can give me.

Thank you!


回答1:


Use a handler and send a message to parent activity from the intentservice

Parent Activity :

Declaring Handler

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

Invoking the intentservice:

        Intent intent = new Intent(this, IntentService1.class);
        intent.putExtra("messenger", new Messenger(handler));
        startService(intent);

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


来源:https://stackoverflow.com/questions/7871521/how-to-collect-info-from-intentservice-and-update-android-ui

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!