public class MainActivity extends AppCompatActivity {
private Button button;
private IMyAidlService myService;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 获取服务对象
myService = IMyAidlService.Stub.asInterface(service);
Toast.makeText(getBaseContext(), "onServiceConnected", Toast.LENGTH_LONG).show();
}
@Override
public void onServiceDisconnected(ComponentName name) {
myService = null;
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
try {
if (myService == null) {
// onServiceConnected 回调完成后才能得到接口
return;
}
User user = myService.giveMessage(new User("Android", 110));
if (user != null) {
Toast.makeText(getBaseContext(), user.name, Toast.LENGTH_LONG).show();
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
});
Intent intent = new Intent();
// 目标Service action
intent.setAction("com.jfson.aidlserver.IMyAidlService");
// 5.0以上,需要指定包名
intent.setPackage("com.jfson.aidlserver");// the service package
// 绑定服务,可设置或触发一些特定的事件
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
}