SoFunction
Updated on 2025-04-09

Use Messenger to implement two-way communication of Service

There is a solution in the Android architecture: use Android Messenger to achieve two-way communication between Service processes.

MainActivity class:

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class MainActivity extends Activity {
 
 private Messenger sender;
 
 private ServiceConnection conn;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  (savedInstanceState);
  setContentView(.activity_main);
  
  Button bind = (Button)findViewById();
  Button start = (Button)findViewById();
  Button send = (Button)findViewById();
  
  (new OnClickListener() {
   @Override
   public void onClick(View v) {
    getStart();
   }
  });
  
  
  (new OnClickListener() {
   @Override
   public void onClick(View v) {
    Intent intent = new Intent(, );
    startService(intent);
   }
  });
  
  (new OnClickListener() {
   @Override
   public void onClick(View v) {
    sendCount();
   }
  });
 }
 
 // Used to start MessengerService private void getStart(){
  
  conn = new ServiceConnection() {
   
   @Override
   public void onServiceDisconnected(ComponentName name) {
    
   }
   
   @Override
   public void onServiceConnected(ComponentName name, IBinder service) {
    
    sender = new Messenger(service);
   }
  };
  
  
  Intent intent = new Intent(this, );
  
//  startService(intent);
  bindService(intent, conn, Service.BIND_AUTO_CREATE);
 
 }
 
 // Pass numerical value private void sendCount(){
  
  Message msg = new Message();
  msg.arg1 = 20;
  msg.arg2 = 20;
 
  try {
   (msg);
  } catch (RemoteException e) {
   ();
  }
  
 }
 
 @Override
 protected void onDestroy() {
  ();
  unbindService(conn);
 }
 
}

kind:

package ;
 
import ;
import ;
import ;
import ;
import ;
import ;
import ;
import ;
 
public class MessengerService extends Service {
 
 Messenger messenger;
 Handler handler;
 int a, b;
 int sum = 0;
 
 @Override
 public IBinder onBind(Intent intent) {
  return ();
 }
 
 @Override
 public void onCreate() {
  ();
  
  handler = new Handler(){
 
   @Override
   public void handleMessage(Message msg) {
    (msg);
 
    a = msg.arg1;
    b = msg.arg2;
   }
   
  };
  messenger = new Messenger(handler);
 }
 
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  
  int sum = subSum(a, b);
  (sum + "");
  return (intent, flags, startId);
 }
 
 private int subSum(int a, int b){
  int sum = a + b;
  return sum;
 }
}

Register in:

<service android:name=".MessengerService"></service>

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.