Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Collect info from IntentService and Update Android UI

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!

like image 596
Fabricio Avatar asked Oct 24 '11 05:10

Fabricio


1 Answers

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");
        }
    }
like image 164
Farhan Avatar answered Oct 15 '22 03:10

Farhan