远程服务类
清单文件中注册
<service android:name=".RemoteService">
<intent-filter>
<action android:name="com.gjj.remoteservice"/>
</intent-filter>
</service>
package com.example.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import com.example.test2.IRemoteInterface;
/**
* Created by joy on 2016/1/12.
*/
public class RemoteService extends Service {
@Override
public IBinder onBind(Intent intent) {
System.out.println("绑定了");
return new Mybind();
}
class Mybind extends IRemoteInterface.Stub {
@Override
public void qianxian() {
RemoteService.this.say();
}
}
public void say(){
System.out.println("我是远程服务");
}
}
IRemoteInterface.Stub为创建的AIDL文件自动生成的类
首先创建AIDL文件IRemoteInterface接口,然后在android studio中make module自动生成IRemoteInterface.java,现在可以调用了
注意这里的AIDL文件的包名必须和客户端的一致
客户端
package com.example.test2;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.View;
public class LocalActivity extends Activity {
private IRemoteInterface remoteInterface;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_local);
}
public void startRemoteService(View v){
Intent intent=new Intent();
intent.setAction("com.gjj.remoteservice");
bindService(intent,new MyServiceConn(),BIND_AUTO_CREATE);
}
public void callRemoteMethod(View v){
try {
remoteInterface.qianxian();
} catch (RemoteException e) {
e.printStackTrace();
}
}
class MyServiceConn implements ServiceConnection{
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
remoteInterface= IRemoteInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
}
}