一、单向通信
1.新建项目:MyServiceOne
2.新建Service:File -> new -> service
package com.likego.myserviceone;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
}
3.新建aidl:File -> new -> AIDL ->AIDL File
// IMyAidlInterface.aidl
package com.likego.myserviceone;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
}
4.新建项目MyServiceTwo
5.在MyServiceTwo项目下新建MyServiceTwo
6.复制MyServiceOne下的aidl文件夹到MyServiceTwo项目同目录下,并clean一下项目二(andorid studio的BUG,不clean无法找到这个接口文件)build -> clean project,最后两个项目的结构如下:
7.准备工作完成了,开始修改代码,切换到项目一,修改服务一:
package com.likego.myserviceone;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
public class MyService extends Service {
private static final String TAG = "MyService";
//实现接口
private final IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub(){
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString) {
Log.d(TAG, "basicTypes: 服务二给我发消息了");
Log.d(TAG, "basicTypes() called with: anInt = [" + anInt + "], aLong = [" + aLong + "]," +
" aBoolean = [" +