描述:https://github.com/leavesC
*/
public class MainActivity extends AppCompatActivity {
private static final String TAG = “MainActivity”;
private static final int CODE_MESSAGE = 1;
private Messenger messenger;
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
messenger = new Messenger(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
messenger = null;
}
};
private EditText et_message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindService();
initView();
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(serviceConnection);
}
private void bindService() {
Intent intent = new Intent();
intent.setClassName(“com.czy.messenger_server”, “com.czy.messenger_server.MessengerService”);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void initView() {
et_message = findViewById(R.id.et_message);
Button btn_sendMessage = findViewById(R.id.btn_sendMessage);
btn_sendMessage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (messenger == null) {
return;
}
String content = et_message.getText().toString();
if (TextUtils.isEmpty(content)) {
return;
}
int arg1 = Integer.valueOf(content);
Message message = new Message();
message.what = CODE_MESSAGE;
message.arg1 = arg1;
try {
messenger.send(message);
Log.e(TAG, “消息发送成功”);
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
}