SohailAziz
SohailAziz

Reputation: 8034

passing data back to activity from service

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

Answers (1)

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52936

Cons:

  • there can be multiple instances of an activity, with your approach only the one created last will get the result.
  • it may or may not be visible/usable when the result is delivered.
  • your service will be directly depending on your UI(Activity).

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

Related Questions