Best practice for pass info from Service to Activity (or Fragment)

一笑奈何 提交于 2019-11-30 16:11:53
Libin

You can bind to the service from Activity and create a service connection. So that you will have the instance of service to communicate.

See my answer here How to pass a handler from activity to service on how to bind to service and establish a service connection.

Apart from this, have an interface defined in your service

public interface OnServiceListener{
    public void onDataReceived(String data);
}

Add a set Listener method in service to register the listener from Activity

private OnServiceListener mOnServiceListener = null;

public void setOnServiceListener(OnServiceListener serviceListener){
    mOnServiceListener = serviceListener;
}

Next, In your Activity implement the Listener interface

public class MainActivity extends ActionBarActivity implements CustomService.OnServiceListener{

    @Override
    public void onDataReceived(String data) {

     }
}

Next, When the service connection is established , register the listener

    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        customService = ((CustomService.LocalBinder) iBinder).getInstance();
        customService.setOnServiceListener(MainActivity.this);
    }

Now, When you receive the data in service pass the data to the Activity through onDataReceived method.

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