Reputation: 8034
In order to pass data back to activity from service, I came to know about ResultReceiver, broadcast/local broadcasts and binded service. However I am confused about this approach: If we simply call activity static public funcion to pass something back, what are the pros and cons of this approach. Say I have activity:
public interface ListenerInterface {
void DataExchange(String data);
}
public class MainActivity extends Activity implements ListenerInterface{
private static MainActivity instance;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
instance=this;
Intent i=new Intent();
i.setClass(this, MyService.class);
startService(i);
}
public static MainActivity getInstance(){
if(instance!=null)
return instance;
return null;
}
@Override
public void DataExchange(String data) {
// TODO Auto-generated method stub
Log.d("sohail","data received="+data);
}
}
and an IntentService:
public class MyService extends IntentService{
MainActivity obj;
public MyService() {
super("MyService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent arg0) {
// TODO Auto-generated method stub
MainActivity.getInstance().DataExchange("Service Data");
}
}
Upvotes: 1
Views: 1078
Reputation: 52936
Cons:
A better approach would be to have the activity implement some interface (say DataHandler
) and not couple it directly to the service. Additionally, to make sure you only receive data when you can actually do something with it, have the activity register itself as a handler onStart()
and unregister onStop()
.
Upvotes: 2