Android : Service Communication with Activity

We know how much service are important in Android Application Development. We already know that we can communicate with Service from activity just by using method startService() and passing Intent to the argument in the method, or either we can use bindService() to bind the service to the activity with argument Intent. Also when I was new to Android and anyone had asked me how to make Synchronous calls with Service then my answer is like First we will start service and we define our custom Action with BroadCastReceiver and when action is sent then BroadCastReceiver can be used to start activity.

This seems easy but actually its a big problem when you need an freequent update to the activity if you go with this solution you might end up chocking your Application. Also either we are using bindService() or startService() method we can only pass Intent objects to them and here we are limited with what Intent can carry. Also these is nothing you have to create in this followup examples everthing is already in the Android API you just need to implement and register it properly.

But when you need an instant update in your activity with your Service then you can go with Local Bind Service. By using Callback implementation in Service you can can get instant result of the operation that is being performed in Service, in onBind() you can get the instance of Service and once you have the instance of the service you call call its method which process the task. and you can set the Callbacks during those process and the response of the call back in Acivity can be used to update the UI for the User.

Following is the raw implementation for Service with custom callback methods

public class ServiceCommunication extends Service {// Unique Notification ID 
private static final int NOTIFICATION_ID = 1001;
// Custom Binder
private MyBinder mLocalbinder = new MyBinder();
// Custom interface Callback which is declared in this Service
private CallBack mCallBack;
@Nullable
@Override
public IBinder onBind(Intent intent) {// Getting the instance of Binder
return mLocalbinder;
}
// Callback Setter
public void setCallBack(CallBack callBack) {
mCallBack = callBack;
}
// Method to perform Long running task for User
public void doLongRunningTaskInService(User user) {
new CustomAsyncTask().execute(user);
}
// Method to create notification
private Notification getNotificationBuilder() {
Notification notification;
// Build your own custom Notification
return notification;
}
// callback Interface
public interface CallBack {
void onOperationProgress(int progress);
void onOperationCompleted(User user);
}
//Custom Binder class
public class MyBinder extends Binder {
public ServiceCommunication getService() {return ServiceCommunication.this;}}// AsyncTask class to perform any task
private class CustomAsyncTask extends AsyncTask<User, Integer, User> {
@Override
protected void onPreExecute() {
super.onPreExecute();
Notification notification = getNotificationBuilder();
startForeground(NOTIFICATION_ID, notification);
}@Override
protected User doInBackground(User... objects) {
return null;
}
@Override
protected void onPostExecute(User user) {
super.onPostExecute(user);
if (mCallBack != null) {
mCallBack.onOperationCompleted(user);
}
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
if (mCallBack != null && values.length > 0) {for (Integer integer : values)
mCallBack.onOperationProgress(integer);
}
}
@Override
protected void onCancelled() {
super.onCancelled();
}
}
}

Now its time to use this service in our Activity with our callback.

// Activity class with ServiceConnection interface from Android Api //and our Custom Interface ServiceCommunication.CallBackpublic class MainActivity extends AppCompatActivity implements ServiceConnection, ServiceCommunication.CallBack {ServiceCommunication serviceCommunitcation;@Override
protected void onResume() {
super.onResume();
Intent intentData = new Intent(this, ServiceCommunication.class); bindService(intentData, this, BIND_AUTO_CREATE);
}
@Override
protected void onPause() {
super.onPause();
// unbindService if activity is in onPause() state
if (serviceCommunitcation != null) {
serviceCommunitcation.setCallBack(null);
unbindService(this);
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
onTriggerLongRunningOperation();}public void onTriggerLongRunningOperation() {if (serviceCommunitcation != null) {serviceCommunitcation.
doLongRunningTaskInService(new User("Sahitya", "Male"));
}}@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

serviceCommunitcation = ((ServiceCommunication.MyBinder)iBinder).getService();
serviceCommunitcation.setCallBack(this); }@Override
public void onServiceDisconnected(ComponentName componentName) {
}@Override
public void onOperationProgress(int progress) {
// Call back result form the Service
}
@Override
public void onOperationCompleted(User user) {
// Resultant output from the Service after task compeletion }
}

So in this way we can communicate with service with Activity.

)
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade