Android源码添加自己的aidl,service/clien

2018-11-30  本文已影响0人  简书宇少

1 service的实现

步骤1:

添加aidl文件,包名自己定,然后在Android.mk中添加

package xx.xx.xx.xx
interface AIDL_Service {
    //auto code
    void testPrint();
}

LOCAL_SRC_FILES += $(call all-Iaidl-files-under, src/xxx/xxx/xxx)

然后mm编译,会生成相应的java

步骤2:

添加service java文件,

public class MyService extends Service {
    IMyService.Stub mBinder = new IMyService.Stub() {
        @Override
        public void testPrint() throws RemoteException {
            FTLog.d(this, "this is from MyService remote invoke");
        }
    };

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }
}

AndroidManifest.xml添加service组件

<service android:name=".MyService"
            android:process=":remote"
            android:exported="true">
            <intent-filter>
                <action android:name="com.xxx.xxx.MyService"/>
            </intent-filter>
</service>

这样服务端基本上已经好了,下面看client

2 client的实现

步骤1:
需要创建一个同aidl的包名,和上面的保持一致,将aidl文件拷贝过来,我的client使用的AS开发的,需要Make Project,

    IMyService mMyService;

    private ServiceConnection sc = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            //mAIDL_Service = AIDL_Service1.Stub.asInterface(service);
            mMyService = IMyService.Stub.asInterface(service);

            try {
                mMyService.testPrint();
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
Intent intent = new Intent("com.xxx.xxx.MyService");
intent.setPackage("com.xxx.xxx");
bindService(intent,sc, Context.BIND_AUTO_CREATE);

参考资料:
https://blog.csdn.net/carson_ho/article/details/53160279
https://blog.csdn.net/fmc088/article/details/82628632

以上做一个记录。

上一篇下一篇

猜你喜欢

热点阅读