服务端
public class MyService extends Service {
public MyService ( ) {
}
IBinder iBinder = new IMyAidlInterface. Stub ( ) {
@Override
public int muit ( int a, int b) throws RemoteException {
return a* b;
}
} ;
@Override
public IBinder onBind ( Intent intent) {
return iBinder;
}
}
客户端
public class MainActivity extends AppCompatActivity {
private ServiceConnection connection;
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R. layout. activity_main) ;
Intent intent = new Intent ( ) ;
intent. setPackage ( "com.example.aidl_service" ) ;
intent. setAction ( "com.lu" ) ;
connection = new ServiceConnection ( ) {
@Override
public void onServiceConnected ( ComponentName componentName, IBinder iBinder) {
IMyAidlInterface iMyAidlInterface = IMyAidlInterface. Stub. asInterface ( iBinder) ;
try {
int muit = iMyAidlInterface. muit ( 2 , 2 ) ;
Toast. makeText ( MainActivity. this , "2*2=" + muit, Toast. LENGTH_SHORT) . show ( ) ;
} catch ( RemoteException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void onServiceDisconnected ( ComponentName componentName) {
}
} ;
bindService ( intent, connection, BIND_AUTO_CREATE) ;
}
@Override
protected void onDestroy ( ) {
super . onDestroy ( ) ;
unbindService ( connection) ;
}
}