public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
};
}
intentt = new Intent();启动服务
intentt.setComponent(new ComponentName("com.example.com.myapplication", "com.example.com.myapplication.MyService"));
bindService(intentt, this, Context.BIND_AUTO_CREATE);
销毁服务
unbindService(this);5.返回一个iMyAidlInterface接口
/**6.传递数据
*
* 连接
* @param name
* @param service
*/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMyAidlInterface=IMyAidlInterface.Stub.asInterface(service);
}
if(iMyAidlInterface!=null) {
try {
iMyAidlInterface.setDate(et.getText().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
7.接受数据并且应用
return new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public void setDate(String data) throws RemoteException {
MyService.this.data=data;
}
};
服务返回值onBind
public IBinder onBind(Intent intent) {启动服务
// TODO: Return the communication channel to the service.
return new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
};
}
bindService(intentt, this, Context.BIND_AUTO_CREATE);
销毁服务
unbindService(this);
/**
* 连接成功
* @param name
* @param service
*/
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// 打印输出
Log.e("App2 BInd service", "StartService");
}
/**
* 连接失败
* @param name
* @param
*/
@Override
public void onServiceDisconnected(ComponentName name) {
}
if(iMyAidlInterface!=null) {
try {
iMyAidlInterface.setDate(et.getText().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
返回时接受的接口
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
iMyAidlInterface=IMyAidlInterface.Stub.asInterface(service);
}
在p里面的Service中实现接口并且传值
@Override在Myservic中使用:
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public void setDate(String data) throws RemoteException {
MyService.this.data=data;
}
};
}
@Override
public void onCreate() {
super.onCreate();
new Thread(new Runnable() {
@Override
public void run() {
run=true;
while (run){
try {
Thread.sleep(1000);
Log.e("service", data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
Log.e("service", "startServier");
}
原文:http://www.cnblogs.com/huihuizhang/p/5222431.html