根据android的binder,以及网上aidl的例子,编写了一个调用远程service的例子.
server//
1.aidl
建立com.easymorse包,aidl文件为ICountService.aidl
文件内容:
package com.easymorse;
interface ICountService{
int getCount();
}
2.service
public class CountService extends Service {
private boolean threadDisable;
private int count;
public ICountService.Stub serviceBinder=new ICountService.Stub(){
@Override
public int getCount() throws RemoteException {
return count;
}
};
@Override
public IBinder onBind(Intent intent) {
count = 103;
Log.v("zxl---onBind", "Count is " + count);
return serviceBinder;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
this.threadDisable = true;
Log.v("zxl---CountService", "on destroy");
}
}
3.AndroidManifest.xml
<service
android:name="com.example.myservice.CountService">
server//
client//
1.aidl
建立com.easymorse包,aidl文件为ICountService.aidl
文件内容:
package com.easymorse;
interface ICountService{
int getCount();
}
2.调用
public class MyClientActivity extends Activity {
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("zxl---onServiceDisconnected---"+name);
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ICountService iCountService = ICountService.Stub.asInterface(service);
try {
System.out.println("zxl---onServiceConnected---"+iCountService.getCount());
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my_client);
Intent service = new Intent("com.easymorse.CountService");
bindService(service, serviceConnection, BIND_AUTO_CREATE);
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
unbindService(serviceConnection);
super.onDestroy();
}
}
client//