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

后端 未结 1 1165
时光取名叫无心
时光取名叫无心 2021-01-03 12:41

I am running a Socket.IO client on my Android app and I am having trouble passing data from the Service (that handles the connection o

1条回答
  •  有刺的猬
    2021-01-03 13:46

    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");
        }
    

    0 讨论(0)
提交回复
热议问题