服务器
创建一个Service
package com. example. aidl_server;
import android. app. Service;
import android. content. Intent;
import android. os. IBinder;
import android. os. RemoteException;
public class AudkService extends Service {
public AudkService ( ) {
}
IBinder iBinder = new IMyAidlInterface. Stub ( ) {
@Override
public int add ( int a, int b) throws RemoteException {
return a+ b;
}
} ;
@Override
public IBinder onBind ( Intent intent) {
return iBinder;
}
}
创建一个文件夹aidl中右键创建IMyAidlInterface
package com. example. aidl_server;
interface IMyAidlInterface {
int add ( int a , int b) ;
}
清单配置文件
< ? xml version= "1.0" encoding= "utf-8" ? >
< manifest xmlns: android= "http://schemas.android.com/apk/res/android"
package = "com.example.aidl_server" >
< application
android: allowBackup= "true"
android: icon= "@mipmap/ic_launcher"
android: label= "@string/app_name"
android: roundIcon= "@mipmap/ic_launcher_round"
android: supportsRtl= "true"
android: theme= "@style/AppTheme" >
< service
android: name= ".AudkService"
android: enabled= "true"
android: exported= "true" >
< intent- filter>
< action android: name= "com.ludan.111" > < / action>
< / intent- filter>
< / service>
< activity android: name= ".MainActivity" >
< intent- filter>
< action android: name= "android.intent.action.MAIN" / >
< category android: name= "android.intent.category.LAUNCHER" / >
< / intent- filter>
< / activity>
< / application>
< / manifest>
客户端
package com. example. aidl_client;
import android. app. Service;
import android. content. ComponentName;
import android. content. Intent;
import android. content. ServiceConnection;
import android. os. IBinder;
import android. os. RemoteException;
import android. support. v7. app. AppCompatActivity;
import android. os. Bundle;
import android. util. Log;
import android. widget. Toast;
import com. example. aidl_server. IMyAidlInterface;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate ( Bundle savedInstanceState) {
super . onCreate ( savedInstanceState) ;
setContentView ( R. layout. activity_main) ;
ServiceConnection connection = new ServiceConnection ( ) {
@Override
public void onServiceConnected ( ComponentName name, IBinder service) {
IMyAidlInterface iMyAidlInterface = IMyAidlInterface. Stub. asInterface ( service) ;
try {
int add = iMyAidlInterface. add ( 10 , 10 ) ;
Log. i ( "TAG" , "onServiceConnected: " + add) ; ;
Toast. makeText ( MainActivity. this , add+ "" , Toast. LENGTH_SHORT) . show ( ) ;
} catch ( RemoteException e) {
e. printStackTrace ( ) ;
}
}
@Override
public void onServiceDisconnected ( ComponentName name) {
}
} ;
Intent intent = new Intent ( ) ;
intent. setPackage ( "com.example.aidl_server" ) ;
intent. setAction ( "com.ludan.111" ) ;
bindService ( intent, connection, Service. BIND_AUTO_CREATE) ;
}
}