创建两个Module
在Module:app中的Myservice代码
public class Myservice extends Service {
@SuppressLint("HandlerLeak")
Messenger server_messager=new Messenger(new Handler(){
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
//接受客户端消息
Bundle bundle = msg.getData();
String message = bundle.getString("client_message");
Toast.makeText(Myservice.this, "服务器发来的消息:"+message, Toast.LENGTH_SHORT).show();
//向客户端发送消息
Messenger clientMessager=msg.replyTo;//用于获取客户端的信使
Message message1 = Message.obtain();
Bundle bundle1 = new Bundle();
bundle1.putString("server_message","你不是真正的快乐");
message1.setData(bundle1);
try {
clientMessager.send(message1);
} catch (RemoteException e) {
e.printStackTrace();
}
super.handleMessage(msg);
}
});
//TODO 返回server_messager的代理人,便于客户端获取服务端信使
@Override
public IBinder onBind(Intent intent) {
return server_messager.getBinder();
}
public Myservice() {
}
}
在Module:myservices中的MainActivity代码
public class MainActivity extends AppCompatActivity {
@SuppressLint("HandlerLeak")
//3.客户端的信使:负责接受服务器发来的消息
private Messenger Clientmesssager = new Messenger(new Handler() {
@Override
public void handleMessage(@NonNull Message msg) {
super.handleMessage(msg);
Bundle bundle = msg.getData();
String message = bundle.getString("server_message");
Toast.makeText(MainActivity.this, "接受到服务器发来的消息" + message, Toast.LENGTH_SHORT).show();
}
});
// 4. 客户端发送消息给服务端
private Messenger servermessenger;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
servermessenger = new Messenger(service);
Message message = Message.obtain();
Bundle bundle = new Bundle();
bundle.putString("client_message", "服务器你好");
message.setData(bundle);
//非常重要的一句话
message.replyTo = Clientmesssager;
try {
servermessenger.send(message);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i("TAG", "onCreate方法");
//1.绑定服务
Intent intent = new Intent();
intent.setAction("com.myf");
intent.setPackage("com.bwie.mylianxi820");
bindService(intent,connection, Service.BIND_AUTO_CREATE);
}
//2.解除绑定
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(connection);
}
}