Saturday, 7 September 2013

Communication between Android service and activity using listener

Communication between Android service and activity using listener

Most the examples I see for communication between activity and service are
using a BroadcastReceiver. My question is can I replace the broadcast
receiver with just a normal listener? Then I don't have to worry about
marshaling my web service response into a Bundle class. Is there anything
wrong with this approach? Anything less advantageous than using a
BroadcastReceiver? AddListener would be called on the Activity's onCreate
method and RemoveListener would be called in the Activity's onDestroy
method.
package com.example.test;
import java.util.ArrayList;
import java.util.List;
import android.app.IntentService;
import android.content.Intent;
public class AsyncService extends IntentService
{
static List<WebServiceListener> listeners = new
ArrayList<WebServiceListener>();
public static void addListener(WebServiceListener listener)
{
listeners.add(listener);
}
public static void removeListener(WebServiceListener listener)
{
listeners.remove(listener);
}
public AsyncService(String name)
{
super(name);
}
@Override
protected void onHandleIntent(Intent intent)
{
try
{
Thread.sleep(5000); //simulate calling webservice
}
catch (Exception e)
{
//
}
WebServiceResponse response = new WebServiceResponse();
response.status = "SUCCESS";
for (WebServiceListener listener : listeners)
{
listener.onReceiveResult(response);
}
}
}

No comments:

Post a Comment