├── .gitignore ├── .travis.yml ├── LICENSE.txt ├── README.md ├── README_CN.md ├── andlinker ├── .gitignore ├── build.gradle ├── maven-publish.gradle ├── proguard-rules.pro ├── properties.gradle └── src │ └── main │ ├── AndroidManifest.xml │ └── java │ └── com │ └── codezjx │ └── andlinker │ ├── AndLinker.java │ ├── AndLinkerBinder.java │ ├── ArrayType.java │ ├── BaseTypeWrapper.java │ ├── Call.java │ ├── CallAdapter.java │ ├── Callback.java │ ├── CallbackTypeWrapper.java │ ├── Dispatcher.java │ ├── ICallback.java │ ├── ITransfer.java │ ├── InOutTypeWrapper.java │ ├── InTypeWrapper.java │ ├── Invoker.java │ ├── LinkerBinderImpl.java │ ├── Logger.java │ ├── MethodExecutor.java │ ├── OutType.java │ ├── OutTypeWrapper.java │ ├── ParameterHandler.java │ ├── RemoteCall.java │ ├── Request.java │ ├── RequestBuilder.java │ ├── Response.java │ ├── ServiceMethod.java │ ├── SuperParcelable.java │ ├── Type.java │ ├── TypeFactory.java │ ├── Utils.java │ ├── adapter │ ├── DefaultCallAdapterFactory.java │ ├── OriginalCallAdapterFactory.java │ ├── rxjava │ │ ├── CallArbiter.java │ │ ├── CallExecuteOnSubscribe.java │ │ ├── RxJavaCallAdapter.java │ │ └── RxJavaCallAdapterFactory.java │ └── rxjava2 │ │ ├── CallExecuteObservable.java │ │ ├── RxJava2CallAdapter.java │ │ └── RxJava2CallAdapterFactory.java │ └── annotation │ ├── Callback.java │ ├── In.java │ ├── Inout.java │ ├── OneWay.java │ ├── Out.java │ └── RemoteInterface.java ├── build.gradle ├── dependencies.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sample ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── andlinker │ │ ├── BindingActivity.java │ │ ├── IBaseCallback.java │ │ ├── IBaseService.java │ │ ├── IRemoteCallback.java │ │ ├── IRemoteService.java │ │ ├── IRemoteTask.java │ │ ├── ParcelableObj.java │ │ └── RemoteService.java │ └── res │ ├── drawable-v24 │ └── ic_launcher_foreground.xml │ ├── drawable │ └── ic_launcher_background.xml │ ├── layout │ └── activity_binding.xml │ ├── mipmap-anydpi-v26 │ ├── ic_launcher.xml │ └── ic_launcher_round.xml │ ├── mipmap-hdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-mdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ ├── mipmap-xxxhdpi │ ├── ic_launcher.png │ └── ic_launcher_round.png │ └── values │ ├── colors.xml │ ├── strings.xml │ └── styles.xml └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | jdk: 4 | - oraclejdk8 5 | 6 | android: 7 | components: 8 | # Uncomment the lines below if you want to 9 | # use the latest revision of Android SDK Tools 10 | - tools 11 | - platform-tools 12 | 13 | # The SDK version used to compile your project 14 | - android-26 15 | 16 | # The BuildTools version used by your project 17 | - build-tools-28.0.3 18 | 19 | # Additional components 20 | - extra-android-support 21 | - extra-android-m2repository 22 | 23 | # Command to run 24 | script: ./gradlew :andlinker:build 25 | 26 | notifications: 27 | email: false 28 | 29 | # as per http://blog.travis-ci.com/2014-12-17-faster-builds-with-container-based-infrastructure/ 30 | sudo: false 31 | 32 | # Caching: https://docs.travis-ci.com/user/languages/android/#Default-Test-Command-for-Gradle 33 | before_cache: 34 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 35 | - rm -fr $HOME/.gradle/caches/*/plugin-resolution/ 36 | 37 | cache: 38 | directories: 39 | - $HOME/.gradle/caches/ 40 | - $HOME/.gradle/wrapper/ 41 | - $HOME/.android/build-cache 42 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2018 codezjx 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | [![Build Status](https://travis-ci.org/codezjx/AndLinker.svg?branch=master)](https://travis-ci.org/codezjx/AndLinker) 3 | [![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.codezjx.library/andlinker/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.codezjx.library/andlinker) 4 | [![License](https://img.shields.io/badge/License-Apache%20License%202.0-blue.svg)](http://www.apache.org/licenses/LICENSE-2.0) 5 | 6 | # AndLinker 7 | 8 | [中文文档](README_CN.md) 9 | 10 | ## Introduction 11 | 12 | AndLinker is a IPC(Inter-Process Communication) library for Android, which combines the features of [AIDL][aidl] and [Retrofit][retrofit]. Allows IPC call seamlessly compose with [RxJava][rxjava] and [RxJava2][rxjava2] call adapters. Project design and partial code refer to the great project [Retrofit][retrofit]. 13 | 14 | ## Setup 15 | 16 | Add the `mavenCentral()` repository in your root `build.gradle`. 17 | ```groovy 18 | allprojects { 19 | repositories { 20 | mavenCentral() 21 | } 22 | } 23 | ``` 24 | 25 | Add the dependencies in your app level `build.gradle`. 26 | ```groovy 27 | dependencies { 28 | implementation 'com.codezjx.library:andlinker:0.9.1' 29 | } 30 | ``` 31 | 32 | ## Features 33 | 34 | - Define normal Java Interface instead of AIDL Interface 35 | - Generates the IPC implementation of the remote service interface like [Retrofit][retrofit] 36 | - Support call adapter: `Call`, [RxJava][rxjava] `Observable`, [RxJava2][rxjava2] `Observable` & `Flowable` 37 | - Support remote service callback 38 | - Support all AIDL data types 39 | - Support all AIDL directional tag, either `in`, `out`, or `inout` 40 | - Support the AIDL `oneway` keyword 41 | 42 | ## Getting Started 43 | 44 | Define a normal java Interface with `@RemoteInterface` annotation, and implements the interface. 45 | 46 | ```java 47 | @RemoteInterface 48 | public interface IRemoteService { 49 | 50 | int getPid(); 51 | 52 | void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 53 | double aDouble, String aString); 54 | } 55 | 56 | private final IRemoteService mRemoteService = new IRemoteService() { 57 | 58 | @Override 59 | public int getPid() { 60 | return android.os.Process.myPid(); 61 | } 62 | 63 | @Override 64 | public void basicTypes(int anInt, long aLong, boolean aBoolean, 65 | float aFloat, double aDouble, String aString) { 66 | // Does something 67 | } 68 | }; 69 | ``` 70 | 71 | In your server app, create the `AndLinkerBinder` object and register interface implementation above, then expose the linker binder to clients. 72 | 73 | ```java 74 | private AndLinkerBinder mLinkerBinder; 75 | 76 | public class RemoteService extends Service { 77 | @Override 78 | public void onCreate() { 79 | super.onCreate(); 80 | mLinkerBinder = AndLinkerBinder.Factory.newBinder(); 81 | mLinkerBinder.registerObject(mRemoteService); 82 | } 83 | 84 | @Override 85 | public IBinder onBind(Intent intent) { 86 | return mLinkerBinder; 87 | } 88 | } 89 | ``` 90 | 91 | In your client app, create the `AndLinker` object and generates an implementation of the `IRemoteService` interface. 92 | 93 | ```java 94 | public class BindingActivity extends Activity { 95 | 96 | private AndLinker mLinker; 97 | private IRemoteService mRemoteService; 98 | 99 | @Override 100 | protected void onCreate(@Nullable Bundle savedInstanceState) { 101 | super.onCreate(savedInstanceState); 102 | mLinker = new AndLinker.Builder(this) 103 | .packageName("com.example.andlinker") 104 | .action("com.example.andlinker.REMOTE_SERVICE_ACTION") 105 | .build(); 106 | mLinker.bind(); 107 | 108 | mRemoteService = mLinker.create(IRemoteService.class); 109 | } 110 | 111 | @Override 112 | protected void onDestroy() { 113 | super.onDestroy(); 114 | mLinker.unbind(); 115 | } 116 | } 117 | ``` 118 | 119 | Now your client app is ready, all methods from the created `IRemoteService` are IPC methods, call it directly! 120 | 121 | ```java 122 | int pid = mRemoteService.getPid(); 123 | mRemoteService.basicTypes(1, 2L, true, 3.0f, 4.0d, "str"); 124 | ``` 125 | 126 | ## Supported data types 127 | 128 | AndLinker supports all AIDL data types: 129 | - All primitive types in the Java programming language (such as `int`, `long`, `char`, `boolean`, and so on) 130 | - `String` 131 | - `CharSequence` 132 | - `Parcelable` 133 | - `List` (All elements in the List must be one of the supported data types in this list) 134 | - `Map` (All elements in the Map must be one of the supported data types in this list) 135 | 136 | ## Advanced 137 | 138 | ### Call Adapters 139 | You can modify the client side app's remote service interface, wrap the return type of the method. 140 | 141 | ```java 142 | @RemoteInterface 143 | public interface IRemoteService { 144 | 145 | Observable getPid(); 146 | 147 | Call basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 148 | double aDouble, String aString); 149 | } 150 | ``` 151 | 152 | Register the call adapter factory in `AndLinker.Builder`, the remaining steps are consistent with [Retrofit][retrofit]. 153 | 154 | ```java 155 | new AndLinker.Builder(this) 156 | ... 157 | .addCallAdapterFactory(OriginalCallAdapterFactory.create()) // Basic 158 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // RxJava2 159 | .build(); 160 | ``` 161 | 162 | ### Deal with callbacks 163 | Define callback interface to receive callbacks from the remote service with `@RemoteInterface` annotation. 164 | 165 | ```java 166 | @RemoteInterface 167 | public interface IRemoteCallback { 168 | 169 | void onValueChange(int value); 170 | } 171 | ``` 172 | 173 | Use `@Callback` annotation for callback parameter. 174 | 175 | ```java 176 | void registerCallback(@Callback IRemoteCallback callback); 177 | ``` 178 | 179 | In your client app, implements the remote callback and register to `AndLinker`, and that's it! 180 | 181 | ```java 182 | private final IRemoteCallback mRemoteCallback = new IRemoteCallback() { 183 | @Override 184 | public void onValueChange(int value) { 185 | // Invoke when server side callback 186 | } 187 | }; 188 | mLinker.registerObject(mRemoteCallback); 189 | ``` 190 | 191 | ### Specify directional tag 192 | You can specify `@In`, `@Out`, or `@Inout` annotation for parameter, indicating which way the data goes, same as AIDL. 193 | 194 | ```java 195 | void directionalParamMethod(@In KeyEvent event, @Out int[] arr, @Inout Rect rect); 196 | ``` 197 | 198 | >**Caution**: 199 | >- All non-primitive parameters require a directional annotation indicating which way the data goes. Either `@In`, `@Out`, or `@Inout`. Primitives are `@In` by default, and cannot be otherwise. 200 | >- Parcelable parameter with `@Out` or `@Inout` annotation must implements from `SuperParcelable`, or you must add method `public void readFromParcel(Parcel in)` by yourself. 201 | 202 | ### Use `@OneWay` annotation 203 | You can use `@OneWay` for a method which modifies the behavior of remote calls. When used, a remote call does not block, it simply sends the transaction data and immediately returns, same as AIDL. 204 | 205 | ```java 206 | @OneWay 207 | void onewayMethod(String msg); 208 | ``` 209 | 210 | ## Proguard Configuration 211 | 212 | Add following rules to `proguard-rules.pro` file, keep classes that will be serialized/deserialized over AndLinker. 213 | ``` 214 | -keep class com.example.andlinker.model.** { 215 | public void readFromParcel(android.os.Parcel); 216 | } 217 | ``` 218 | 219 | ## Feedback 220 | 221 | Any issues or PRs are welcome! 222 | 223 | ## License 224 | 225 | Copyright 2018 codezjx 226 | 227 | Licensed under the Apache License, Version 2.0 (the "License"); 228 | you may not use this file except in compliance with the License. 229 | You may obtain a copy of the License at 230 | 231 | http://www.apache.org/licenses/LICENSE-2.0 232 | 233 | Unless required by applicable law or agreed to in writing, software 234 | distributed under the License is distributed on an "AS IS" BASIS, 235 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 236 | See the License for the specific language governing permissions and 237 | limitations under the License. 238 | 239 | 240 | [retrofit]: https://github.com/square/retrofit 241 | [rxjava]: https://github.com/ReactiveX/RxJava/tree/1.x 242 | [rxjava2]: https://github.com/ReactiveX/RxJava/tree/2.x 243 | [aidl]: https://developer.android.com/guide/components/aidl.html -------------------------------------------------------------------------------- /README_CN.md: -------------------------------------------------------------------------------- 1 | 2 | ## 简介 3 | 4 | AndLinker是一款Android上的IPC (进程间通信) 库,结合了[AIDL][aidl]和[Retrofit][retrofit]的诸多特性,且可以与[RxJava][rxjava]和[RxJava2][rxjava2]的Call Adapters无缝结合使用。项目的设计与部分代码参考了伟大的[Retrofit][retrofit]项目。 5 | 6 | ## 配置 7 | 8 | 在项目根目录的`build.gradle`中添加`mavenCentral()`仓库 9 | ```groovy 10 | allprojects { 11 | repositories { 12 | mavenCentral() 13 | } 14 | } 15 | ``` 16 | 17 | 在App的`build.gradle`中添加如下依赖 18 | ```groovy 19 | dependencies { 20 | implementation 'com.codezjx.library:andlinker:0.9.1' 21 | } 22 | ``` 23 | 24 | ## 功能特性 25 | 26 | - 以普通Java接口代替AIDL接口 27 | - 像[Retrofit][retrofit]一样生成远程服务接口的IPC实现 28 | - 支持的Call Adapters:`Call`,[RxJava][rxjava] `Observable`,[RxJava2][rxjava2] `Observable` & `Flowable` 29 | - 支持远程服务回调机制 30 | - 支持AIDL的所有数据类型 31 | - 支持AIDL的所有数据定向tag:`in`,`out`,`inout` 32 | - 支持AIDL的`oneway`关键字 33 | 34 | ## 快速开始 35 | 36 | 使用注解`@RemoteInterface`修饰远程服务接口`IRemoteService`,并实现它 37 | 38 | ```java 39 | @RemoteInterface 40 | public interface IRemoteService { 41 | 42 | int getPid(); 43 | 44 | void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 45 | double aDouble, String aString); 46 | } 47 | 48 | private final IRemoteService mRemoteService = new IRemoteService() { 49 | 50 | @Override 51 | public int getPid() { 52 | return android.os.Process.myPid(); 53 | } 54 | 55 | @Override 56 | public void basicTypes(int anInt, long aLong, boolean aBoolean, 57 | float aFloat, double aDouble, String aString) { 58 | // Does something 59 | } 60 | }; 61 | ``` 62 | 63 | 在服务端App中,创建`AndLinkerBinder`对象,并注册上面的接口实现。然后在`onBind()`方法中返回,暴露给客户端 64 | 65 | ```java 66 | private AndLinkerBinder mLinkerBinder; 67 | 68 | public class RemoteService extends Service { 69 | @Override 70 | public void onCreate() { 71 | super.onCreate(); 72 | mLinkerBinder = AndLinkerBinder.Factory.newBinder(); 73 | mLinkerBinder.registerObject(mRemoteService); 74 | } 75 | 76 | @Override 77 | public IBinder onBind(Intent intent) { 78 | return mLinkerBinder; 79 | } 80 | } 81 | ``` 82 | 83 | 在客户端App中,通过`Builder`创建`AndLinker`对象,并通过`create()`方法生成一个`IRemoteService`远程接口的IPC实现 84 | 85 | ```java 86 | public class BindingActivity extends Activity { 87 | 88 | private AndLinker mLinker; 89 | private IRemoteService mRemoteService; 90 | 91 | @Override 92 | protected void onCreate(@Nullable Bundle savedInstanceState) { 93 | super.onCreate(savedInstanceState); 94 | mLinker = new AndLinker.Builder(this) 95 | .packageName("com.example.andlinker") 96 | .action("com.example.andlinker.REMOTE_SERVICE_ACTION") 97 | .build(); 98 | mLinker.bind(); 99 | 100 | mRemoteService = mLinker.create(IRemoteService.class); 101 | } 102 | 103 | @Override 104 | protected void onDestroy() { 105 | super.onDestroy(); 106 | mLinker.unbind(); 107 | } 108 | } 109 | ``` 110 | 111 | 一切就绪,现在`mRemoteService`对象中的所有方法都是IPC方法,直接调用即可 112 | 113 | ```java 114 | int pid = mRemoteService.getPid(); 115 | mRemoteService.basicTypes(1, 2L, true, 3.0f, 4.0d, "str"); 116 | ``` 117 | 118 | ## 支持数据类型 119 | 120 | AndLinker支持AIDL所有数据类型: 121 | - Java语言中的所有原始类型 (如:`int`,`long`,`char`,`boolean`,等等) 122 | - `String` 123 | - `CharSequence` 124 | - `Parcelable` 125 | - `List` (List中的所有元素必须是此列表中支持的数据类型) 126 | - `Map` (Map中的所有元素必须是此列表中支持的数据类型) 127 | 128 | ## 进阶使用 129 | 130 | ### Call Adapters 131 | 在客户端App中,你可以copy并修改远程服务接口,包装方法的返回值 132 | 133 | ```java 134 | @RemoteInterface 135 | public interface IRemoteService { 136 | 137 | Observable getPid(); 138 | 139 | Call basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 140 | double aDouble, String aString); 141 | } 142 | ``` 143 | 144 | 在`AndLinker.Builder`中注册对应的Call Adapter Factory,剩下的步骤基本和[Retrofit][retrofit]一致,不再赘述 145 | 146 | ```java 147 | new AndLinker.Builder(this) 148 | ... 149 | .addCallAdapterFactory(OriginalCallAdapterFactory.create()) // Basic 150 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // RxJava2 151 | .build(); 152 | ``` 153 | 154 | ### 处理远程服务接口回调 155 | 使用`@RemoteInterface`注解修饰远程服务回调接口`IRemoteCallback` 156 | 157 | ```java 158 | @RemoteInterface 159 | public interface IRemoteCallback { 160 | 161 | void onValueChange(int value); 162 | } 163 | ``` 164 | 165 | 在远程方法中使用`@Callback`注解修饰callback参数 166 | 167 | ```java 168 | void registerCallback(@Callback IRemoteCallback callback); 169 | ``` 170 | 171 | 在客户端App中,实现上面定义的远程服务回调接口`IRemoteCallback`,并且注册到`AndLinker`中,就是这么简单 172 | 173 | ```java 174 | private final IRemoteCallback mRemoteCallback = new IRemoteCallback() { 175 | @Override 176 | public void onValueChange(int value) { 177 | // Invoke when server side callback 178 | } 179 | }; 180 | mLinker.registerObject(mRemoteCallback); 181 | ``` 182 | 183 | ### 指定数据定向tag 184 | 你可以为远程方法的参数指定`@In`,`@Out`,或者`@Inout`注解,它标记了数据在底层Binder中的流向,跟AIDL中的用法一致 185 | 186 | ```java 187 | void directionalParamMethod(@In KeyEvent event, @Out int[] arr, @Inout Rect rect); 188 | ``` 189 | 190 | >**注意**: 191 | >- 所有非原始类型必须指定数据定向tag:`@In`,`@Out`,或者`@Inout`,用来标记数据的流向。原始类型默认是`@In`类型,并且不能指定其他值。 192 | >- 使用`@Out`或者`@Inout`修饰的Parcelable参数必须实现`SuperParcelable`接口,否则你必须手动添加此方法`public void readFromParcel(Parcel in)`。 193 | 194 | ### 使用`@OneWay`注解 195 | 你可以在远程方法上使用`@OneWay`注解,这会修改远程方法调用的行为。当使用它时,远程方法调用不会堵塞,它只是简单的发送数据并立即返回,跟AIDL中的用法一致 196 | 197 | ```java 198 | @OneWay 199 | void onewayMethod(String msg); 200 | ``` 201 | 202 | ## Proguard配置 203 | 204 | 在`proguard-rules.pro`文件中添加如下混淆规则,将需要序列化/反序列化的model类给keep掉 205 | ``` 206 | -keep class com.example.andlinker.model.** { 207 | public void readFromParcel(android.os.Parcel); 208 | } 209 | ``` 210 | 211 | ## 反馈 212 | 213 | 欢迎各位提issues和PRs! 214 | 215 | ## License 216 | 217 | Copyright 2018 codezjx 218 | 219 | Licensed under the Apache License, Version 2.0 (the "License"); 220 | you may not use this file except in compliance with the License. 221 | You may obtain a copy of the License at 222 | 223 | http://www.apache.org/licenses/LICENSE-2.0 224 | 225 | Unless required by applicable law or agreed to in writing, software 226 | distributed under the License is distributed on an "AS IS" BASIS, 227 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 228 | See the License for the specific language governing permissions and 229 | limitations under the License. 230 | 231 | 232 | [retrofit]: https://github.com/square/retrofit 233 | [rxjava]: https://github.com/ReactiveX/RxJava/tree/1.x 234 | [rxjava2]: https://github.com/ReactiveX/RxJava/tree/2.x 235 | [aidl]: https://developer.android.com/guide/components/aidl.html -------------------------------------------------------------------------------- /andlinker/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /andlinker/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.library' 2 | 3 | android { 4 | compileSdkVersion versions.compileSdk 5 | 6 | defaultConfig { 7 | minSdkVersion versions.minSdk 8 | targetSdkVersion versions.targetSdk 9 | versionCode 1 10 | versionName "1.0" 11 | } 12 | 13 | buildTypes { 14 | release { 15 | minifyEnabled false 16 | consumerProguardFiles 'proguard-rules.pro' 17 | } 18 | } 19 | 20 | } 21 | 22 | dependencies { 23 | compileOnly deps.rx.java 24 | compileOnly deps.rx.java2 25 | } 26 | 27 | apply from: 'properties.gradle' 28 | apply from: 'maven-publish.gradle' -------------------------------------------------------------------------------- /andlinker/maven-publish.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'maven' 2 | apply plugin: 'signing' 3 | 4 | // Android libraries 5 | task sourcesJar(type: Jar) { 6 | classifier = 'sources' 7 | from android.sourceSets.main.java.srcDirs 8 | } 9 | 10 | task javadoc(type: Javadoc) { 11 | // https://github.com/novoda/bintray-release/issues/71 12 | excludes = ['**/*.kt'] // < ---- Exclude all kotlin files from javadoc file. 13 | source = android.sourceSets.main.java.srcDirs 14 | classpath += project.files(android.getBootClasspath().join(File.pathSeparator)) 15 | options.encoding = "UTF-8" 16 | options.charSet = "UTF-8" 17 | } 18 | 19 | tasks.withType(JavaCompile) { 20 | options.encoding = "UTF-8" 21 | } 22 | 23 | tasks.withType(Javadoc) { 24 | options.encoding = "UTF-8" 25 | } 26 | 27 | task javadocJar(type: Jar, dependsOn: javadoc) { 28 | classifier = 'javadoc' 29 | from javadoc.destinationDir 30 | } 31 | 32 | // Add javadoc/source jar tasks as artifacts 33 | artifacts { 34 | archives javadocJar 35 | archives sourcesJar 36 | } 37 | 38 | // Signing artifacts 39 | signing { 40 | required { gradle.taskGraph.hasTask("uploadArchives") } 41 | sign configurations.archives 42 | } 43 | 44 | uploadArchives { 45 | repositories { 46 | mavenDeployer { 47 | beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) } 48 | 49 | repository(url: "https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") { 50 | authentication(userName: ossrhUsername, password: ossrhPassword) 51 | } 52 | 53 | snapshotRepository(url: "https://s01.oss.sonatype.org/content/repositories/snapshots/") { 54 | authentication(userName: ossrhUsername, password: ossrhPassword) 55 | } 56 | 57 | pom.groupId = publishedGroupId 58 | pom.artifactId = artifact 59 | pom.version = libraryVersion 60 | 61 | pom.project { 62 | packaging 'aar' 63 | 64 | name libraryName 65 | description libraryDescription 66 | url siteUrl 67 | 68 | scm { 69 | connection gitUrl 70 | developerConnection gitUrl 71 | url siteUrl 72 | } 73 | 74 | licenses { 75 | license { 76 | name licenseName 77 | url licenseUrl 78 | } 79 | } 80 | 81 | developers { 82 | developer { 83 | id developerId 84 | name developerName 85 | email developerEmail 86 | } 87 | } 88 | } 89 | } 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /andlinker/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | 23 | -dontwarn com.codezjx.andlinker.adapter.** 24 | -keep class * implements com.codezjx.andlinker.SuperParcelable { 25 | public void readFromParcel(android.os.Parcel); 26 | } 27 | -keep @com.codezjx.andlinker.annotation.RemoteInterface class * { 28 | ; 29 | } -------------------------------------------------------------------------------- /andlinker/properties.gradle: -------------------------------------------------------------------------------- 1 | ext { 2 | publishedGroupId = 'com.codezjx.library' 3 | artifact = 'andlinker' 4 | libraryVersion = '0.9.1' 5 | 6 | libraryName = 'AndLinker' 7 | libraryDescription = 'AndLinker is a IPC library for Android, which combines the features of AIDL and Retrofit. Allows IPC call seamlessly compose with rxjava and rxjava2 call adapters.' 8 | 9 | siteUrl = 'https://github.com/codezjx/AndLinker' 10 | gitUrl = 'https://github.com/codezjx/AndLinker.git' 11 | 12 | developerId = 'codezjx' 13 | developerName = 'codezjx' 14 | developerEmail = 'code.zjx@gmail.com' 15 | 16 | licenseName = 'The Apache Software License, Version 2.0' 17 | licenseUrl = 'http://www.apache.org/licenses/LICENSE-2.0.txt' 18 | allLicenses = ["Apache-2.0"] 19 | } -------------------------------------------------------------------------------- /andlinker/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 3 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/AndLinker.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.content.ComponentName; 4 | import android.content.Context; 5 | import android.content.Intent; 6 | import android.content.ServiceConnection; 7 | import android.os.IBinder; 8 | import android.os.RemoteException; 9 | 10 | import com.codezjx.andlinker.adapter.DefaultCallAdapterFactory; 11 | 12 | import java.lang.annotation.Annotation; 13 | import java.lang.reflect.InvocationHandler; 14 | import java.lang.reflect.Method; 15 | import java.lang.reflect.Proxy; 16 | import java.lang.reflect.Type; 17 | import java.util.ArrayList; 18 | import java.util.List; 19 | import java.util.Map; 20 | import java.util.concurrent.ConcurrentHashMap; 21 | 22 | import static com.codezjx.andlinker.Utils.checkNotNull; 23 | 24 | /** 25 | * AndLinker adapts a Java interface to IPC calls by using annotations on the declared methods to 26 | * define how requests are made. Create instances using {@linkplain Builder 27 | * the builder} and pass your interface to {@link #create} to generate an implementation. 28 | */ 29 | public final class AndLinker { 30 | 31 | private static final String TAG = "AndLinker"; 32 | 33 | private final Map serviceMethodCache = new ConcurrentHashMap<>(); 34 | private ServiceConnection mServiceConnection; 35 | private Invoker mInvoker; 36 | private Context mContext; 37 | private String mPackageName; 38 | private String mAction; 39 | private String mClassName; 40 | private List mAdapterFactories; 41 | private Dispatcher mDispatcher; 42 | private ITransfer mTransferService; 43 | private ICallback mCallback; 44 | private BindCallback mBindCallback; 45 | 46 | private AndLinker(Context context, String packageName, String action, String className, List adapterFactories) { 47 | mContext = context; 48 | mPackageName = packageName; 49 | mAction = action; 50 | mClassName = className; 51 | mInvoker = new Invoker(); 52 | mAdapterFactories = adapterFactories; 53 | mDispatcher = new Dispatcher(); 54 | mServiceConnection = createServiceConnection(); 55 | mCallback = createCallback(); 56 | } 57 | 58 | /** 59 | * Create an implementation defined by the remote service interface. 60 | */ 61 | @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. 62 | public T create(final Class service) { 63 | Utils.validateServiceInterface(service); 64 | return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service }, 65 | new InvocationHandler() { 66 | @Override 67 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 68 | // If the method is a method from Object then defer to normal invocation. 69 | if (method.getDeclaringClass() == Object.class) { 70 | return method.invoke(this, args); 71 | } 72 | ServiceMethod serviceMethod = loadServiceMethod(method, service.getSimpleName()); 73 | RemoteCall remoteCall = new RemoteCall(mTransferService, serviceMethod, args, mDispatcher); 74 | return serviceMethod.getCallAdapter().adapt(remoteCall); 75 | } 76 | }); 77 | } 78 | 79 | /** 80 | * Connect to the remote service. 81 | */ 82 | public void bind() { 83 | if (isBind()) { 84 | Logger.d(TAG, "Already bind, just return."); 85 | return; 86 | } 87 | Intent intent = new Intent(); 88 | if (!Utils.isStringBlank(mAction)) { 89 | intent.setAction(mAction); 90 | } else if (!Utils.isStringBlank(mClassName)) { 91 | intent.setClassName(mPackageName, mClassName); 92 | } 93 | // After android 5.0+, service Intent must be explicit. 94 | intent.setPackage(mPackageName); 95 | mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE); 96 | } 97 | 98 | /** 99 | * Disconnect from the remote service. 100 | */ 101 | public void unbind() { 102 | if (!isBind()) { 103 | Logger.d(TAG, "Already unbind, just return."); 104 | return; 105 | } 106 | mContext.unbindService(mServiceConnection); 107 | handleUnBind(true); 108 | } 109 | 110 | /** 111 | * Register client interface implementation called by remote service. 112 | */ 113 | public void registerObject(Object target) { 114 | mInvoker.registerObject(target); 115 | } 116 | 117 | /** 118 | * Unregister client interface implementation. 119 | */ 120 | public void unRegisterObject(Object target) { 121 | mInvoker.unRegisterObject(target); 122 | } 123 | 124 | /** 125 | * Set callback to be invoked when linker is bind or unBind. 126 | */ 127 | public void setBindCallback(BindCallback bindCallback) { 128 | mBindCallback = bindCallback; 129 | } 130 | 131 | /** 132 | * Return the remote service bind state. 133 | */ 134 | public boolean isBind() { 135 | return mTransferService != null; 136 | } 137 | 138 | CallAdapter findCallAdapter(Type returnType, Annotation[] annotations) { 139 | checkNotNull(returnType, "returnType == null"); 140 | checkNotNull(annotations, "annotations == null"); 141 | 142 | for (int i = 0, count = mAdapterFactories.size(); i < count; i++) { 143 | CallAdapter adapter = mAdapterFactories.get(i).get(returnType, annotations); 144 | if (adapter != null) { 145 | return adapter; 146 | } 147 | } 148 | 149 | return DefaultCallAdapterFactory.INSTANCE.get(returnType, annotations); 150 | } 151 | 152 | private ServiceConnection createServiceConnection() { 153 | return new ServiceConnection() { 154 | @Override 155 | public void onServiceConnected(ComponentName name, IBinder service) { 156 | Logger.d(TAG, "onServiceConnected:" + name + " service:" + service); 157 | mTransferService = ITransfer.Stub.asInterface(service); 158 | try { 159 | mTransferService.register(mCallback); 160 | } catch (RemoteException e) { 161 | e.printStackTrace(); 162 | } 163 | fireOnBind(); 164 | } 165 | 166 | @Override 167 | public void onServiceDisconnected(ComponentName name) { 168 | Logger.d(TAG, "onServiceDisconnected:" + name); 169 | handleUnBind(false); 170 | } 171 | }; 172 | } 173 | 174 | private void handleUnBind(boolean unRegister) { 175 | Logger.d(TAG, "handleUnBind:" + unRegister); 176 | if (mTransferService == null) { 177 | Logger.e(TAG, "Error occur, TransferService was null when service disconnected."); 178 | fireOnUnBind(); 179 | return; 180 | } 181 | if (unRegister) { 182 | try { 183 | mTransferService.unRegister(mCallback); 184 | } catch (RemoteException e) { 185 | e.printStackTrace(); 186 | } 187 | } 188 | mTransferService = null; 189 | fireOnUnBind(); 190 | } 191 | 192 | private void fireOnBind() { 193 | if (mBindCallback != null) { 194 | mBindCallback.onBind(); 195 | } 196 | } 197 | 198 | private void fireOnUnBind() { 199 | if (mBindCallback != null) { 200 | mBindCallback.onUnBind(); 201 | } 202 | } 203 | 204 | private ICallback createCallback() { 205 | return new ICallback.Stub() { 206 | @Override 207 | public Response callback(Request request) throws RemoteException { 208 | Logger.d(TAG, "Receive callback in client:" + request.toString()); 209 | return mInvoker.invoke(request); 210 | } 211 | }; 212 | } 213 | 214 | private ServiceMethod loadServiceMethod(Method method, String clsName) { 215 | ServiceMethod result = serviceMethodCache.get(method); 216 | if (result != null) { 217 | return result; 218 | } 219 | 220 | synchronized (serviceMethodCache) { 221 | result = serviceMethodCache.get(method); 222 | if (result == null) { 223 | result = new ServiceMethod.Builder(this, method, clsName).build(); 224 | serviceMethodCache.put(method, result); 225 | } 226 | } 227 | return result; 228 | } 229 | 230 | /** 231 | * Method to enable or disable internal logger 232 | */ 233 | public static void enableLogger(boolean enable) { 234 | Logger.sEnable = enable; 235 | } 236 | 237 | /** 238 | * Builder to create a new {@link AndLinker} instance. 239 | */ 240 | public static final class Builder { 241 | 242 | private Context mContext; 243 | private String mPackageName; 244 | private String mAction; 245 | private String mClassName; 246 | private List mAdapterFactories = new ArrayList<>(); 247 | 248 | public Builder(Context context) { 249 | mContext = context; 250 | } 251 | 252 | /** 253 | * Set the remote service package name. 254 | */ 255 | public Builder packageName(String packageName) { 256 | mPackageName = packageName; 257 | return this; 258 | } 259 | 260 | /** 261 | * Set the action to bind the remote service. 262 | */ 263 | public Builder action(String action) { 264 | mAction = action; 265 | return this; 266 | } 267 | 268 | /** 269 | * Set the class name of the remote service. 270 | */ 271 | public Builder className(String className) { 272 | mClassName = className; 273 | return this; 274 | } 275 | 276 | /** 277 | * Add a call adapter factory for supporting service method return types other than {@link Call}. 278 | */ 279 | public Builder addCallAdapterFactory(CallAdapter.Factory factory) { 280 | mAdapterFactories.add(checkNotNull(factory, "factory == null")); 281 | return this; 282 | } 283 | 284 | /** 285 | * Create the {@link AndLinker} instance using the configured values. 286 | */ 287 | public AndLinker build() { 288 | if (Utils.isStringBlank(mPackageName)) { 289 | throw new IllegalStateException("Package name required."); 290 | } 291 | if (Utils.isStringBlank(mAction) && Utils.isStringBlank(mClassName)) { 292 | throw new IllegalStateException("You must set one of the action or className."); 293 | } 294 | return new AndLinker(mContext, mPackageName, mAction, mClassName, mAdapterFactories); 295 | } 296 | } 297 | 298 | /** 299 | * Interface definition for a callback to be invoked when linker is bind or unBind to the service. 300 | */ 301 | public interface BindCallback { 302 | 303 | /** 304 | * Called when a connection to the remote service has been established, now you can execute the remote call. 305 | */ 306 | void onBind(); 307 | 308 | /** 309 | * Called when a connection to the remote service has been lost, any remote call will not execute. 310 | */ 311 | void onUnBind(); 312 | } 313 | } 314 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/AndLinkerBinder.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.IBinder; 4 | 5 | /** 6 | * AndLinker {@link IBinder} object to return in {@link android.app.Service#onBind(android.content.Intent)} method. 7 | */ 8 | public interface AndLinkerBinder extends IBinder { 9 | 10 | /** 11 | * Register service interface implementation. 12 | */ 13 | void registerObject(Object target); 14 | 15 | /** 16 | * Unregister service interface implementation. 17 | */ 18 | void unRegisterObject(Object target); 19 | 20 | /** 21 | * {@link AndLinkerBinder} factory class. 22 | */ 23 | final class Factory { 24 | 25 | private Factory() { 26 | 27 | } 28 | 29 | /** 30 | * Factory method to create the {@link AndLinkerBinder} impl instance. 31 | */ 32 | public static AndLinkerBinder newBinder() { 33 | // Return inner package access LinkerBinder, prevent exposed. 34 | return new LinkerBinderImpl(); 35 | } 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/ArrayType.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import java.lang.reflect.Array; 7 | 8 | /** 9 | * Created by codezjx on 2017/11/28.
10 | */ 11 | interface ArrayType extends OutType { 12 | 13 | T newInstance(int length); 14 | 15 | final class ByteArrayType implements ArrayType { 16 | 17 | @Override 18 | public void writeToParcel(Parcel dest, int flags, byte[] val) { 19 | dest.writeByteArray(val); 20 | } 21 | 22 | @Override 23 | public byte[] createFromParcel(Parcel in) { 24 | return in.createByteArray(); 25 | } 26 | 27 | @Override 28 | public void readFromParcel(Parcel in, byte[] val) { 29 | in.readByteArray(val); 30 | } 31 | 32 | @Override 33 | public byte[] newInstance(int length) { 34 | return new byte[length]; 35 | } 36 | } 37 | 38 | final class ShortArrayType implements ArrayType { 39 | 40 | @Override 41 | public void writeToParcel(Parcel dest, int flags, short[] val) { 42 | if (val != null) { 43 | int N = val.length; 44 | dest.writeInt(N); 45 | for (int i = 0; i < N; i++) { 46 | dest.writeInt(val[i]); 47 | } 48 | } else { 49 | dest.writeInt(-1); 50 | } 51 | } 52 | 53 | @Override 54 | public short[] createFromParcel(Parcel in) { 55 | int N = in.readInt(); 56 | if (N >= 0 && N <= (in.dataAvail() >> 2)) { 57 | short[] val = new short[N]; 58 | for (int i = 0; i < N; i++) { 59 | val[i] = (short) in.readInt(); 60 | } 61 | return val; 62 | } else { 63 | return null; 64 | } 65 | } 66 | 67 | @Override 68 | public void readFromParcel(Parcel in, short[] val) { 69 | int N = in.readInt(); 70 | if (N == val.length) { 71 | for (int i = 0; i < N; i++) { 72 | val[i] = (short) in.readInt(); 73 | } 74 | } else { 75 | throw new RuntimeException("bad array lengths"); 76 | } 77 | } 78 | 79 | @Override 80 | public short[] newInstance(int length) { 81 | return new short[length]; 82 | } 83 | } 84 | 85 | final class IntArrayType implements ArrayType { 86 | 87 | @Override 88 | public void writeToParcel(Parcel dest, int flags, int[] val) { 89 | dest.writeIntArray(val); 90 | } 91 | 92 | @Override 93 | public int[] createFromParcel(Parcel in) { 94 | return in.createIntArray(); 95 | } 96 | 97 | @Override 98 | public void readFromParcel(Parcel in, int[] val) { 99 | in.readIntArray(val); 100 | } 101 | 102 | @Override 103 | public int[] newInstance(int length) { 104 | return new int[length]; 105 | } 106 | } 107 | 108 | final class LongArrayType implements ArrayType { 109 | 110 | @Override 111 | public void writeToParcel(Parcel dest, int flags, long[] val) { 112 | dest.writeLongArray(val); 113 | } 114 | 115 | @Override 116 | public long[] createFromParcel(Parcel in) { 117 | return in.createLongArray(); 118 | } 119 | 120 | @Override 121 | public void readFromParcel(Parcel in, long[] val) { 122 | in.readLongArray(val); 123 | } 124 | 125 | @Override 126 | public long[] newInstance(int length) { 127 | return new long[length]; 128 | } 129 | } 130 | 131 | final class FloatArrayType implements ArrayType { 132 | 133 | @Override 134 | public void writeToParcel(Parcel dest, int flags, float[] val) { 135 | dest.writeFloatArray(val); 136 | } 137 | 138 | @Override 139 | public float[] createFromParcel(Parcel in) { 140 | return in.createFloatArray(); 141 | } 142 | 143 | @Override 144 | public void readFromParcel(Parcel in, float[] val) { 145 | in.readFloatArray(val); 146 | } 147 | 148 | @Override 149 | public float[] newInstance(int length) { 150 | return new float[length]; 151 | } 152 | } 153 | 154 | final class DoubleArrayType implements ArrayType { 155 | 156 | @Override 157 | public void writeToParcel(Parcel dest, int flags, double[] val) { 158 | dest.writeDoubleArray(val); 159 | } 160 | 161 | @Override 162 | public double[] createFromParcel(Parcel in) { 163 | return in.createDoubleArray(); 164 | } 165 | 166 | @Override 167 | public void readFromParcel(Parcel in, double[] val) { 168 | in.readDoubleArray(val); 169 | } 170 | 171 | @Override 172 | public double[] newInstance(int length) { 173 | return new double[length]; 174 | } 175 | } 176 | 177 | final class BooleanArrayType implements ArrayType { 178 | 179 | @Override 180 | public void writeToParcel(Parcel dest, int flags, boolean[] val) { 181 | dest.writeBooleanArray(val); 182 | } 183 | 184 | @Override 185 | public boolean[] createFromParcel(Parcel in) { 186 | return in.createBooleanArray(); 187 | } 188 | 189 | @Override 190 | public void readFromParcel(Parcel in, boolean[] val) { 191 | in.readBooleanArray(val); 192 | } 193 | 194 | @Override 195 | public boolean[] newInstance(int length) { 196 | return new boolean[length]; 197 | } 198 | } 199 | 200 | final class CharArrayType implements ArrayType { 201 | 202 | @Override 203 | public void writeToParcel(Parcel dest, int flags, char[] val) { 204 | dest.writeCharArray(val); 205 | } 206 | 207 | @Override 208 | public char[] createFromParcel(Parcel in) { 209 | return in.createCharArray(); 210 | } 211 | 212 | @Override 213 | public void readFromParcel(Parcel in, char[] val) { 214 | in.readCharArray(val); 215 | } 216 | 217 | @Override 218 | public char[] newInstance(int length) { 219 | return new char[length]; 220 | } 221 | } 222 | 223 | final class StringArrayType implements ArrayType { 224 | 225 | @Override 226 | public void writeToParcel(Parcel dest, int flags, String[] val) { 227 | dest.writeStringArray(val); 228 | } 229 | 230 | @Override 231 | public String[] createFromParcel(Parcel in) { 232 | return in.createStringArray(); 233 | } 234 | 235 | @Override 236 | public void readFromParcel(Parcel in, String[] val) { 237 | in.readStringArray(val); 238 | } 239 | 240 | @Override 241 | public String[] newInstance(int length) { 242 | return new String[length]; 243 | } 244 | } 245 | 246 | final class CharSequenceArrayType implements ArrayType { 247 | 248 | @Override 249 | public void writeToParcel(Parcel dest, int flags, CharSequence[] val) { 250 | writeCharSequenceArray(dest, val); 251 | } 252 | 253 | @Override 254 | public CharSequence[] createFromParcel(Parcel in) { 255 | return readCharSequenceArray(in); 256 | } 257 | 258 | @Override 259 | public void readFromParcel(Parcel in, CharSequence[] val) { 260 | int N = in.readInt(); 261 | if (N == val.length) { 262 | for (int i = 0; i < N; i++) { 263 | val[i] = Type.CharSequenceType.readCharSequence(in); 264 | } 265 | } else { 266 | throw new RuntimeException("bad array lengths"); 267 | } 268 | } 269 | 270 | @Override 271 | public CharSequence[] newInstance(int length) { 272 | return new CharSequence[length]; 273 | } 274 | 275 | private void writeCharSequenceArray(Parcel dest, CharSequence[] val) { 276 | if (val != null) { 277 | int N = val.length; 278 | dest.writeInt(N); 279 | for (int i = 0; i < N; i++) { 280 | Type.CharSequenceType.writeCharSequence(dest, val[i]); 281 | } 282 | } else { 283 | dest.writeInt(-1); 284 | } 285 | } 286 | 287 | private CharSequence[] readCharSequenceArray(Parcel in) { 288 | CharSequence[] array = null; 289 | 290 | int length = in.readInt(); 291 | if (length >= 0) { 292 | array = new CharSequence[length]; 293 | 294 | for (int i = 0 ; i < length ; i++) { 295 | array[i] = Type.CharSequenceType.readCharSequence(in); 296 | } 297 | } 298 | 299 | return array; 300 | } 301 | } 302 | 303 | final class ParcelableArrayType implements ArrayType { 304 | 305 | @Override 306 | public void writeToParcel(Parcel dest, int flags, Parcelable[] val) { 307 | dest.writeString(val.getClass().getComponentType().getName()); 308 | dest.writeParcelableArray(val, flags); 309 | } 310 | 311 | @Override 312 | public Parcelable[] createFromParcel(Parcel in) { 313 | String componentType = in.readString(); 314 | Object obj = null; 315 | try { 316 | Class cls = Class.forName(componentType); 317 | obj = createTypedArray(in, cls); 318 | } catch (ClassNotFoundException e) { 319 | e.printStackTrace(); 320 | } 321 | return (Parcelable[]) obj; 322 | } 323 | 324 | @Override 325 | public void readFromParcel(Parcel in, Parcelable[] val) { 326 | // Just read and do nothing, because we don't need component type here 327 | in.readString(); 328 | int N = in.readInt(); 329 | if (N == val.length) { 330 | for (int i = 0; i < N; i++) { 331 | val[i] = in.readParcelable(getClass().getClassLoader()); 332 | } 333 | } else { 334 | throw new RuntimeException("bad array lengths"); 335 | } 336 | } 337 | 338 | @Override 339 | public Parcelable[] newInstance(int length) { 340 | return new Parcelable[length]; 341 | } 342 | 343 | private T[] createTypedArray(Parcel in, Class cls) { 344 | int N = in.readInt(); 345 | if (N < 0) { 346 | return null; 347 | } 348 | T[] arr = (T[]) Array.newInstance(cls, N); 349 | for (int i = 0; i < N; i++) { 350 | arr[i] = in.readParcelable(cls.getClassLoader()); 351 | } 352 | return arr; 353 | } 354 | } 355 | 356 | } 357 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/BaseTypeWrapper.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | /** 4 | * Created by codezjx on 2017/11/19.
5 | */ 6 | interface BaseTypeWrapper extends SuperParcelable { 7 | 8 | int TYPE_EMPTY = 0; 9 | 10 | // Primitives 11 | int TYPE_BYTE = 1; 12 | int TYPE_SHORT = 2; 13 | int TYPE_INT = 3; 14 | int TYPE_LONG = 4; 15 | int TYPE_FLOAT = 5; 16 | int TYPE_DOUBLE = 6; 17 | int TYPE_BOOLEAN = 7; 18 | int TYPE_CHAR = 8; 19 | 20 | // Primitive Arrays 21 | int TYPE_BYTEARRAY = 9; 22 | int TYPE_SHORTARRAY = 10; 23 | int TYPE_INTARRAY = 11; 24 | int TYPE_LONGARRAY = 12; 25 | int TYPE_FLOATARRAY = 13; 26 | int TYPE_DOUBLEARRAY = 14; 27 | int TYPE_BOOLEANARRAY = 15; 28 | int TYPE_CHARARRAY = 16; 29 | 30 | // Other 31 | int TYPE_STRING = 17; 32 | int TYPE_STRINGARRAY = 18; 33 | int TYPE_CHARSEQUENCE = 19; 34 | int TYPE_CHARSEQUENCEARRAY = 20; 35 | int TYPE_PARCELABLE = 21; 36 | int TYPE_PARCELABLEARRAY = 22; 37 | int TYPE_LIST = 23; 38 | int TYPE_MAP = 24; 39 | int TYPE_CALLBACK = 25; 40 | 41 | int getType(); 42 | 43 | Object getParam(); 44 | } 45 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Call.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | /** 4 | * An invocation of a remote method that sends a request to host and returns a response. 5 | */ 6 | public interface Call { 7 | 8 | /** 9 | * Synchronously send the request and return its response. 10 | */ 11 | T execute(); 12 | 13 | /** 14 | * Asynchronously send the request and notify when response return. 15 | * @param callback The callback to notify. 16 | */ 17 | void enqueue(Callback callback); 18 | 19 | /** 20 | * Returns true if this call has been either {@linkplain #execute() executed} or {@linkplain #enqueue(Callback) enqueued}. 21 | */ 22 | boolean isExecuted(); 23 | 24 | /** 25 | * Cancel this call. If the call has not yet been executed it never will be. 26 | */ 27 | void cancel(); 28 | 29 | /** 30 | * True if {@link #cancel()} was called. 31 | */ 32 | boolean isCanceled(); 33 | 34 | } 35 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/CallAdapter.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import java.lang.annotation.Annotation; 4 | import java.lang.reflect.Type; 5 | 6 | /** 7 | * Adapts a {@link Call} with response type {@code R} into the type of {@code T}. Instances are 8 | * created by {@linkplain Factory factory} which is {@linkplain AndLinker.Builder#addCallAdapterFactory(Factory) installed} 9 | * into the {@link AndLinker} instance. 10 | */ 11 | public interface CallAdapter { 12 | 13 | /** 14 | * Returns an instance of {@code T} which delegates to {@code call}. 15 | */ 16 | T adapt(Call call); 17 | 18 | /** 19 | * Creates {@link CallAdapter} instances based on the return type of {@linkplain 20 | * AndLinker#create(Class) the service interface} methods. 21 | */ 22 | abstract class Factory { 23 | 24 | /** 25 | * Returns a call adapter for interface methods that return {@code returnType}, or null if it 26 | * cannot be handled by this factory. 27 | */ 28 | public abstract CallAdapter get(Type returnType, Annotation[] annotations); 29 | 30 | protected static Class getRawType(Type type) { 31 | return Utils.getRawType(type); 32 | } 33 | 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Callback.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | /** 4 | * Interface definition for a callback to be invoked when execute {@linkplain Call#enqueue(Callback) asynchronously call}. 5 | * By default callbacks are executed on the application's main (UI) thread. 6 | */ 7 | public interface Callback { 8 | 9 | /** 10 | * Invoked for a received response. 11 | */ 12 | void onResponse(Call call, T response); 13 | 14 | /** 15 | * Invoked when a remote exception occurred. 16 | */ 17 | void onFailure(Call call, Throwable t); 18 | 19 | } 20 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/CallbackTypeWrapper.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | /** 6 | * Created by codezjx on 2017/11/18.
7 | */ 8 | final class CallbackTypeWrapper implements BaseTypeWrapper { 9 | 10 | private String mClassName; 11 | 12 | CallbackTypeWrapper(String className) { 13 | mClassName = className; 14 | } 15 | 16 | String getClassName() { 17 | return mClassName; 18 | } 19 | 20 | @Override 21 | public int getType() { 22 | return TYPE_CALLBACK; 23 | } 24 | 25 | @Override 26 | public Object getParam() { 27 | return null; 28 | } 29 | 30 | @Override 31 | public int describeContents() { 32 | return 0; 33 | } 34 | 35 | @Override 36 | public void writeToParcel(Parcel dest, int flags) { 37 | dest.writeString(mClassName); 38 | } 39 | 40 | @Override 41 | public void readFromParcel(Parcel in) { 42 | mClassName = in.readString(); 43 | } 44 | 45 | private CallbackTypeWrapper(Parcel in) { 46 | readFromParcel(in); 47 | } 48 | 49 | public static final Creator CREATOR = new Creator() { 50 | @Override 51 | public CallbackTypeWrapper createFromParcel(Parcel source) { 52 | return new CallbackTypeWrapper(source); 53 | } 54 | 55 | @Override 56 | public CallbackTypeWrapper[] newArray(int size) { 57 | return new CallbackTypeWrapper[size]; 58 | } 59 | }; 60 | } 61 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Dispatcher.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import java.util.concurrent.ExecutorService; 4 | import java.util.concurrent.SynchronousQueue; 5 | import java.util.concurrent.ThreadFactory; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | 10 | /** 11 | * Created by codezjx on 2018/1/10.
12 | */ 13 | final class Dispatcher { 14 | 15 | private static final String THREAD_NAME = "Dispatcher Thread #"; 16 | private static final int KEEP_ALIVE_TIME_SECONDS = 60; 17 | private ExecutorService mExecutorService; 18 | 19 | Dispatcher() { 20 | 21 | } 22 | 23 | Dispatcher(ExecutorService executorService) { 24 | mExecutorService = executorService; 25 | } 26 | 27 | synchronized void enqueue(Runnable task) { 28 | if (mExecutorService == null) { 29 | mExecutorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 30 | KEEP_ALIVE_TIME_SECONDS, TimeUnit.SECONDS, 31 | new SynchronousQueue(), createFactory()); 32 | } 33 | mExecutorService.execute(task); 34 | } 35 | 36 | private ThreadFactory createFactory() { 37 | return new ThreadFactory() { 38 | private final AtomicInteger mCount = new AtomicInteger(1); 39 | 40 | @Override 41 | public Thread newThread(Runnable runnable) { 42 | Thread thread = new Thread(runnable, THREAD_NAME + mCount.getAndIncrement()); 43 | thread.setDaemon(false); 44 | return thread; 45 | } 46 | }; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/ICallback.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | interface ICallback extends android.os.IInterface { 4 | /** 5 | * Local-side IPC implementation stub class. 6 | */ 7 | abstract class Stub extends android.os.Binder implements ICallback { 8 | private static final String DESCRIPTOR = "com.codezjx.alinker.ICallback"; 9 | 10 | /** 11 | * Construct the stub at attach it to the interface. 12 | */ 13 | Stub() { 14 | this.attachInterface(this, DESCRIPTOR); 15 | } 16 | 17 | /** 18 | * Cast an IBinder object into an com.codezjx.alinker.ICallback interface, 19 | * generating a proxy if needed. 20 | */ 21 | static ICallback asInterface(android.os.IBinder obj) { 22 | if ((obj == null)) { 23 | return null; 24 | } 25 | android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); 26 | if (((iin != null) && (iin instanceof ICallback))) { 27 | return ((ICallback) iin); 28 | } 29 | return new Proxy(obj); 30 | } 31 | 32 | @Override 33 | public android.os.IBinder asBinder() { 34 | return this; 35 | } 36 | 37 | @Override 38 | public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { 39 | switch (code) { 40 | case INTERFACE_TRANSACTION: { 41 | reply.writeString(DESCRIPTOR); 42 | return true; 43 | } 44 | case TRANSACTION_callback: { 45 | data.enforceInterface(DESCRIPTOR); 46 | Request _arg0; 47 | if ((0 != data.readInt())) { 48 | _arg0 = Request.CREATOR.createFromParcel(data); 49 | } else { 50 | _arg0 = null; 51 | } 52 | Response _result = this.callback(_arg0); 53 | reply.writeNoException(); 54 | if ((_result != null)) { 55 | reply.writeInt(1); 56 | _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 57 | } else { 58 | reply.writeInt(0); 59 | } 60 | return true; 61 | } 62 | } 63 | return super.onTransact(code, data, reply, flags); 64 | } 65 | 66 | private static class Proxy implements ICallback { 67 | private android.os.IBinder mRemote; 68 | 69 | Proxy(android.os.IBinder remote) { 70 | mRemote = remote; 71 | } 72 | 73 | @Override 74 | public android.os.IBinder asBinder() { 75 | return mRemote; 76 | } 77 | 78 | public String getInterfaceDescriptor() { 79 | return DESCRIPTOR; 80 | } 81 | 82 | @Override 83 | public Response callback(Request request) throws android.os.RemoteException { 84 | android.os.Parcel _data = android.os.Parcel.obtain(); 85 | android.os.Parcel _reply = android.os.Parcel.obtain(); 86 | Response _result; 87 | try { 88 | _data.writeInterfaceToken(DESCRIPTOR); 89 | if ((request != null)) { 90 | _data.writeInt(1); 91 | request.writeToParcel(_data, 0); 92 | } else { 93 | _data.writeInt(0); 94 | } 95 | mRemote.transact(Stub.TRANSACTION_callback, _data, _reply, 0); 96 | _reply.readException(); 97 | if ((0 != _reply.readInt())) { 98 | _result = Response.CREATOR.createFromParcel(_reply); 99 | } else { 100 | _result = null; 101 | } 102 | } finally { 103 | _reply.recycle(); 104 | _data.recycle(); 105 | } 106 | return _result; 107 | } 108 | } 109 | 110 | static final int TRANSACTION_callback = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); 111 | } 112 | 113 | Response callback(Request request) throws android.os.RemoteException; 114 | } 115 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/ITransfer.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | interface ITransfer extends android.os.IInterface { 4 | /** 5 | * Local-side IPC implementation stub class. 6 | */ 7 | abstract class Stub extends android.os.Binder implements ITransfer { 8 | private static final String DESCRIPTOR = "com.codezjx.alinker.ITransfer"; 9 | 10 | /** 11 | * Construct the stub at attach it to the interface. 12 | */ 13 | Stub() { 14 | this.attachInterface(this, DESCRIPTOR); 15 | } 16 | 17 | /** 18 | * Cast an IBinder object into an com.codezjx.alinker.ITransfer interface, 19 | * generating a proxy if needed. 20 | */ 21 | static ITransfer asInterface(android.os.IBinder obj) { 22 | if ((obj == null)) { 23 | return null; 24 | } 25 | android.os.IInterface iin = obj.queryLocalInterface(DESCRIPTOR); 26 | if (((iin != null) && (iin instanceof ITransfer))) { 27 | return ((ITransfer) iin); 28 | } 29 | return new Proxy(obj); 30 | } 31 | 32 | @Override 33 | public android.os.IBinder asBinder() { 34 | return this; 35 | } 36 | 37 | @Override 38 | public boolean onTransact(int code, android.os.Parcel data, android.os.Parcel reply, int flags) throws android.os.RemoteException { 39 | switch (code) { 40 | case INTERFACE_TRANSACTION: { 41 | reply.writeString(DESCRIPTOR); 42 | return true; 43 | } 44 | case TRANSACTION_execute: { 45 | data.enforceInterface(DESCRIPTOR); 46 | Request _arg0; 47 | if ((0 != data.readInt())) { 48 | _arg0 = Request.CREATOR.createFromParcel(data); 49 | } else { 50 | _arg0 = null; 51 | } 52 | Response _result = this.execute(_arg0); 53 | if ((flags & android.os.IBinder.FLAG_ONEWAY) != 0) { 54 | // One-way mode just execute and return directly. 55 | return true; 56 | } 57 | reply.writeNoException(); 58 | if ((_result != null)) { 59 | reply.writeInt(1); 60 | _result.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 61 | } else { 62 | reply.writeInt(0); 63 | } 64 | if ((_arg0 != null)) { 65 | reply.writeInt(1); 66 | _arg0.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE); 67 | } else { 68 | reply.writeInt(0); 69 | } 70 | return true; 71 | } 72 | case TRANSACTION_register: { 73 | data.enforceInterface(DESCRIPTOR); 74 | ICallback _arg0; 75 | _arg0 = ICallback.Stub.asInterface(data.readStrongBinder()); 76 | this.register(_arg0); 77 | reply.writeNoException(); 78 | return true; 79 | } 80 | case TRANSACTION_unRegister: { 81 | data.enforceInterface(DESCRIPTOR); 82 | ICallback _arg0; 83 | _arg0 = ICallback.Stub.asInterface(data.readStrongBinder()); 84 | this.unRegister(_arg0); 85 | reply.writeNoException(); 86 | return true; 87 | } 88 | } 89 | return super.onTransact(code, data, reply, flags); 90 | } 91 | 92 | private static class Proxy implements ITransfer { 93 | private android.os.IBinder mRemote; 94 | 95 | Proxy(android.os.IBinder remote) { 96 | mRemote = remote; 97 | } 98 | 99 | @Override 100 | public android.os.IBinder asBinder() { 101 | return mRemote; 102 | } 103 | 104 | public String getInterfaceDescriptor() { 105 | return DESCRIPTOR; 106 | } 107 | 108 | @Override 109 | public Response execute(Request request) throws android.os.RemoteException { 110 | android.os.Parcel _data = android.os.Parcel.obtain(); 111 | android.os.Parcel _reply = android.os.Parcel.obtain(); 112 | Response _result; 113 | try { 114 | _data.writeInterfaceToken(DESCRIPTOR); 115 | if ((request != null)) { 116 | _data.writeInt(1); 117 | request.writeToParcel(_data, 0); 118 | } else { 119 | _data.writeInt(0); 120 | } 121 | // One-way mode just transact and return directly. 122 | if (request != null && request.isOneWay()) { 123 | mRemote.transact(Stub.TRANSACTION_execute, _data, null, android.os.IBinder.FLAG_ONEWAY); 124 | return null; 125 | } 126 | mRemote.transact(Stub.TRANSACTION_execute, _data, _reply, 0); 127 | _reply.readException(); 128 | if ((0 != _reply.readInt())) { 129 | _result = Response.CREATOR.createFromParcel(_reply); 130 | } else { 131 | _result = null; 132 | } 133 | if ((0 != _reply.readInt())) { 134 | request.readFromParcel(_reply); 135 | } 136 | } finally { 137 | _reply.recycle(); 138 | _data.recycle(); 139 | } 140 | return _result; 141 | } 142 | 143 | @Override 144 | public void register(ICallback callback) throws android.os.RemoteException { 145 | android.os.Parcel _data = android.os.Parcel.obtain(); 146 | android.os.Parcel _reply = android.os.Parcel.obtain(); 147 | try { 148 | _data.writeInterfaceToken(DESCRIPTOR); 149 | _data.writeStrongBinder((((callback != null)) ? (callback.asBinder()) : (null))); 150 | mRemote.transact(Stub.TRANSACTION_register, _data, _reply, 0); 151 | _reply.readException(); 152 | } finally { 153 | _reply.recycle(); 154 | _data.recycle(); 155 | } 156 | } 157 | 158 | @Override 159 | public void unRegister(ICallback callback) throws android.os.RemoteException { 160 | android.os.Parcel _data = android.os.Parcel.obtain(); 161 | android.os.Parcel _reply = android.os.Parcel.obtain(); 162 | try { 163 | _data.writeInterfaceToken(DESCRIPTOR); 164 | _data.writeStrongBinder((((callback != null)) ? (callback.asBinder()) : (null))); 165 | mRemote.transact(Stub.TRANSACTION_unRegister, _data, _reply, 0); 166 | _reply.readException(); 167 | } finally { 168 | _reply.recycle(); 169 | _data.recycle(); 170 | } 171 | } 172 | } 173 | 174 | static final int TRANSACTION_execute = (android.os.IBinder.FIRST_CALL_TRANSACTION + 0); 175 | static final int TRANSACTION_register = (android.os.IBinder.FIRST_CALL_TRANSACTION + 1); 176 | static final int TRANSACTION_unRegister = (android.os.IBinder.FIRST_CALL_TRANSACTION + 2); 177 | } 178 | 179 | Response execute(Request request) throws android.os.RemoteException; 180 | 181 | void register(ICallback callback) throws android.os.RemoteException; 182 | 183 | void unRegister(ICallback callback) throws android.os.RemoteException; 184 | } 185 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/InOutTypeWrapper.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | /** 6 | * Created by codezjx on 2017/11/30.
7 | */ 8 | final class InOutTypeWrapper implements BaseTypeWrapper { 9 | 10 | private int mType; 11 | private Object mParam; 12 | 13 | InOutTypeWrapper(Object param, Class mParamType) { 14 | mType = Utils.getTypeByClass(mParamType); 15 | mParam = param; 16 | } 17 | 18 | @Override 19 | public int getType() { 20 | return mType; 21 | } 22 | 23 | @Override 24 | public Object getParam() { 25 | return mParam; 26 | } 27 | 28 | @Override 29 | public int describeContents() { 30 | return 0; 31 | } 32 | 33 | @Override 34 | public void writeToParcel(Parcel dest, int flags) { 35 | dest.writeInt(mType); 36 | Type type = TypeFactory.getType(mType); 37 | type.writeToParcel(dest, flags, mParam); 38 | } 39 | 40 | @Override 41 | public void readFromParcel(Parcel in) { 42 | mType = in.readInt(); 43 | OutType type = (OutType) TypeFactory.getType(mType); 44 | type.readFromParcel(in, mParam); 45 | } 46 | 47 | private InOutTypeWrapper(Parcel in) { 48 | mType = in.readInt(); 49 | Type type = TypeFactory.getType(mType); 50 | mParam = type.createFromParcel(in); 51 | } 52 | 53 | public static final Creator CREATOR = new Creator() { 54 | @Override 55 | public InOutTypeWrapper createFromParcel(Parcel source) { 56 | return new InOutTypeWrapper(source); 57 | } 58 | 59 | @Override 60 | public InOutTypeWrapper[] newArray(int size) { 61 | return new InOutTypeWrapper[size]; 62 | } 63 | }; 64 | 65 | } 66 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/InTypeWrapper.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | /** 6 | * Created by codezjx on 2017/11/19.
7 | */ 8 | final class InTypeWrapper implements BaseTypeWrapper { 9 | 10 | private int mType; 11 | private Object mParam; 12 | 13 | InTypeWrapper(Object param, Class mParamType) { 14 | mType = Utils.getTypeByClass(mParamType); 15 | mParam = param; 16 | } 17 | 18 | @Override 19 | public int getType() { 20 | return mType; 21 | } 22 | 23 | @Override 24 | public Object getParam() { 25 | return mParam; 26 | } 27 | 28 | @Override 29 | public int describeContents() { 30 | return 0; 31 | } 32 | 33 | @Override 34 | public void writeToParcel(Parcel dest, int flags) { 35 | // Return if write return value, because in type won't readFromParcel 36 | if (flags == PARCELABLE_WRITE_RETURN_VALUE) { 37 | return; 38 | } 39 | dest.writeInt(mType); 40 | Type type = TypeFactory.getType(mType); 41 | type.writeToParcel(dest, flags, mParam); 42 | } 43 | 44 | @Override 45 | public void readFromParcel(Parcel in) { 46 | // Nothing to do with in type 47 | } 48 | 49 | private InTypeWrapper(Parcel in) { 50 | mType = in.readInt(); 51 | Type type = TypeFactory.getType(mType); 52 | mParam = type.createFromParcel(in); 53 | } 54 | 55 | public static final Creator CREATOR = new Creator() { 56 | @Override 57 | public InTypeWrapper createFromParcel(Parcel source) { 58 | return new InTypeWrapper(source); 59 | } 60 | 61 | @Override 62 | public InTypeWrapper[] newArray(int size) { 63 | return new InTypeWrapper[size]; 64 | } 65 | }; 66 | 67 | } 68 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Invoker.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Binder; 4 | import android.os.RemoteCallbackList; 5 | import android.os.RemoteException; 6 | 7 | import com.codezjx.andlinker.annotation.RemoteInterface; 8 | 9 | import java.lang.annotation.Annotation; 10 | import java.lang.reflect.InvocationHandler; 11 | import java.lang.reflect.Method; 12 | import java.lang.reflect.Proxy; 13 | import java.lang.reflect.Type; 14 | import java.util.concurrent.ConcurrentHashMap; 15 | 16 | /** 17 | * Created by codezjx on 2017/10/3.
18 | */ 19 | final class Invoker { 20 | 21 | private static final String TAG = "Invoker"; 22 | 23 | private final ConcurrentHashMap> mCallbackClassTypes; 24 | private final ConcurrentHashMap mMethodExecutors; 25 | private final RemoteCallbackList mCallbackList; 26 | 27 | Invoker() { 28 | mCallbackClassTypes = new ConcurrentHashMap>(); 29 | mMethodExecutors = new ConcurrentHashMap(); 30 | mCallbackList = new RemoteCallbackList(); 31 | } 32 | 33 | private void handleCallbackClass(Class clazz, boolean isRegister) { 34 | if (!clazz.isAnnotationPresent(RemoteInterface.class)) { 35 | throw new IllegalArgumentException("Callback interface doesn't has @RemoteInterface annotation."); 36 | } 37 | String className = clazz.getSimpleName(); 38 | if (isRegister) { 39 | mCallbackClassTypes.putIfAbsent(className, clazz); 40 | } else { 41 | mCallbackClassTypes.remove(className); 42 | } 43 | } 44 | 45 | private void handleObject(Object target, boolean isRegister) { 46 | if (target == null) { 47 | throw new NullPointerException("Object to (un)register must not be null."); 48 | } 49 | Class[] interfaces = target.getClass().getInterfaces(); 50 | if (interfaces.length != 1) { 51 | throw new IllegalArgumentException("Remote object must extend just one interface."); 52 | } 53 | Class clazz = interfaces[0]; 54 | if (!clazz.isAnnotationPresent(RemoteInterface.class)) { 55 | throw new IllegalArgumentException("Interface doesn't has @RemoteInterface annotation."); 56 | } 57 | // Cache all annotation method 58 | String clsName = clazz.getSimpleName(); 59 | Method[] methods = clazz.getMethods(); 60 | for (Method method : methods) { 61 | // The compiler sometimes creates synthetic bridge methods as part of the 62 | // type erasure process. As of JDK8 these methods now include the same 63 | // annotations as the original declarations. They should be ignored for 64 | // subscribe/produce. 65 | if (method.isBridge()) { 66 | continue; 67 | } 68 | String methodName = method.getName(); 69 | String methodClsName = method.getDeclaringClass().getSimpleName(); 70 | String key = createMethodExecutorKey(Utils.createClsName(clsName, methodClsName), methodName); 71 | if (isRegister) { 72 | MethodExecutor executor = new MethodExecutor(target, method); 73 | MethodExecutor preExecutor = mMethodExecutors.putIfAbsent(key, executor); 74 | if (preExecutor != null) { 75 | throw new IllegalStateException("Key conflict with key:" + key + " method:" + methodName 76 | + ". Please try another class/method name."); 77 | } 78 | } else { 79 | mMethodExecutors.remove(key); 80 | } 81 | // Cache callback class if exist 82 | Class[] paramCls = method.getParameterTypes(); 83 | Annotation[][] paramAnnotations = method.getParameterAnnotations(); 84 | for (int i = 0; i < paramCls.length; i++) { 85 | Class cls = paramCls[i]; 86 | Annotation[] annotations = paramAnnotations[i]; 87 | if (!containCallbackAnnotation(annotations)) { 88 | continue; 89 | } 90 | handleCallbackClass(cls, isRegister); 91 | } 92 | } 93 | } 94 | 95 | private boolean containCallbackAnnotation(Annotation[] annotations) { 96 | if (annotations == null) { 97 | return false; 98 | } 99 | for (Annotation annotation : annotations) { 100 | if (annotation instanceof com.codezjx.andlinker.annotation.Callback) { 101 | return true; 102 | } 103 | } 104 | return false; 105 | } 106 | 107 | void registerObject(Object target) { 108 | handleObject(target, true); 109 | } 110 | 111 | void unRegisterObject(Object target) { 112 | handleObject(target, false); 113 | } 114 | 115 | Response invoke(Request request) { 116 | BaseTypeWrapper[] wrappers = request.getArgsWrapper(); 117 | Object[] args = new Object[wrappers.length]; 118 | for (int i = 0; i < wrappers.length; i++) { 119 | // Assign the origin args parameter 120 | args[i] = wrappers[i].getParam(); 121 | if (wrappers[i].getType() == BaseTypeWrapper.TYPE_CALLBACK) { 122 | int pid = Binder.getCallingPid(); 123 | String clazzName = ((CallbackTypeWrapper) wrappers[i]).getClassName(); 124 | Class clazz = getCallbackClass(clazzName); 125 | if (clazz == null) { 126 | throw new IllegalStateException("Can't find callback class: " + clazzName); 127 | } 128 | args[i] = getCallbackProxy(clazz, pid); 129 | } 130 | } 131 | MethodExecutor executor = getMethodExecutor(request); 132 | if (executor == null) { 133 | String errMsg = String.format("The method '%s' you call was not exist!", request.getMethodName()); 134 | return new Response(Response.STATUS_CODE_NOT_FOUND, errMsg, null); 135 | } 136 | return executor.execute(args); 137 | } 138 | 139 | RemoteCallbackList getCallbackList() { 140 | return mCallbackList; 141 | } 142 | 143 | @SuppressWarnings("unchecked") // Single-interface proxy creation guarded by parameter safety. 144 | private T getCallbackProxy(final Class service, final int pid) { 145 | Utils.validateServiceInterface(service); 146 | return (T) Proxy.newProxyInstance(service.getClassLoader(), new Class[] { service }, 147 | new InvocationHandler() { 148 | @Override 149 | public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 150 | Object result = null; 151 | final int len = mCallbackList.beginBroadcast(); 152 | for (int i = 0; i < len; i++) { 153 | int cookiePid = (int) mCallbackList.getBroadcastCookie(i); 154 | if (cookiePid == pid) { 155 | try { 156 | Type[] parameterTypes = method.getGenericParameterTypes(); 157 | String clsName = Utils.createClsName(service.getSimpleName(), method.getDeclaringClass().getSimpleName()); 158 | Request request = createCallbackRequest(clsName, method.getName(), args, parameterTypes); 159 | Response response = mCallbackList.getBroadcastItem(i).callback(request); 160 | result = response.getResult(); 161 | if (response.getStatusCode() != Response.STATUS_CODE_SUCCESS) { 162 | Logger.e(TAG, "Execute remote callback fail: " + response.toString()); 163 | } 164 | } catch (RemoteException e) { 165 | Logger.e(TAG, "Error when execute callback!", e); 166 | } 167 | break; 168 | } 169 | } 170 | mCallbackList.finishBroadcast(); 171 | return result; 172 | } 173 | }); 174 | } 175 | 176 | private Request createCallbackRequest(String targetClass, String methodName, Object[] args, Type[] parameterTypes) { 177 | int argsLength = args != null ? args.length : 0; 178 | BaseTypeWrapper[] wrappers = new BaseTypeWrapper[argsLength]; 179 | for (int i = 0; i < argsLength; i++) { 180 | Class rawParameterType = Utils.getRawType(parameterTypes[i]); 181 | wrappers[i] = new InTypeWrapper(args[i], rawParameterType); 182 | } 183 | return new Request(targetClass, methodName, wrappers); 184 | } 185 | 186 | private Class getCallbackClass(String className) { 187 | return mCallbackClassTypes.get(className); 188 | } 189 | 190 | private String createMethodExecutorKey(String clsName, String methodName) { 191 | StringBuilder sb = new StringBuilder(); 192 | sb.append(clsName) 193 | .append('-') 194 | .append(methodName); 195 | return sb.toString(); 196 | } 197 | 198 | private MethodExecutor getMethodExecutor(Request request) { 199 | String key = createMethodExecutorKey(request.getTargetClass(), request.getMethodName()); 200 | return mMethodExecutors.get(key); 201 | } 202 | 203 | } 204 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/LinkerBinderImpl.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Binder; 4 | import android.os.RemoteCallbackList; 5 | import android.os.RemoteException; 6 | 7 | /** 8 | * Created by codezjx on 2017/9/13.
9 | */ 10 | final class LinkerBinderImpl extends ITransfer.Stub implements AndLinkerBinder { 11 | 12 | private static final String TAG = "LinkerBinder"; 13 | private RemoteCallbackList mCallbackList; 14 | private Invoker mInvoker; 15 | 16 | LinkerBinderImpl() { 17 | mInvoker = new Invoker(); 18 | mCallbackList = mInvoker.getCallbackList(); 19 | } 20 | 21 | @Override 22 | public void registerObject(Object target) { 23 | mInvoker.registerObject(target); 24 | } 25 | 26 | @Override 27 | public void unRegisterObject(Object target) { 28 | mInvoker.unRegisterObject(target); 29 | } 30 | 31 | @Override 32 | public Response execute(Request request) throws RemoteException { 33 | for (BaseTypeWrapper wrapper : request.getArgsWrapper()) { 34 | Logger.d(TAG, "Receive param, value:" + wrapper.getParam() 35 | + " type:" + (wrapper.getParam() != null ? wrapper.getParam().getClass() : "null")); 36 | } 37 | Logger.d(TAG, "Receive request:" + request.getMethodName()); 38 | return mInvoker.invoke(request); 39 | } 40 | 41 | @Override 42 | public void register(ICallback callback) throws RemoteException { 43 | int pid = Binder.getCallingPid(); 44 | Logger.d(TAG, "register callback:" + callback + " pid:" + pid); 45 | if (callback != null) { 46 | mCallbackList.register(callback, pid); 47 | } 48 | } 49 | 50 | @Override 51 | public void unRegister(ICallback callback) throws RemoteException { 52 | int pid = Binder.getCallingPid(); 53 | Logger.d(TAG, "unRegister callback:" + callback + " pid:" + pid); 54 | if (callback != null) { 55 | mCallbackList.unregister(callback); 56 | } 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Logger.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Build; 4 | import android.util.Log; 5 | 6 | import java.io.PrintWriter; 7 | import java.io.StringWriter; 8 | import java.util.regex.Matcher; 9 | import java.util.regex.Pattern; 10 | 11 | /** 12 | * Created by codezjx on 2018/1/23.
13 | */ 14 | final class Logger { 15 | 16 | private Logger() { 17 | // private constructor 18 | } 19 | 20 | private static final String DEFAULT_LOG_TAG = "Logger"; 21 | private static final int MAX_TAG_LENGTH = 23; 22 | // 3 method calls inside Logger 23 | private static final int CALL_STACK_INDEX = 3; 24 | private static final Pattern ANONYMOUS_CLASS = Pattern.compile("(\\$\\d+)+$"); 25 | static boolean sEnable = false; 26 | 27 | static void v(String msg) { 28 | log(Log.VERBOSE, null, msg, null); 29 | } 30 | 31 | static void v(String tag, String msg) { 32 | log(Log.VERBOSE, tag, msg, null); 33 | } 34 | 35 | static void d(String msg) { 36 | log(Log.DEBUG, null, msg, null); 37 | } 38 | 39 | static void d(String tag, String msg) { 40 | log(Log.DEBUG, tag, msg, null); 41 | } 42 | 43 | static void i(String msg) { 44 | log(Log.INFO, null, msg, null); 45 | } 46 | 47 | static void i(String tag, String msg) { 48 | log(Log.INFO, tag, msg, null); 49 | } 50 | 51 | static void w(String msg) { 52 | log(Log.WARN, null, msg, null); 53 | } 54 | 55 | static void w(String tag, String msg) { 56 | log(Log.WARN, tag, msg, null); 57 | } 58 | 59 | static void w(String msg, Throwable t) { 60 | log(Log.WARN, null, msg, t); 61 | } 62 | 63 | static void w(String tag, String msg, Throwable t) { 64 | log(Log.WARN, tag, msg, t); 65 | } 66 | 67 | static void e(String msg) { 68 | log(Log.ERROR, null, msg, null); 69 | } 70 | 71 | static void e(String tag, String msg) { 72 | log(Log.ERROR, tag, msg, null); 73 | } 74 | 75 | static void e(String msg, Throwable t) { 76 | log(Log.ERROR, null, msg, t); 77 | } 78 | 79 | static void e(String tag, String msg, Throwable t) { 80 | log(Log.ERROR, tag, msg, t); 81 | } 82 | 83 | private static void log(int priority, String tag, String msg, Throwable t) { 84 | if (!sEnable) { 85 | return; 86 | } 87 | String curTag = (tag != null && tag.trim().length() > 0) ? tag : getTag(); 88 | String curMsg = (t != null) ? (msg + '\n' + getStackTraceString(t)) : msg; 89 | Log.println(priority, curTag, curMsg); 90 | } 91 | 92 | private static String getStackTraceString(Throwable t) { 93 | if (t == null) { 94 | return ""; 95 | } 96 | // Don't replace this with Log.getStackTraceString() - it hides 97 | // UnknownHostException, which is not what we want. 98 | StringWriter sw = new StringWriter(256); 99 | PrintWriter pw = new PrintWriter(sw, false); 100 | t.printStackTrace(pw); 101 | pw.flush(); 102 | return sw.toString(); 103 | } 104 | 105 | private static String getTag() { 106 | StackTraceElement[] stackTrace = new Throwable().getStackTrace(); 107 | if (stackTrace.length <= CALL_STACK_INDEX) { 108 | Log.e(DEFAULT_LOG_TAG, "Synthetic stacktrace didn't have enough elements, use the default logger tag, are you using proguard?"); 109 | return DEFAULT_LOG_TAG; 110 | } 111 | return createStackElementTag(stackTrace[CALL_STACK_INDEX]); 112 | } 113 | 114 | private static String createStackElementTag(StackTraceElement element) { 115 | String tag = element.getClassName(); 116 | Matcher m = ANONYMOUS_CLASS.matcher(tag); 117 | if (m.find()) { 118 | tag = m.replaceAll(""); 119 | } 120 | tag = tag.substring(tag.lastIndexOf('.') + 1); 121 | // Tag length limit was removed in API 24. 122 | if (tag.length() <= MAX_TAG_LENGTH || Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) { 123 | return tag; 124 | } 125 | return tag.substring(0, MAX_TAG_LENGTH); 126 | } 127 | } 128 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/MethodExecutor.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | 4 | import java.lang.reflect.InvocationTargetException; 5 | import java.lang.reflect.Method; 6 | 7 | /** 8 | * Created by codezjx on 2017/10/22.
9 | */ 10 | final class MethodExecutor { 11 | 12 | /** Target object to invoke. */ 13 | private final Object mTarget; 14 | /** Method to execute. */ 15 | private final Method mMethod; 16 | 17 | MethodExecutor(Object target, Method method) { 18 | if (target == null) { 19 | throw new NullPointerException("Target cannot be null."); 20 | } 21 | if (method == null) { 22 | throw new NullPointerException("Method cannot be null."); 23 | } 24 | 25 | mTarget = target; 26 | mMethod = method; 27 | method.setAccessible(true); 28 | } 29 | 30 | Response execute(Object[] args) { 31 | Object result = null; 32 | int statusCode = Response.STATUS_CODE_SUCCESS; 33 | String resultMsg = String.format("Call method '%s' successfully!", mMethod.getName()); 34 | Throwable throwable = null; 35 | try { 36 | result = mMethod.invoke(mTarget, args); 37 | } catch (IllegalAccessException e) { 38 | statusCode = Response.STATUS_CODE_ILLEGAL_ACCESS; 39 | throwable = e; 40 | } catch (InvocationTargetException e) { 41 | statusCode = Response.STATUS_CODE_INVOCATION_FAIL; 42 | throwable = e; 43 | } 44 | if (throwable != null) { 45 | String cause = throwable.getCause() != null ? throwable.getCause().toString() : ""; 46 | resultMsg = "Exception occur when execute method: " + mMethod.getName() + "\n Cause: " + cause; 47 | if (Logger.sEnable) { 48 | throwable.printStackTrace(); 49 | } 50 | } 51 | return new Response(statusCode, resultMsg, result); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/OutType.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import java.lang.reflect.InvocationTargetException; 7 | import java.lang.reflect.Method; 8 | import java.util.List; 9 | import java.util.Map; 10 | 11 | /** 12 | * Created by codezjx on 2017/11/30.
13 | */ 14 | interface OutType extends Type { 15 | 16 | void readFromParcel(Parcel in, T val); 17 | 18 | final class ParcelableType implements OutType { 19 | 20 | private static final String TAG = "ParcelableType"; 21 | 22 | @Override 23 | public void writeToParcel(Parcel dest, int flags, Parcelable val) { 24 | if (flags == Parcelable.PARCELABLE_WRITE_RETURN_VALUE) { 25 | val.writeToParcel(dest, flags); 26 | } else { 27 | dest.writeParcelable(val, flags); 28 | } 29 | } 30 | 31 | @Override 32 | public Parcelable createFromParcel(Parcel in) { 33 | return in.readParcelable(getClass().getClassLoader()); 34 | } 35 | 36 | @Override 37 | public void readFromParcel(Parcel in, Parcelable val) { 38 | if (val instanceof SuperParcelable) { 39 | ((SuperParcelable) val).readFromParcel(in); 40 | return; 41 | } 42 | Method method = Utils.getMethodReadFromParcel(val.getClass()); 43 | if (method == null) { 44 | throw new IllegalArgumentException("Parcelable parameter with @Out or @Inout annotation must " + 45 | "declare the public readFromParcel() method or implements interface SuperParcelable. " + 46 | "Error parameter type: " + val.getClass().getName()); 47 | } 48 | try { 49 | method.invoke(val, in); 50 | } catch (IllegalAccessException e) { 51 | Logger.e(TAG, "Can't access method readFromParcel().", e); 52 | } catch (InvocationTargetException e) { 53 | Logger.e(TAG, "Method readFromParcel() throws an exception.", e); 54 | } 55 | } 56 | } 57 | 58 | final class ListType implements OutType { 59 | 60 | @Override 61 | public void writeToParcel(Parcel dest, int flags, List val) { 62 | dest.writeList(val); 63 | } 64 | 65 | @Override 66 | public List createFromParcel(Parcel in) { 67 | return in.readArrayList(getClass().getClassLoader()); 68 | } 69 | 70 | @Override 71 | public void readFromParcel(Parcel in, List val) { 72 | // Clear the list before read list 73 | val.clear(); 74 | int N = in.readInt(); 75 | while (N > 0) { 76 | Object value = in.readValue(getClass().getClassLoader()); 77 | val.add(value); 78 | N--; 79 | } 80 | } 81 | } 82 | 83 | final class MapType implements OutType { 84 | 85 | @Override 86 | public void writeToParcel(Parcel dest, int flags, Map val) { 87 | dest.writeMap(val); 88 | } 89 | 90 | @Override 91 | public Map createFromParcel(Parcel in) { 92 | return in.readHashMap(getClass().getClassLoader()); 93 | } 94 | 95 | @Override 96 | public void readFromParcel(Parcel in, Map val) { 97 | ClassLoader loader = getClass().getClassLoader(); 98 | // Clear the map before read map 99 | val.clear(); 100 | int N = in.readInt(); 101 | while (N > 0) { 102 | Object key = in.readValue(loader); 103 | Object value = in.readValue(loader); 104 | val.put(key, value); 105 | N--; 106 | } 107 | } 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/OutTypeWrapper.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | import java.lang.reflect.Array; 6 | import java.util.ArrayList; 7 | import java.util.HashMap; 8 | 9 | /** 10 | * Created by codezjx on 2017/11/30.
11 | */ 12 | final class OutTypeWrapper implements BaseTypeWrapper { 13 | 14 | private int mType; 15 | private Object mParam; 16 | 17 | OutTypeWrapper(Object param, Class mParamType) { 18 | mType = Utils.getTypeByClass(mParamType); 19 | mParam = param; 20 | } 21 | 22 | @Override 23 | public int getType() { 24 | return mType; 25 | } 26 | 27 | @Override 28 | public Object getParam() { 29 | return mParam; 30 | } 31 | 32 | 33 | @Override 34 | public int describeContents() { 35 | return 0; 36 | } 37 | 38 | @Override 39 | public void writeToParcel(Parcel dest, int flags) { 40 | dest.writeInt(mType); 41 | Type type = TypeFactory.getType(mType); 42 | if (flags == PARCELABLE_WRITE_RETURN_VALUE) { 43 | type.writeToParcel(dest, flags, mParam); 44 | } else { 45 | if (mType == BaseTypeWrapper.TYPE_PARCELABLE) { 46 | dest.writeString(mParam.getClass().getName()); 47 | } else if (mType == BaseTypeWrapper.TYPE_PARCELABLEARRAY) { 48 | dest.writeInt(Array.getLength(mParam)); 49 | dest.writeString(mParam.getClass().getComponentType().getName()); 50 | } else if (Utils.isArrayType(mType)) { 51 | // array type just write length 52 | dest.writeInt(Array.getLength(mParam)); 53 | } 54 | } 55 | } 56 | 57 | @Override 58 | public void readFromParcel(Parcel in) { 59 | mType = in.readInt(); 60 | OutType type = (OutType) TypeFactory.getType(mType); 61 | type.readFromParcel(in, mParam); 62 | } 63 | 64 | private OutTypeWrapper(Parcel in) { 65 | mType = in.readInt(); 66 | if (mType == BaseTypeWrapper.TYPE_PARCELABLE) { 67 | String clsName = in.readString(); 68 | mParam = Utils.createObjFromClassName(clsName); 69 | } else if (mType == BaseTypeWrapper.TYPE_PARCELABLEARRAY) { 70 | int length = in.readInt(); 71 | String componentType = in.readString(); 72 | mParam = Utils.createArrayFromComponentType(componentType, length); 73 | } else if (mType == BaseTypeWrapper.TYPE_LIST) { 74 | mParam = new ArrayList(); 75 | } else if (mType == BaseTypeWrapper.TYPE_MAP) { 76 | mParam = new HashMap(); 77 | } else if (Utils.isArrayType(mType)) { 78 | int length = in.readInt(); 79 | ArrayType type = (ArrayType) TypeFactory.getType(mType); 80 | mParam = type.newInstance(length); 81 | } 82 | } 83 | 84 | public static final Creator CREATOR = new Creator() { 85 | @Override 86 | public OutTypeWrapper createFromParcel(Parcel source) { 87 | return new OutTypeWrapper(source); 88 | } 89 | 90 | @Override 91 | public OutTypeWrapper[] newArray(int size) { 92 | return new OutTypeWrapper[size]; 93 | } 94 | }; 95 | } 96 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/ParameterHandler.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import com.codezjx.andlinker.annotation.In; 4 | import com.codezjx.andlinker.annotation.Inout; 5 | import com.codezjx.andlinker.annotation.Out; 6 | 7 | import java.lang.annotation.Annotation; 8 | 9 | /** 10 | * Created by codezjx on 2017/9/17.
11 | */ 12 | interface ParameterHandler { 13 | 14 | void apply(RequestBuilder builder, T value, int index); 15 | 16 | final class CallbackHandler implements ParameterHandler { 17 | 18 | Class mParamType; 19 | 20 | CallbackHandler(Class paramType) { 21 | mParamType = paramType; 22 | } 23 | 24 | @Override 25 | public void apply(RequestBuilder builder, T value, int index) { 26 | Logger.d("CallbackHandler", "ParameterHandler mParamType:" + mParamType + " value:" + value); 27 | String className = mParamType.getSimpleName(); 28 | CallbackTypeWrapper wrapper = new CallbackTypeWrapper(className); 29 | builder.applyWrapper(index, wrapper); 30 | } 31 | 32 | } 33 | 34 | final class ParamDirectionHandler implements ParameterHandler { 35 | 36 | Annotation mAnnotation; 37 | Class mParamType; 38 | 39 | ParamDirectionHandler(Annotation annotation, Class paramType) { 40 | mAnnotation = annotation; 41 | mParamType = paramType; 42 | } 43 | 44 | @Override 45 | public void apply(RequestBuilder builder, T value, int index) { 46 | Logger.d("ParamDirectionHandler", " mParamType:" + mParamType + " value:" + value + " index:" + index); 47 | if (Utils.canOnlyBeInType(mParamType) && !(mAnnotation instanceof In)) { 48 | throw new IllegalArgumentException("Primitives are in by default, and cannot be otherwise."); 49 | } 50 | BaseTypeWrapper wrapper = null; 51 | if (mAnnotation instanceof In) { 52 | wrapper = new InTypeWrapper(value, mParamType); 53 | } else if (mAnnotation instanceof Out) { 54 | wrapper = new OutTypeWrapper(value, mParamType); 55 | } else if (mAnnotation instanceof Inout) { 56 | wrapper = new InOutTypeWrapper(value, mParamType); 57 | } 58 | builder.applyWrapper(index, wrapper); 59 | } 60 | } 61 | 62 | final class DefaultParameterHandler implements ParameterHandler { 63 | 64 | Class mParamType; 65 | 66 | DefaultParameterHandler(Class paramType) { 67 | mParamType = paramType; 68 | } 69 | 70 | @Override 71 | public void apply(RequestBuilder builder, T value, int index) { 72 | if (Utils.canOnlyBeInType(mParamType)) { 73 | InTypeWrapper wrapper = new InTypeWrapper(value, mParamType); 74 | builder.applyWrapper(index, wrapper); 75 | } else { 76 | throw new IllegalArgumentException("Parameter type '" + mParamType.getSimpleName() + "' can be an out type, so you must declare it as @In, @Out or @Inout."); 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/RemoteCall.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.RemoteException; 4 | 5 | import static com.codezjx.andlinker.Utils.checkNotNull; 6 | 7 | /** 8 | * Created by codezjx on 2017/10/14.
9 | */ 10 | final class RemoteCall implements Call { 11 | 12 | private static final String TAG = "RemoteCall"; 13 | 14 | private final ITransfer mTransferService; 15 | private final ServiceMethod mServiceMethod; 16 | private final Object[] mArgs; 17 | private final Dispatcher mDispatcher; 18 | private volatile boolean mExecuted; 19 | private volatile boolean mCanceled; 20 | 21 | RemoteCall(ITransfer transferService, ServiceMethod serviceMethod, Object[] args, Dispatcher dispatcher) { 22 | mTransferService = transferService; 23 | mServiceMethod = serviceMethod; 24 | mArgs = args; 25 | mDispatcher = dispatcher; 26 | } 27 | 28 | private Object executeInternal() throws RemoteException { 29 | if (mTransferService == null) { 30 | Logger.e(TAG, "TransferService null when execute, this may occur if the client is not already bind to the service."); 31 | return null; 32 | } 33 | @SuppressWarnings("unchecked") 34 | ParameterHandler[] handlers = (ParameterHandler[]) mServiceMethod.getParameterHandlers(); 35 | 36 | int argumentCount = mArgs != null ? mArgs.length : 0; 37 | if (argumentCount != handlers.length) { 38 | throw new IllegalArgumentException("Argument count (" + argumentCount 39 | + ") doesn't match expected count (" + handlers.length + ")"); 40 | } 41 | 42 | RequestBuilder requestBuilder = new RequestBuilder(mServiceMethod.getClassName(), mServiceMethod.getMethodName(), argumentCount, mServiceMethod.isOneWay()); 43 | for (int p = 0; p < argumentCount; p++) { 44 | handlers[p].apply(requestBuilder, mArgs[p], p); 45 | } 46 | 47 | Response response = mTransferService.execute(requestBuilder.build()); 48 | // May return null in one-way mode. 49 | if (response == null) { 50 | return null; 51 | } 52 | if (response.getStatusCode() != Response.STATUS_CODE_SUCCESS) { 53 | Logger.e(TAG, "Execute remote call fail: " + response.toString()); 54 | } 55 | return response.getResult(); 56 | } 57 | 58 | @Override 59 | public Object execute() { 60 | checkExecuted(); 61 | if (mCanceled) { 62 | Logger.w(TAG, "Already canceled"); 63 | return null; 64 | } 65 | Object result = null; 66 | try { 67 | result = executeInternal(); 68 | } catch (RemoteException e) { 69 | e.printStackTrace(); 70 | } 71 | return result; 72 | } 73 | 74 | @Override 75 | public void enqueue(Callback callback) { 76 | checkNotNull(callback, "callback == null"); 77 | checkExecuted(); 78 | if (mCanceled) { 79 | Logger.w(TAG, "Already canceled"); 80 | return; 81 | } 82 | 83 | mDispatcher.enqueue(new AsyncCall(callback)); 84 | } 85 | 86 | private void checkExecuted() { 87 | synchronized (this) { 88 | if (mExecuted) { 89 | throw new IllegalStateException("Already executed."); 90 | } 91 | mExecuted = true; 92 | } 93 | } 94 | 95 | final class AsyncCall implements Runnable { 96 | 97 | private Callback mCallback; 98 | 99 | AsyncCall(Callback callback) { 100 | mCallback = callback; 101 | } 102 | 103 | @Override 104 | public void run() { 105 | try { 106 | Object result = executeInternal(); 107 | mCallback.onResponse(RemoteCall.this, result); 108 | } catch (RemoteException e) { 109 | e.printStackTrace(); 110 | mCallback.onFailure(RemoteCall.this, e); 111 | } 112 | } 113 | 114 | } 115 | 116 | @Override 117 | public synchronized boolean isExecuted() { 118 | return mExecuted; 119 | } 120 | 121 | @Override 122 | public void cancel() { 123 | mCanceled = true; 124 | } 125 | 126 | @Override 127 | public boolean isCanceled() { 128 | return mCanceled; 129 | } 130 | 131 | } 132 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Request.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import java.lang.reflect.Array; 7 | import java.util.Arrays; 8 | 9 | /** 10 | * Created by codezjx on 2017/9/13.
11 | */ 12 | final class Request implements SuperParcelable { 13 | 14 | private String mTargetClass; 15 | private String mMethodName; 16 | private BaseTypeWrapper[] mArgsWrapper; 17 | // This field use for client slide only 18 | private boolean mOneWay = false; 19 | 20 | Request(String targetClass, String methodName, BaseTypeWrapper[] argsWrapper) { 21 | this(targetClass, methodName, argsWrapper, false); 22 | } 23 | 24 | Request(String targetClass, String methodName, BaseTypeWrapper[] argsWrapper, boolean oneWay) { 25 | mTargetClass = targetClass; 26 | mMethodName = methodName; 27 | mArgsWrapper = argsWrapper; 28 | mOneWay = oneWay; 29 | } 30 | 31 | @Override 32 | public int describeContents() { 33 | return 0; 34 | } 35 | 36 | @Override 37 | public void writeToParcel(Parcel dest, int flags) { 38 | dest.writeString(mTargetClass); 39 | dest.writeString(mMethodName); 40 | if (flags == PARCELABLE_WRITE_RETURN_VALUE) { 41 | writeParcelableArrayToParcel(dest, mArgsWrapper, flags); 42 | } else { 43 | dest.writeParcelableArray(mArgsWrapper, flags); 44 | } 45 | } 46 | 47 | @Override 48 | public void readFromParcel(Parcel in) { 49 | mTargetClass = in.readString(); 50 | mMethodName = in.readString(); 51 | readParcelableArrayFromParcel(in, mArgsWrapper); 52 | } 53 | 54 | private Request(Parcel in) { 55 | mTargetClass = in.readString(); 56 | mMethodName = in.readString(); 57 | mArgsWrapper = readParcelableArray(getClass().getClassLoader(), BaseTypeWrapper.class, in); 58 | } 59 | 60 | private void writeParcelableArrayToParcel(Parcel dest, T[] value, int parcelableFlags) { 61 | if (value != null) { 62 | int N = value.length; 63 | dest.writeInt(N); 64 | for (int i = 0; i < N; i++) { 65 | value[i].writeToParcel(dest, parcelableFlags); 66 | } 67 | } else { 68 | dest.writeInt(-1); 69 | } 70 | } 71 | 72 | private void readParcelableArrayFromParcel(Parcel in, T[] value) { 73 | int N = in.readInt(); 74 | if (N < 0) { 75 | return; 76 | } 77 | for (int i = 0; i < N; i++) { 78 | value[i].readFromParcel(in); 79 | } 80 | } 81 | 82 | /** 83 | * Code from {@link Parcel}.readParcelableArray(ClassLoader loader, Class clazz), it's a hide method. 84 | */ 85 | @SuppressWarnings("unchecked") 86 | private T[] readParcelableArray(ClassLoader loader, Class clazz, Parcel in) { 87 | int N = in.readInt(); 88 | if (N < 0) { 89 | return null; 90 | } 91 | T[] p = (T[]) Array.newInstance(clazz, N); 92 | for (int i = 0; i < N; i++) { 93 | p[i] = in.readParcelable(loader); 94 | } 95 | return p; 96 | } 97 | 98 | public static final Creator CREATOR = new Creator() { 99 | @Override 100 | public Request createFromParcel(Parcel source) { 101 | return new Request(source); 102 | } 103 | 104 | @Override 105 | public Request[] newArray(int size) { 106 | return new Request[size]; 107 | } 108 | }; 109 | 110 | String getTargetClass() { 111 | return mTargetClass; 112 | } 113 | 114 | String getMethodName() { 115 | return mMethodName; 116 | } 117 | 118 | boolean isOneWay() { 119 | return mOneWay; 120 | } 121 | 122 | BaseTypeWrapper[] getArgsWrapper() { 123 | return mArgsWrapper; 124 | } 125 | 126 | @Override 127 | public String toString() { 128 | return "Request{" + 129 | "mTargetClass='" + mTargetClass + '\'' + 130 | ", mMethodName='" + mMethodName + '\'' + 131 | ", mArgsWrapper=" + Arrays.toString(mArgsWrapper) + 132 | '}'; 133 | } 134 | } 135 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/RequestBuilder.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | /** 4 | * Created by codezjx on 2017/11/5.
5 | */ 6 | final class RequestBuilder { 7 | 8 | private String mTargetClass; 9 | private String mMethodName; 10 | private BaseTypeWrapper[] mParameterWrappers; 11 | private boolean mOneWay; 12 | 13 | RequestBuilder(String targetClass, String methodName, int argumentCount, boolean oneWay) { 14 | mTargetClass = targetClass; 15 | mMethodName = methodName; 16 | mParameterWrappers = new BaseTypeWrapper[argumentCount]; 17 | mOneWay = oneWay; 18 | } 19 | 20 | void applyWrapper(int index, BaseTypeWrapper wrapper) { 21 | if (index < 0 || index >= mParameterWrappers.length) { 22 | throw new IllegalArgumentException("Index out of range."); 23 | } 24 | mParameterWrappers[index] = wrapper; 25 | } 26 | 27 | Request build() { 28 | return new Request(mTargetClass, mMethodName, mParameterWrappers, mOneWay); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Response.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | /** 6 | * Created by codezjx on 2017/9/13.
7 | */ 8 | final class Response implements SuperParcelable { 9 | 10 | static final int STATUS_CODE_SUCCESS = 200; 11 | static final int STATUS_CODE_ILLEGAL_ACCESS = 400; 12 | static final int STATUS_CODE_INVOCATION_FAIL = 401; 13 | static final int STATUS_CODE_NOT_FOUND = 404; 14 | 15 | private int mStatusCode; 16 | private String mStatusMessage; 17 | private Object mResult; 18 | 19 | Response(int statusCode, String statusMessage, Object result) { 20 | mStatusCode = statusCode; 21 | mStatusMessage = statusMessage; 22 | mResult = result; 23 | } 24 | 25 | @Override 26 | public int describeContents() { 27 | return 0; 28 | } 29 | 30 | @Override 31 | public void writeToParcel(Parcel dest, int flags) { 32 | dest.writeInt(mStatusCode); 33 | dest.writeString(mStatusMessage); 34 | dest.writeValue(mResult); 35 | } 36 | 37 | @Override 38 | public void readFromParcel(Parcel in) { 39 | mStatusCode = in.readInt(); 40 | mStatusMessage = in.readString(); 41 | mResult = in.readValue(getClass().getClassLoader()); 42 | } 43 | 44 | private Response(Parcel in) { 45 | readFromParcel(in); 46 | } 47 | 48 | public static final Creator CREATOR = new Creator() { 49 | @Override 50 | public Response createFromParcel(Parcel source) { 51 | return new Response(source); 52 | } 53 | 54 | @Override 55 | public Response[] newArray(int size) { 56 | return new Response[size]; 57 | } 58 | }; 59 | 60 | int getStatusCode() { 61 | return mStatusCode; 62 | } 63 | 64 | String getStatusMessage() { 65 | return mStatusMessage; 66 | } 67 | 68 | Object getResult() { 69 | return mResult; 70 | } 71 | 72 | @Override 73 | public String toString() { 74 | return "Response{" + 75 | "mStatusCode=" + mStatusCode + 76 | ", mStatusMessage='" + mStatusMessage + '\'' + 77 | ", mResult=" + mResult + 78 | '}'; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/ServiceMethod.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import com.codezjx.andlinker.annotation.Callback; 4 | import com.codezjx.andlinker.annotation.In; 5 | import com.codezjx.andlinker.annotation.Inout; 6 | import com.codezjx.andlinker.annotation.OneWay; 7 | import com.codezjx.andlinker.annotation.Out; 8 | 9 | import java.lang.annotation.Annotation; 10 | import java.lang.reflect.Method; 11 | import java.lang.reflect.Type; 12 | 13 | /** 14 | * Created by codezjx on 2017/9/14.
15 | * Adapts an invocation of an interface method into an AIDL call. 16 | */ 17 | final class ServiceMethod { 18 | 19 | private static final String TAG = "ServiceMethod"; 20 | 21 | private CallAdapter mCallAdapter; 22 | private String mClassName; 23 | private String mMethodName; 24 | private boolean mOneWay; 25 | private ParameterHandler[] mParameterHandlers; 26 | 27 | ServiceMethod(Builder builder) { 28 | mCallAdapter = builder.mCallAdapter; 29 | mClassName = builder.mClassName; 30 | mMethodName = builder.mMethodName; 31 | mOneWay = builder.mOneWay; 32 | mParameterHandlers = builder.mParameterHandlers; 33 | } 34 | 35 | CallAdapter getCallAdapter() { 36 | return mCallAdapter; 37 | } 38 | 39 | String getClassName() { 40 | return mClassName; 41 | } 42 | 43 | String getMethodName() { 44 | return mMethodName; 45 | } 46 | 47 | boolean isOneWay() { 48 | return mOneWay; 49 | } 50 | 51 | ParameterHandler[] getParameterHandlers() { 52 | return mParameterHandlers; 53 | } 54 | 55 | static final class Builder { 56 | 57 | private AndLinker mLinker; 58 | private Method mMethod; 59 | private Annotation[] mMethodAnnotations; 60 | private Annotation[][] mParameterAnnotationsArray; 61 | private Type[] mParameterTypes; 62 | 63 | private CallAdapter mCallAdapter; 64 | private String mClassName = ""; 65 | private String mMethodName = ""; 66 | private boolean mOneWay = false; 67 | private ParameterHandler[] mParameterHandlers; 68 | 69 | Builder(AndLinker linker, Method method, String clsName) { 70 | mLinker = linker; 71 | mMethod = method; 72 | mClassName = clsName; 73 | mMethodAnnotations = method.getAnnotations(); 74 | mParameterAnnotationsArray = method.getParameterAnnotations(); 75 | mParameterTypes = method.getGenericParameterTypes(); 76 | } 77 | 78 | ServiceMethod build() { 79 | mCallAdapter = createCallAdapter(); 80 | String methodClsName = mMethod.getDeclaringClass().getSimpleName(); 81 | mClassName = Utils.createClsName(mClassName, methodClsName); 82 | mMethodName = mMethod.getName(); 83 | 84 | for (Annotation annotation : mMethodAnnotations) { 85 | if (annotation instanceof OneWay) { 86 | mOneWay = true; 87 | break; 88 | } 89 | } 90 | 91 | int parameterCount = mParameterAnnotationsArray.length; 92 | mParameterHandlers = new ParameterHandler[parameterCount]; 93 | for (int p = 0; p < parameterCount; p++) { 94 | Type parameterType = mParameterTypes[p]; 95 | if (Utils.hasUnresolvableType(parameterType)) { 96 | throw parameterError(p, "Parameter type must not include a type variable or wildcard: %s", 97 | parameterType); 98 | } 99 | 100 | Annotation[] parameterAnnotations = mParameterAnnotationsArray[p]; 101 | mParameterHandlers[p] = parseParameter(p, parameterType, parameterAnnotations); 102 | } 103 | 104 | return new ServiceMethod(this); 105 | } 106 | 107 | private CallAdapter createCallAdapter() { 108 | Type returnType = mMethod.getGenericReturnType(); 109 | if (Utils.hasUnresolvableType(returnType)) { 110 | throw methodError( 111 | "Method return type must not include a type variable or wildcard: %s", returnType); 112 | } 113 | Annotation[] annotations = mMethod.getAnnotations(); 114 | try { 115 | //noinspection unchecked 116 | return mLinker.findCallAdapter(returnType, annotations); 117 | } catch (RuntimeException e) { // Wide exception range because factories are user code. 118 | throw methodError(e, "Unable to create call adapter for %s", returnType); 119 | } 120 | } 121 | 122 | private ParameterHandler parseParameter(int p, Type parameterType, Annotation[] annotations) { 123 | Class rawParameterType = Utils.getRawType(parameterType); 124 | if (annotations == null || annotations.length == 0) { 125 | return new ParameterHandler.DefaultParameterHandler<>(rawParameterType); 126 | } 127 | for (Annotation annotation : annotations) { 128 | if (annotation instanceof Callback) { 129 | return new ParameterHandler.CallbackHandler<>(rawParameterType); 130 | } else if (annotation instanceof In || annotation instanceof Out || annotation instanceof Inout) { 131 | return new ParameterHandler.ParamDirectionHandler<>(annotation, rawParameterType); 132 | } 133 | } 134 | throw parameterError(p, "No support annotation found."); 135 | } 136 | 137 | private RuntimeException methodError(String message, Object... args) { 138 | return methodError(null, message, args); 139 | } 140 | 141 | private RuntimeException methodError(Throwable cause, String message, Object... args) { 142 | message = String.format(message, args); 143 | return new IllegalArgumentException(message 144 | + "\n for method " 145 | + mMethod.getDeclaringClass().getSimpleName() 146 | + "." 147 | + mMethod.getName(), cause); 148 | } 149 | 150 | private RuntimeException parameterError( 151 | Throwable cause, int p, String message, Object... args) { 152 | return methodError(cause, message + " (parameter #" + (p + 1) + ")", args); 153 | } 154 | 155 | private RuntimeException parameterError(int p, String message, Object... args) { 156 | return methodError(message + " (parameter #" + (p + 1) + ")", args); 157 | } 158 | 159 | } 160 | 161 | } 162 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/SuperParcelable.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | /** 7 | * Parcelable parameter classes with @Out or @Inout annotation must inherit from this class. 8 | */ 9 | public interface SuperParcelable extends Parcelable { 10 | 11 | /** 12 | * Reads the parcel contents into this object, so we can restore it. 13 | * @param in The parcel to overwrite this object from. 14 | */ 15 | void readFromParcel(Parcel in); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Type.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.text.TextUtils; 5 | 6 | /** 7 | * Created by codezjx on 2017/11/28.
8 | */ 9 | interface Type { 10 | 11 | void writeToParcel(Parcel dest, int flags, T val); 12 | 13 | T createFromParcel(Parcel in); 14 | 15 | final class EmptyType implements Type { 16 | 17 | @Override 18 | public void writeToParcel(Parcel dest, int flags, Object val) { 19 | // Nothing to do 20 | } 21 | 22 | @Override 23 | public Object createFromParcel(Parcel in) { 24 | return null; 25 | } 26 | } 27 | 28 | final class ByteType implements Type { 29 | 30 | @Override 31 | public void writeToParcel(Parcel dest, int flags, Byte val) { 32 | dest.writeByte(val); 33 | } 34 | 35 | @Override 36 | public Byte createFromParcel(Parcel in) { 37 | return in.readByte(); 38 | } 39 | } 40 | 41 | final class ShortType implements Type { 42 | 43 | @Override 44 | public void writeToParcel(Parcel dest, int flags, Short val) { 45 | dest.writeInt(val.intValue()); 46 | } 47 | 48 | @Override 49 | public Short createFromParcel(Parcel in) { 50 | return (short) in.readInt(); 51 | } 52 | } 53 | 54 | final class IntType implements Type { 55 | 56 | @Override 57 | public void writeToParcel(Parcel dest, int flags, Integer val) { 58 | dest.writeInt(val); 59 | } 60 | 61 | @Override 62 | public Integer createFromParcel(Parcel in) { 63 | return in.readInt(); 64 | } 65 | } 66 | 67 | final class LongType implements Type { 68 | 69 | @Override 70 | public void writeToParcel(Parcel dest, int flags, Long val) { 71 | dest.writeLong(val); 72 | } 73 | 74 | @Override 75 | public Long createFromParcel(Parcel in) { 76 | return in.readLong(); 77 | } 78 | } 79 | 80 | final class FloatType implements Type { 81 | 82 | @Override 83 | public void writeToParcel(Parcel dest, int flags, Float val) { 84 | dest.writeFloat(val); 85 | } 86 | 87 | @Override 88 | public Float createFromParcel(Parcel in) { 89 | return in.readFloat(); 90 | } 91 | } 92 | 93 | final class DoubleType implements Type { 94 | 95 | @Override 96 | public void writeToParcel(Parcel dest, int flags, Double val) { 97 | dest.writeDouble(val); 98 | } 99 | 100 | @Override 101 | public Double createFromParcel(Parcel in) { 102 | return in.readDouble(); 103 | } 104 | } 105 | 106 | final class BooleanType implements Type { 107 | 108 | @Override 109 | public void writeToParcel(Parcel dest, int flags, Boolean val) { 110 | dest.writeInt(val ? 1 : 0); 111 | } 112 | 113 | @Override 114 | public Boolean createFromParcel(Parcel in) { 115 | return in.readInt() == 1; 116 | } 117 | } 118 | 119 | final class CharType implements Type { 120 | 121 | @Override 122 | public void writeToParcel(Parcel dest, int flags, Character val) { 123 | dest.writeInt(((int) val)); 124 | } 125 | 126 | @Override 127 | public Character createFromParcel(Parcel in) { 128 | return (char) in.readInt(); 129 | } 130 | } 131 | 132 | final class StringType implements Type { 133 | 134 | @Override 135 | public void writeToParcel(Parcel dest, int flags, String val) { 136 | dest.writeString(val); 137 | } 138 | 139 | @Override 140 | public String createFromParcel(Parcel in) { 141 | return in.readString(); 142 | } 143 | } 144 | 145 | final class CharSequenceType implements Type { 146 | 147 | @Override 148 | public void writeToParcel(Parcel dest, int flags, CharSequence val) { 149 | writeCharSequence(dest, val); 150 | } 151 | 152 | @Override 153 | public CharSequence createFromParcel(Parcel in) { 154 | return readCharSequence(in); 155 | } 156 | 157 | static void writeCharSequence(Parcel dest, CharSequence val) { 158 | TextUtils.writeToParcel(val, dest, 0); 159 | } 160 | 161 | static CharSequence readCharSequence(Parcel in) { 162 | return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in); 163 | } 164 | } 165 | 166 | } 167 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/TypeFactory.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | /** 4 | * Created by codezjx on 2017/11/28.
5 | */ 6 | final class TypeFactory { 7 | 8 | private TypeFactory() { 9 | 10 | } 11 | 12 | private static Type[] sTypeArr = { 13 | new Type.EmptyType(), 14 | new Type.ByteType(), new Type.ShortType(), new Type.IntType(), new Type.LongType(), 15 | new Type.FloatType(), new Type.DoubleType(), new Type.BooleanType(), new Type.CharType(), 16 | new ArrayType.ByteArrayType(), new ArrayType.ShortArrayType(), new ArrayType.IntArrayType(), new ArrayType.LongArrayType(), 17 | new ArrayType.FloatArrayType(), new ArrayType.DoubleArrayType(), new ArrayType.BooleanArrayType(), new ArrayType.CharArrayType(), 18 | new Type.StringType(), new ArrayType.StringArrayType(), new Type.CharSequenceType(), new ArrayType.CharSequenceArrayType(), 19 | new OutType.ParcelableType(), new ArrayType.ParcelableArrayType(), new OutType.ListType(), new OutType.MapType() 20 | }; 21 | 22 | static Type getType(int type) { 23 | return sTypeArr[type]; 24 | } 25 | 26 | static Type getType(Class classType) { 27 | return sTypeArr[Utils.getTypeByClass(classType)]; 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/Utils.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker; 2 | 3 | import android.os.Parcel; 4 | import android.os.Parcelable; 5 | 6 | import java.lang.reflect.Array; 7 | import java.lang.reflect.GenericArrayType; 8 | import java.lang.reflect.Method; 9 | import java.lang.reflect.ParameterizedType; 10 | import java.lang.reflect.Type; 11 | import java.lang.reflect.TypeVariable; 12 | import java.lang.reflect.WildcardType; 13 | import java.util.List; 14 | import java.util.Map; 15 | 16 | /** 17 | * Created by codezjx on 2017/9/14.
18 | */ 19 | final class Utils { 20 | 21 | private static final String TAG = "Utils"; 22 | 23 | private Utils() { 24 | // private constructor 25 | } 26 | 27 | static void validateServiceInterface(Class service) { 28 | if (!service.isInterface()) { 29 | throw new IllegalArgumentException("API declarations must be interfaces."); 30 | } 31 | } 32 | 33 | static boolean hasUnresolvableType(Type type) { 34 | if (type instanceof Class) { 35 | return false; 36 | } 37 | if (type instanceof ParameterizedType) { 38 | ParameterizedType parameterizedType = (ParameterizedType) type; 39 | for (Type typeArgument : parameterizedType.getActualTypeArguments()) { 40 | if (hasUnresolvableType(typeArgument)) { 41 | return true; 42 | } 43 | } 44 | return false; 45 | } 46 | if (type instanceof GenericArrayType) { 47 | return hasUnresolvableType(((GenericArrayType) type).getGenericComponentType()); 48 | } 49 | if (type instanceof TypeVariable) { 50 | return true; 51 | } 52 | if (type instanceof WildcardType) { 53 | return true; 54 | } 55 | String className = type == null ? "null" : type.getClass().getName(); 56 | throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " 57 | + "GenericArrayType, but <" + type + "> is of type " + className); 58 | } 59 | 60 | static Class getRawType(Type type) { 61 | checkNotNull(type, "type == null"); 62 | 63 | if (type instanceof Class) { 64 | // Type is a normal class. 65 | return (Class) type; 66 | } 67 | if (type instanceof ParameterizedType) { 68 | ParameterizedType parameterizedType = (ParameterizedType) type; 69 | 70 | // I'm not exactly sure why getRawType() returns Type instead of Class. Neal isn't either but 71 | // suspects some pathological case related to nested classes exists. 72 | Type rawType = parameterizedType.getRawType(); 73 | if (!(rawType instanceof Class)) throw new IllegalArgumentException(); 74 | return (Class) rawType; 75 | } 76 | if (type instanceof GenericArrayType) { 77 | Type componentType = ((GenericArrayType) type).getGenericComponentType(); 78 | return Array.newInstance(getRawType(componentType), 0).getClass(); 79 | } 80 | if (type instanceof TypeVariable) { 81 | // We could use the variable's bounds, but that won't work if there are multiple. Having a raw 82 | // type that's more general than necessary is okay. 83 | return Object.class; 84 | } 85 | if (type instanceof WildcardType) { 86 | return getRawType(((WildcardType) type).getUpperBounds()[0]); 87 | } 88 | 89 | throw new IllegalArgumentException("Expected a Class, ParameterizedType, or " 90 | + "GenericArrayType, but <" + type + "> is of type " + type.getClass().getName()); 91 | } 92 | 93 | static T checkNotNull(T object, String message) { 94 | if (object == null) { 95 | throw new NullPointerException(message); 96 | } 97 | return object; 98 | } 99 | 100 | static boolean canOnlyBeInType(Class classType) { 101 | return isPrimitiveType(classType) || classType == String.class || classType == CharSequence.class; 102 | } 103 | 104 | static boolean isArrayType(int type) { 105 | return type == BaseTypeWrapper.TYPE_BYTEARRAY || type == BaseTypeWrapper.TYPE_SHORTARRAY || type == BaseTypeWrapper.TYPE_INTARRAY 106 | || type == BaseTypeWrapper.TYPE_LONGARRAY || type == BaseTypeWrapper.TYPE_FLOATARRAY || type == BaseTypeWrapper.TYPE_DOUBLEARRAY 107 | || type == BaseTypeWrapper.TYPE_BOOLEANARRAY || type == BaseTypeWrapper.TYPE_CHARARRAY || type == BaseTypeWrapper.TYPE_STRINGARRAY 108 | || type == BaseTypeWrapper.TYPE_CHARSEQUENCEARRAY || type == BaseTypeWrapper.TYPE_PARCELABLEARRAY; 109 | } 110 | 111 | static boolean isPrimitiveType(Class classType) { 112 | return classType.isPrimitive() || classType == Byte.class || classType == Short.class 113 | || classType == Integer.class || classType == Long.class || classType == Float.class 114 | || classType == Double.class || classType == Boolean.class || classType == Character.class; 115 | } 116 | 117 | static boolean isArrayType(Class classType) { 118 | return classType == byte[].class || classType == short[].class || classType == int[].class || classType == long[].class 119 | || classType == float[].class || classType == double[].class || classType == boolean[].class || classType == char[].class 120 | || classType == String[].class || classType == CharSequence[].class || classType == Parcelable[].class; 121 | } 122 | 123 | static int getTypeByClass(Class classType) { 124 | int type; 125 | if (classType == byte.class || classType == Byte.class) { 126 | type = BaseTypeWrapper.TYPE_BYTE; 127 | } else if (classType == short.class || classType == Short.class) { 128 | type = BaseTypeWrapper.TYPE_SHORT; 129 | } else if (classType == int.class || classType == Integer.class) { 130 | type = BaseTypeWrapper.TYPE_INT; 131 | } else if (classType == long.class || classType == Long.class) { 132 | type = BaseTypeWrapper.TYPE_LONG; 133 | } else if (classType == float.class || classType == Float.class) { 134 | type = BaseTypeWrapper.TYPE_FLOAT; 135 | } else if (classType == double.class || classType == Double.class) { 136 | type = BaseTypeWrapper.TYPE_DOUBLE; 137 | } else if (classType == boolean.class || classType == Boolean.class) { 138 | type = BaseTypeWrapper.TYPE_BOOLEAN; 139 | } else if (classType == char.class || classType == Character.class) { 140 | type = BaseTypeWrapper.TYPE_CHAR; 141 | } else if (classType == byte[].class) { 142 | type = BaseTypeWrapper.TYPE_BYTEARRAY; 143 | } else if (classType == short[].class) { 144 | type = BaseTypeWrapper.TYPE_SHORTARRAY; 145 | } else if (classType == int[].class) { 146 | type = BaseTypeWrapper.TYPE_INTARRAY; 147 | } else if (classType == long[].class) { 148 | type = BaseTypeWrapper.TYPE_LONGARRAY; 149 | } else if (classType == float[].class) { 150 | type = BaseTypeWrapper.TYPE_FLOATARRAY; 151 | } else if (classType == double[].class) { 152 | type = BaseTypeWrapper.TYPE_DOUBLEARRAY; 153 | } else if (classType == boolean[].class) { 154 | type = BaseTypeWrapper.TYPE_BOOLEANARRAY; 155 | } else if (classType == char[].class) { 156 | type = BaseTypeWrapper.TYPE_CHARARRAY; 157 | } else if (classType == String.class) { 158 | type = BaseTypeWrapper.TYPE_STRING; 159 | } else if (classType == String[].class) { 160 | type = BaseTypeWrapper.TYPE_STRINGARRAY; 161 | } else if (classType == CharSequence.class) { 162 | type = BaseTypeWrapper.TYPE_CHARSEQUENCE; 163 | } else if (classType == CharSequence[].class) { 164 | type = BaseTypeWrapper.TYPE_CHARSEQUENCEARRAY; 165 | } else if (Parcelable.class.isAssignableFrom(classType)) { 166 | type = BaseTypeWrapper.TYPE_PARCELABLE; 167 | } else if (Parcelable[].class.isAssignableFrom(classType)) { 168 | type = BaseTypeWrapper.TYPE_PARCELABLEARRAY; 169 | } else if (List.class.isAssignableFrom(classType)) { 170 | type = BaseTypeWrapper.TYPE_LIST; 171 | } else if (Map.class.isAssignableFrom(classType)) { 172 | type = BaseTypeWrapper.TYPE_MAP; 173 | } else { 174 | type = BaseTypeWrapper.TYPE_EMPTY; 175 | } 176 | return type; 177 | } 178 | 179 | static Object createObjFromClassName(String clsName) { 180 | Object obj = null; 181 | try { 182 | obj = Class.forName(clsName).newInstance(); 183 | } catch (InstantiationException e) { 184 | e.printStackTrace(); 185 | } catch (IllegalAccessException e) { 186 | e.printStackTrace(); 187 | } catch (ClassNotFoundException e) { 188 | e.printStackTrace(); 189 | } 190 | return obj; 191 | } 192 | 193 | static Object createArrayFromComponentType(String componentType, int length) { 194 | Object obj = null; 195 | try { 196 | Class clsType = Class.forName(componentType); 197 | obj = Array.newInstance(clsType, length); 198 | } catch (ClassNotFoundException e) { 199 | e.printStackTrace(); 200 | } 201 | return obj; 202 | } 203 | 204 | static boolean isStringBlank(String str) { 205 | return str == null || str.trim().length() == 0; 206 | } 207 | 208 | static Method getMethodReadFromParcel(Class cls) { 209 | checkNotNull(cls, "Class must not be null."); 210 | Method method = null; 211 | try { 212 | method = cls.getMethod("readFromParcel", Parcel.class); 213 | } catch (NoSuchMethodException e) { 214 | Logger.e(TAG, "No public readFromParcel() method in class:" + cls.getName()); 215 | } catch (SecurityException e) { 216 | Logger.e(TAG, "SecurityException when get readFromParcel() method in class:" + cls.getName()); 217 | } 218 | return method; 219 | } 220 | 221 | /** 222 | * Support for remote interfaces to extend interfaces, combine child class and method class. 223 | */ 224 | static String createClsName(String clsName, String methodClsName) { 225 | return clsName + '-' + methodClsName; 226 | } 227 | } 228 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/DefaultCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter; 2 | 3 | import com.codezjx.andlinker.Call; 4 | import com.codezjx.andlinker.CallAdapter; 5 | 6 | import java.lang.annotation.Annotation; 7 | import java.lang.reflect.Type; 8 | 9 | /** 10 | * Default {@linkplain CallAdapter.Factory call adapter} which adapt {@link Call} to the execute result. 11 | */ 12 | public class DefaultCallAdapterFactory extends CallAdapter.Factory { 13 | 14 | public static final CallAdapter.Factory INSTANCE = new DefaultCallAdapterFactory(); 15 | 16 | @Override 17 | public CallAdapter get(final Type returnType, Annotation[] annotations) { 18 | return new CallAdapter() { 19 | @Override 20 | public Object adapt(Call call) { 21 | Class rawType = getRawType(returnType); 22 | Object result = call.execute(); 23 | if (result == null) { 24 | result = createDefaultResult(rawType); 25 | } 26 | // Return the result 27 | return result; 28 | } 29 | }; 30 | } 31 | 32 | private Object createDefaultResult(Class returnType) { 33 | // For java.lang.NullPointerException: Expected to unbox a 'xxx' primitive type but was returned null 34 | // Visit https://github.com/codezjx/AndLinker/issues/14 35 | if (returnType == byte.class) { 36 | return (byte) 0; 37 | } else if (returnType == short.class) { 38 | return (short) 0; 39 | } else if (returnType == int.class || returnType == long.class || returnType == float.class || returnType == double.class) { 40 | return 0; 41 | } else if (returnType == boolean.class) { 42 | return false; 43 | } else if (returnType == char.class) { 44 | return ' '; 45 | } 46 | return null; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/OriginalCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter; 2 | 3 | import android.os.Handler; 4 | import android.os.Looper; 5 | 6 | import com.codezjx.andlinker.Call; 7 | import com.codezjx.andlinker.CallAdapter; 8 | import com.codezjx.andlinker.Callback; 9 | 10 | import java.lang.annotation.Annotation; 11 | import java.lang.reflect.Type; 12 | import java.util.concurrent.Executor; 13 | 14 | /** 15 | * A {@linkplain CallAdapter.Factory call adapter} which uses the original {@link Call}, just return as is. 16 | */ 17 | public class OriginalCallAdapterFactory extends CallAdapter.Factory { 18 | 19 | private Executor mCallbackExecutor; 20 | 21 | private OriginalCallAdapterFactory(Executor callbackExecutor) { 22 | mCallbackExecutor = callbackExecutor; 23 | } 24 | 25 | /** 26 | * Create {@link OriginalCallAdapterFactory} with default Android main thread executor. 27 | */ 28 | public static OriginalCallAdapterFactory create() { 29 | return new OriginalCallAdapterFactory(new MainThreadExecutor()); 30 | } 31 | 32 | /** 33 | * Create {@link OriginalCallAdapterFactory} with specify {@link Executor} 34 | * @param callbackExecutor The executor on which {@link Callback} methods are invoked 35 | * when returning {@link Call} from your service method. 36 | */ 37 | public static OriginalCallAdapterFactory create(Executor callbackExecutor) { 38 | return new OriginalCallAdapterFactory(callbackExecutor); 39 | } 40 | 41 | @Override 42 | public CallAdapter get(Type returnType, Annotation[] annotations) { 43 | if (getRawType(returnType) != Call.class) { 44 | return null; 45 | } 46 | 47 | return new CallAdapter>() { 48 | @Override public Call adapt(Call call) { 49 | // Return executor wrapper call 50 | return new ExecutorCallbackCall<>(mCallbackExecutor, call); 51 | } 52 | }; 53 | } 54 | 55 | static final class ExecutorCallbackCall implements Call { 56 | final Executor mCallbackExecutor; 57 | final Call mDelegate; 58 | 59 | ExecutorCallbackCall(Executor callbackExecutor, Call delegate) { 60 | mCallbackExecutor = callbackExecutor; 61 | mDelegate = delegate; 62 | } 63 | 64 | @Override 65 | public T execute() { 66 | return mDelegate.execute(); 67 | } 68 | 69 | @Override 70 | public void enqueue(final Callback callback) { 71 | if (callback == null) { 72 | throw new NullPointerException("callback == null"); 73 | } 74 | mDelegate.enqueue(new Callback() { 75 | @Override 76 | public void onResponse(Call call, final T response) { 77 | mCallbackExecutor.execute(new Runnable() { 78 | @Override 79 | public void run() { 80 | if (mDelegate.isCanceled()) { 81 | // Emulate behavior of throwing/delivering an IOException on cancellation. 82 | callback.onFailure(ExecutorCallbackCall.this, new IllegalStateException("Already canceled")); 83 | } else { 84 | callback.onResponse(ExecutorCallbackCall.this, response); 85 | } 86 | } 87 | }); 88 | } 89 | 90 | @Override 91 | public void onFailure(Call call, final Throwable t) { 92 | mCallbackExecutor.execute(new Runnable() { 93 | @Override 94 | public void run() { 95 | callback.onFailure(ExecutorCallbackCall.this, t); 96 | } 97 | }); 98 | } 99 | }); 100 | } 101 | 102 | @Override 103 | public boolean isExecuted() { 104 | return mDelegate.isExecuted(); 105 | } 106 | 107 | @Override 108 | public void cancel() { 109 | mDelegate.cancel(); 110 | } 111 | 112 | @Override 113 | public boolean isCanceled() { 114 | return mDelegate.isCanceled(); 115 | } 116 | } 117 | 118 | private static class MainThreadExecutor implements Executor { 119 | private final Handler handler = new Handler(Looper.getMainLooper()); 120 | 121 | @Override public void execute(Runnable r) { 122 | handler.post(r); 123 | } 124 | } 125 | } 126 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava/CallArbiter.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava; 2 | 3 | import com.codezjx.andlinker.Call; 4 | 5 | import java.util.concurrent.atomic.AtomicInteger; 6 | 7 | import rx.Producer; 8 | import rx.Subscriber; 9 | import rx.Subscription; 10 | import rx.exceptions.CompositeException; 11 | import rx.exceptions.Exceptions; 12 | import rx.exceptions.OnCompletedFailedException; 13 | import rx.exceptions.OnErrorFailedException; 14 | import rx.exceptions.OnErrorNotImplementedException; 15 | import rx.plugins.RxJavaPlugins; 16 | 17 | /** 18 | * Created by codezjx on 2017/10/16.
19 | */ 20 | final class CallArbiter extends AtomicInteger implements Subscription, Producer { 21 | private static final int STATE_WAITING = 0; 22 | private static final int STATE_REQUESTED = 1; 23 | private static final int STATE_HAS_RESPONSE = 2; 24 | private static final int STATE_TERMINATED = 3; 25 | 26 | private final Call mCall; 27 | private final Subscriber mSubscriber; 28 | 29 | private volatile T mResponse; 30 | 31 | CallArbiter(Call call, Subscriber subscriber) { 32 | super(STATE_WAITING); 33 | 34 | mCall = call; 35 | mSubscriber = subscriber; 36 | } 37 | 38 | @Override 39 | public void unsubscribe() { 40 | mCall.cancel(); 41 | } 42 | 43 | @Override 44 | public boolean isUnsubscribed() { 45 | return mCall.isCanceled(); 46 | } 47 | 48 | @Override 49 | public void request(long amount) { 50 | if (amount == 0) { 51 | return; 52 | } 53 | while (true) { 54 | int state = get(); 55 | switch (state) { 56 | case STATE_WAITING: 57 | if (compareAndSet(STATE_WAITING, STATE_REQUESTED)) { 58 | return; 59 | } 60 | break; // State transition failed. Try again. 61 | 62 | case STATE_HAS_RESPONSE: 63 | if (compareAndSet(STATE_HAS_RESPONSE, STATE_TERMINATED)) { 64 | deliverResponse(mResponse); 65 | return; 66 | } 67 | break; // State transition failed. Try again. 68 | 69 | case STATE_REQUESTED: 70 | case STATE_TERMINATED: 71 | return; // Nothing to do. 72 | 73 | default: 74 | throw new IllegalStateException("Unknown state: " + state); 75 | } 76 | } 77 | } 78 | 79 | void emitResponse(T response) { 80 | while (true) { 81 | int state = get(); 82 | switch (state) { 83 | case STATE_WAITING: 84 | this.mResponse = response; 85 | if (compareAndSet(STATE_WAITING, STATE_HAS_RESPONSE)) { 86 | return; 87 | } 88 | break; // State transition failed. Try again. 89 | 90 | case STATE_REQUESTED: 91 | if (compareAndSet(STATE_REQUESTED, STATE_TERMINATED)) { 92 | deliverResponse(response); 93 | return; 94 | } 95 | break; // State transition failed. Try again. 96 | 97 | case STATE_HAS_RESPONSE: 98 | case STATE_TERMINATED: 99 | throw new AssertionError(); 100 | 101 | default: 102 | throw new IllegalStateException("Unknown state: " + state); 103 | } 104 | } 105 | } 106 | 107 | private void deliverResponse(T response) { 108 | try { 109 | if (!isUnsubscribed()) { 110 | mSubscriber.onNext(response); 111 | } 112 | } catch (OnCompletedFailedException 113 | | OnErrorFailedException 114 | | OnErrorNotImplementedException e) { 115 | RxJavaPlugins.getInstance().getErrorHandler().handleError(e); 116 | return; 117 | } catch (Throwable t) { 118 | Exceptions.throwIfFatal(t); 119 | try { 120 | mSubscriber.onError(t); 121 | } catch (OnCompletedFailedException 122 | | OnErrorFailedException 123 | | OnErrorNotImplementedException e) { 124 | RxJavaPlugins.getInstance().getErrorHandler().handleError(e); 125 | } catch (Throwable inner) { 126 | Exceptions.throwIfFatal(inner); 127 | CompositeException composite = new CompositeException(t, inner); 128 | RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); 129 | } 130 | return; 131 | } 132 | try { 133 | if (!isUnsubscribed()) { 134 | mSubscriber.onCompleted(); 135 | } 136 | } catch (OnCompletedFailedException 137 | | OnErrorFailedException 138 | | OnErrorNotImplementedException e) { 139 | RxJavaPlugins.getInstance().getErrorHandler().handleError(e); 140 | } catch (Throwable t) { 141 | Exceptions.throwIfFatal(t); 142 | RxJavaPlugins.getInstance().getErrorHandler().handleError(t); 143 | } 144 | } 145 | 146 | void emitError(Throwable t) { 147 | set(STATE_TERMINATED); 148 | 149 | if (!isUnsubscribed()) { 150 | try { 151 | mSubscriber.onError(t); 152 | } catch (OnCompletedFailedException 153 | | OnErrorFailedException 154 | | OnErrorNotImplementedException e) { 155 | RxJavaPlugins.getInstance().getErrorHandler().handleError(e); 156 | } catch (Throwable inner) { 157 | Exceptions.throwIfFatal(inner); 158 | CompositeException composite = new CompositeException(t, inner); 159 | RxJavaPlugins.getInstance().getErrorHandler().handleError(composite); 160 | } 161 | } 162 | } 163 | } 164 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava/CallExecuteOnSubscribe.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava; 2 | 3 | import com.codezjx.andlinker.Call; 4 | 5 | import rx.Observable.OnSubscribe; 6 | import rx.Subscriber; 7 | import rx.exceptions.Exceptions; 8 | 9 | /** 10 | * Created by codezjx on 2017/10/16.
11 | */ 12 | final class CallExecuteOnSubscribe implements OnSubscribe { 13 | 14 | private final Call mCall; 15 | 16 | CallExecuteOnSubscribe(Call call) { 17 | mCall = call; 18 | } 19 | 20 | @Override 21 | public void call(Subscriber subscriber) { 22 | CallArbiter arbiter = new CallArbiter<>(mCall, subscriber); 23 | subscriber.add(arbiter); 24 | subscriber.setProducer(arbiter); 25 | 26 | T response; 27 | try { 28 | response = mCall.execute(); 29 | } catch (Throwable t) { 30 | Exceptions.throwIfFatal(t); 31 | arbiter.emitError(t); 32 | return; 33 | } 34 | arbiter.emitResponse(response); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava/RxJavaCallAdapter.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava; 2 | 3 | import com.codezjx.andlinker.Call; 4 | import com.codezjx.andlinker.CallAdapter; 5 | 6 | import rx.Observable; 7 | import rx.Observable.OnSubscribe; 8 | import rx.Scheduler; 9 | 10 | 11 | /** 12 | * Created by codezjx on 2017/10/16.
13 | */ 14 | final class RxJavaCallAdapter implements CallAdapter> { 15 | 16 | private final Scheduler mScheduler; 17 | 18 | RxJavaCallAdapter(Scheduler scheduler) { 19 | mScheduler = scheduler; 20 | } 21 | 22 | @Override 23 | public Observable adapt(Call call) { 24 | OnSubscribe subscribe = new CallExecuteOnSubscribe<>(call); 25 | Observable observable = Observable.create(subscribe); 26 | 27 | if (mScheduler != null) { 28 | observable = observable.subscribeOn(mScheduler); 29 | } 30 | 31 | return observable; 32 | } 33 | 34 | 35 | } 36 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava/RxJavaCallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava; 2 | 3 | import com.codezjx.andlinker.CallAdapter; 4 | 5 | import java.lang.annotation.Annotation; 6 | import java.lang.reflect.ParameterizedType; 7 | import java.lang.reflect.Type; 8 | 9 | import rx.Observable; 10 | import rx.Scheduler; 11 | 12 | 13 | /** 14 | * A {@linkplain CallAdapter.Factory call adapter} which uses RxJava for creating observables. 15 | */ 16 | public class RxJavaCallAdapterFactory extends CallAdapter.Factory { 17 | 18 | private final Scheduler mScheduler; 19 | 20 | private RxJavaCallAdapterFactory(Scheduler scheduler) { 21 | mScheduler = scheduler; 22 | } 23 | 24 | public static RxJavaCallAdapterFactory create() { 25 | return new RxJavaCallAdapterFactory(null); 26 | } 27 | 28 | public static RxJavaCallAdapterFactory createWithScheduler(Scheduler scheduler) { 29 | if (scheduler == null) throw new NullPointerException("scheduler == null"); 30 | return new RxJavaCallAdapterFactory(scheduler); 31 | } 32 | 33 | @Override 34 | public CallAdapter get(Type returnType, Annotation[] annotations) { 35 | Class rawType = getRawType(returnType); 36 | if (rawType != Observable.class) { 37 | return null; 38 | } 39 | 40 | if (!(returnType instanceof ParameterizedType)) { 41 | throw new IllegalStateException("Observable return type must be parameterized" 42 | + " as Observable or Observable"); 43 | } 44 | return new RxJavaCallAdapter(mScheduler); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava2/CallExecuteObservable.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava2; 2 | 3 | import com.codezjx.andlinker.Call; 4 | 5 | import io.reactivex.Observable; 6 | import io.reactivex.Observer; 7 | import io.reactivex.disposables.Disposable; 8 | import io.reactivex.exceptions.CompositeException; 9 | import io.reactivex.exceptions.Exceptions; 10 | import io.reactivex.plugins.RxJavaPlugins; 11 | 12 | /** 13 | * Created by codezjx on 2017/10/14.
14 | */ 15 | final class CallExecuteObservable extends Observable { 16 | 17 | private final Call mCall; 18 | 19 | CallExecuteObservable(Call call) { 20 | mCall = call; 21 | } 22 | 23 | @Override 24 | protected void subscribeActual(Observer observer) { 25 | observer.onSubscribe(new CallDisposable(mCall)); 26 | boolean terminated = false; 27 | try { 28 | T response = mCall.execute(); 29 | if (!mCall.isCanceled()) { 30 | observer.onNext(response); 31 | } 32 | if (!mCall.isCanceled()) { 33 | terminated = true; 34 | observer.onComplete(); 35 | } 36 | } catch (Throwable t) { 37 | Exceptions.throwIfFatal(t); 38 | if (terminated) { 39 | RxJavaPlugins.onError(t); 40 | } else if (!mCall.isCanceled()) { 41 | try { 42 | observer.onError(t); 43 | } catch (Throwable inner) { 44 | Exceptions.throwIfFatal(inner); 45 | RxJavaPlugins.onError(new CompositeException(t, inner)); 46 | } 47 | } 48 | } 49 | } 50 | 51 | private static final class CallDisposable implements Disposable { 52 | private final Call mCall; 53 | 54 | CallDisposable(Call call) { 55 | this.mCall = call; 56 | } 57 | 58 | @Override public void dispose() { 59 | mCall.cancel(); 60 | } 61 | 62 | @Override public boolean isDisposed() { 63 | return mCall.isCanceled(); 64 | } 65 | } 66 | } -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava2/RxJava2CallAdapter.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava2; 2 | 3 | import com.codezjx.andlinker.Call; 4 | import com.codezjx.andlinker.CallAdapter; 5 | 6 | import io.reactivex.BackpressureStrategy; 7 | import io.reactivex.Observable; 8 | import io.reactivex.Scheduler; 9 | 10 | /** 11 | * Created by codezjx on 2017/10/14.
12 | */ 13 | final class RxJava2CallAdapter implements CallAdapter { 14 | 15 | private final Scheduler mScheduler; 16 | private final boolean mIsFlowable; 17 | 18 | RxJava2CallAdapter(Scheduler scheduler, boolean isFlowable) { 19 | mScheduler = scheduler; 20 | mIsFlowable = isFlowable; 21 | } 22 | 23 | @Override 24 | public Object adapt(Call call) { 25 | Observable observable = new CallExecuteObservable<>(call); 26 | 27 | if (mScheduler != null) { 28 | observable = observable.subscribeOn(mScheduler); 29 | } 30 | 31 | if (mIsFlowable) { 32 | return observable.toFlowable(BackpressureStrategy.LATEST); 33 | } 34 | 35 | return observable; 36 | } 37 | 38 | } -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/adapter/rxjava2/RxJava2CallAdapterFactory.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.adapter.rxjava2; 2 | 3 | import com.codezjx.andlinker.CallAdapter; 4 | 5 | import java.lang.annotation.Annotation; 6 | import java.lang.reflect.ParameterizedType; 7 | import java.lang.reflect.Type; 8 | 9 | import io.reactivex.Flowable; 10 | import io.reactivex.Observable; 11 | import io.reactivex.Scheduler; 12 | 13 | /** 14 | * A {@linkplain CallAdapter.Factory call adapter} which uses RxJava 2 for creating observables. 15 | */ 16 | public class RxJava2CallAdapterFactory extends CallAdapter.Factory { 17 | 18 | private final Scheduler mScheduler; 19 | 20 | private RxJava2CallAdapterFactory(Scheduler scheduler) { 21 | mScheduler = scheduler; 22 | } 23 | 24 | public static RxJava2CallAdapterFactory create() { 25 | return new RxJava2CallAdapterFactory(null); 26 | } 27 | 28 | public static RxJava2CallAdapterFactory createWithScheduler(Scheduler scheduler) { 29 | if (scheduler == null) throw new NullPointerException("scheduler == null"); 30 | return new RxJava2CallAdapterFactory(scheduler); 31 | } 32 | 33 | @Override 34 | public CallAdapter get(Type returnType, Annotation[] annotations) { 35 | Class rawType = getRawType(returnType); 36 | boolean isFlowable = (rawType == Flowable.class); 37 | if (rawType != Observable.class && !isFlowable) { 38 | return null; 39 | } 40 | 41 | if (!(returnType instanceof ParameterizedType)) { 42 | String name = isFlowable ? "Flowable" : "Observable"; 43 | throw new IllegalStateException(name + " return type must be parameterized" 44 | + " as " + name + " or " + name + ""); 45 | } 46 | 47 | return new RxJava2CallAdapter(mScheduler, isFlowable); 48 | } 49 | 50 | } 51 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/Callback.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.PARAMETER; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Indicate a parameter is a remote callback type. 11 | */ 12 | @Target(PARAMETER) 13 | @Retention(RUNTIME) 14 | public @interface Callback { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/In.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.PARAMETER; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Directional tag indicating which way the data goes, same as "in" tag in AIDL. 11 | */ 12 | @Target(PARAMETER) 13 | @Retention(RUNTIME) 14 | public @interface In { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/Inout.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.PARAMETER; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Directional tag indicating which way the data goes, same as "inout" tag in AIDL. 11 | */ 12 | @Target(PARAMETER) 13 | @Retention(RUNTIME) 14 | public @interface Inout { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/OneWay.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.METHOD; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Indicate a remote call does not block, it simply sends the transaction data and immediately 11 | * returns, same as "oneway" tag in AIDL. 12 | */ 13 | @Target(METHOD) 14 | @Retention(RUNTIME) 15 | public @interface OneWay { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/Out.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.PARAMETER; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Directional tag indicating which way the data goes, same as "out" tag in AIDL. 11 | */ 12 | @Target(PARAMETER) 13 | @Retention(RUNTIME) 14 | public @interface Out { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /andlinker/src/main/java/com/codezjx/andlinker/annotation/RemoteInterface.java: -------------------------------------------------------------------------------- 1 | package com.codezjx.andlinker.annotation; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.TYPE; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | /** 10 | * Specify the interface as remote service interface. 11 | */ 12 | @Target(TYPE) 13 | @Retention(RUNTIME) 14 | public @interface RemoteInterface { 15 | 16 | } 17 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | // Top-level build file where you can add configuration options common to all sub-projects/modules. 2 | 3 | buildscript { 4 | 5 | repositories { 6 | google() 7 | mavenCentral() 8 | } 9 | dependencies { 10 | classpath 'com.android.tools.build:gradle:3.4.2' 11 | 12 | // NOTE: Do not place your application dependencies here; they belong 13 | // in the individual module build.gradle files 14 | } 15 | } 16 | 17 | allprojects { 18 | repositories { 19 | google() 20 | mavenCentral() 21 | } 22 | } 23 | 24 | task clean(type: Delete) { 25 | delete rootProject.buildDir 26 | } 27 | 28 | apply from: 'dependencies.gradle' -------------------------------------------------------------------------------- /dependencies.gradle: -------------------------------------------------------------------------------- 1 | ext.versions = [ 2 | 'compileSdk': 26, 3 | 'minSdk': 14, 4 | 'targetSdk': 26, 5 | 6 | 'rxjava': '1.3.6', 7 | 'rxandroid': '1.2.1', 8 | 'rxjava2': '2.1.10', 9 | 'rxandroid2': '2.0.2', 10 | 'butterKnife': '8.8.1' 11 | ] 12 | 13 | ext.deps = [ 14 | 'rx': [ 15 | 'java': "io.reactivex:rxjava:${versions.rxjava}", 16 | 'android': "io.reactivex:rxandroid:${versions.rxandroid}", 17 | 'java2': "io.reactivex.rxjava2:rxjava:${versions.rxjava2}", 18 | 'android2': "io.reactivex.rxjava2:rxandroid:${versions.rxandroid2}" 19 | ], 20 | 'butterKnife': [ 21 | 'runtime': "com.jakewharton:butterknife:${versions.butterKnife}", 22 | 'compiler': "com.jakewharton:butterknife-compiler:${versions.butterKnife}", 23 | ] 24 | ] -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | # Project-wide Gradle settings. 2 | 3 | # IDE (e.g. Android Studio) users: 4 | # Gradle settings configured through the IDE *will override* 5 | # any settings specified in this file. 6 | 7 | # For more details on how to configure your build environment visit 8 | # http://www.gradle.org/docs/current/userguide/build_environment.html 9 | 10 | # Specifies the JVM arguments used for the daemon process. 11 | # The setting is particularly useful for tweaking memory settings. 12 | org.gradle.jvmargs=-Xmx2048m 13 | 14 | # When configured, Gradle will run in incubating parallel mode. 15 | # This option should only be used with decoupled projects. More details, visit 16 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects 17 | # org.gradle.parallel=true 18 | -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codezjx/AndLinker/7ae01bfd87ddcf021319148a8727a95345cf350e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Jun 03 09:22:27 CST 2019 2 | distributionBase=GRADLE_USER_HOME 3 | distributionPath=wrapper/dists 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | distributionUrl=https\://services.gradle.org/distributions/gradle-5.1.1-all.zip 7 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | ############################################################################## 4 | ## 5 | ## Gradle start up script for UN*X 6 | ## 7 | ############################################################################## 8 | 9 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 10 | DEFAULT_JVM_OPTS="" 11 | 12 | APP_NAME="Gradle" 13 | APP_BASE_NAME=`basename "$0"` 14 | 15 | # Use the maximum available, or set MAX_FD != -1 to use that value. 16 | MAX_FD="maximum" 17 | 18 | warn ( ) { 19 | echo "$*" 20 | } 21 | 22 | die ( ) { 23 | echo 24 | echo "$*" 25 | echo 26 | exit 1 27 | } 28 | 29 | # OS specific support (must be 'true' or 'false'). 30 | cygwin=false 31 | msys=false 32 | darwin=false 33 | case "`uname`" in 34 | CYGWIN* ) 35 | cygwin=true 36 | ;; 37 | Darwin* ) 38 | darwin=true 39 | ;; 40 | MINGW* ) 41 | msys=true 42 | ;; 43 | esac 44 | 45 | # Attempt to set APP_HOME 46 | # Resolve links: $0 may be a link 47 | PRG="$0" 48 | # Need this for relative symlinks. 49 | while [ -h "$PRG" ] ; do 50 | ls=`ls -ld "$PRG"` 51 | link=`expr "$ls" : '.*-> \(.*\)$'` 52 | if expr "$link" : '/.*' > /dev/null; then 53 | PRG="$link" 54 | else 55 | PRG=`dirname "$PRG"`"/$link" 56 | fi 57 | done 58 | SAVED="`pwd`" 59 | cd "`dirname \"$PRG\"`/" >/dev/null 60 | APP_HOME="`pwd -P`" 61 | cd "$SAVED" >/dev/null 62 | 63 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 64 | 65 | # Determine the Java command to use to start the JVM. 66 | if [ -n "$JAVA_HOME" ] ; then 67 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 68 | # IBM's JDK on AIX uses strange locations for the executables 69 | JAVACMD="$JAVA_HOME/jre/sh/java" 70 | else 71 | JAVACMD="$JAVA_HOME/bin/java" 72 | fi 73 | if [ ! -x "$JAVACMD" ] ; then 74 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 75 | 76 | Please set the JAVA_HOME variable in your environment to match the 77 | location of your Java installation." 78 | fi 79 | else 80 | JAVACMD="java" 81 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 82 | 83 | Please set the JAVA_HOME variable in your environment to match the 84 | location of your Java installation." 85 | fi 86 | 87 | # Increase the maximum file descriptors if we can. 88 | if [ "$cygwin" = "false" -a "$darwin" = "false" ] ; then 89 | MAX_FD_LIMIT=`ulimit -H -n` 90 | if [ $? -eq 0 ] ; then 91 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then 92 | MAX_FD="$MAX_FD_LIMIT" 93 | fi 94 | ulimit -n $MAX_FD 95 | if [ $? -ne 0 ] ; then 96 | warn "Could not set maximum file descriptor limit: $MAX_FD" 97 | fi 98 | else 99 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" 100 | fi 101 | fi 102 | 103 | # For Darwin, add options to specify how the application appears in the dock 104 | if $darwin; then 105 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" 106 | fi 107 | 108 | # For Cygwin, switch paths to Windows format before running java 109 | if $cygwin ; then 110 | APP_HOME=`cygpath --path --mixed "$APP_HOME"` 111 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` 112 | JAVACMD=`cygpath --unix "$JAVACMD"` 113 | 114 | # We build the pattern for arguments to be converted via cygpath 115 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` 116 | SEP="" 117 | for dir in $ROOTDIRSRAW ; do 118 | ROOTDIRS="$ROOTDIRS$SEP$dir" 119 | SEP="|" 120 | done 121 | OURCYGPATTERN="(^($ROOTDIRS))" 122 | # Add a user-defined pattern to the cygpath arguments 123 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then 124 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" 125 | fi 126 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 127 | i=0 128 | for arg in "$@" ; do 129 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` 130 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option 131 | 132 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition 133 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` 134 | else 135 | eval `echo args$i`="\"$arg\"" 136 | fi 137 | i=$((i+1)) 138 | done 139 | case $i in 140 | (0) set -- ;; 141 | (1) set -- "$args0" ;; 142 | (2) set -- "$args0" "$args1" ;; 143 | (3) set -- "$args0" "$args1" "$args2" ;; 144 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;; 145 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; 146 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; 147 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; 148 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; 149 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; 150 | esac 151 | fi 152 | 153 | # Split up the JVM_OPTS And GRADLE_OPTS values into an array, following the shell quoting and substitution rules 154 | function splitJvmOpts() { 155 | JVM_OPTS=("$@") 156 | } 157 | eval splitJvmOpts $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS 158 | JVM_OPTS[${#JVM_OPTS[*]}]="-Dorg.gradle.appname=$APP_BASE_NAME" 159 | 160 | exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" 161 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @if "%DEBUG%" == "" @echo off 2 | @rem ########################################################################## 3 | @rem 4 | @rem Gradle startup script for Windows 5 | @rem 6 | @rem ########################################################################## 7 | 8 | @rem Set local scope for the variables with windows NT shell 9 | if "%OS%"=="Windows_NT" setlocal 10 | 11 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 12 | set DEFAULT_JVM_OPTS= 13 | 14 | set DIRNAME=%~dp0 15 | if "%DIRNAME%" == "" set DIRNAME=. 16 | set APP_BASE_NAME=%~n0 17 | set APP_HOME=%DIRNAME% 18 | 19 | @rem Find java.exe 20 | if defined JAVA_HOME goto findJavaFromJavaHome 21 | 22 | set JAVA_EXE=java.exe 23 | %JAVA_EXE% -version >NUL 2>&1 24 | if "%ERRORLEVEL%" == "0" goto init 25 | 26 | echo. 27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 28 | echo. 29 | echo Please set the JAVA_HOME variable in your environment to match the 30 | echo location of your Java installation. 31 | 32 | goto fail 33 | 34 | :findJavaFromJavaHome 35 | set JAVA_HOME=%JAVA_HOME:"=% 36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 37 | 38 | if exist "%JAVA_EXE%" goto init 39 | 40 | echo. 41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 42 | echo. 43 | echo Please set the JAVA_HOME variable in your environment to match the 44 | echo location of your Java installation. 45 | 46 | goto fail 47 | 48 | :init 49 | @rem Get command-line arguments, handling Windowz variants 50 | 51 | if not "%OS%" == "Windows_NT" goto win9xME_args 52 | if "%@eval[2+2]" == "4" goto 4NT_args 53 | 54 | :win9xME_args 55 | @rem Slurp the command line arguments. 56 | set CMD_LINE_ARGS= 57 | set _SKIP=2 58 | 59 | :win9xME_args_slurp 60 | if "x%~1" == "x" goto execute 61 | 62 | set CMD_LINE_ARGS=%* 63 | goto execute 64 | 65 | :4NT_args 66 | @rem Get arguments from the 4NT Shell from JP Software 67 | set CMD_LINE_ARGS=%$ 68 | 69 | :execute 70 | @rem Setup the command line 71 | 72 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 73 | 74 | @rem Execute Gradle 75 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% 76 | 77 | :end 78 | @rem End local scope for the variables with windows NT shell 79 | if "%ERRORLEVEL%"=="0" goto mainEnd 80 | 81 | :fail 82 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 83 | rem the _cmd.exe /c_ return code! 84 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 85 | exit /b 1 86 | 87 | :mainEnd 88 | if "%OS%"=="Windows_NT" endlocal 89 | 90 | :omega 91 | -------------------------------------------------------------------------------- /sample/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sample/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 26 5 | 6 | defaultConfig { 7 | applicationId "com.example.andlinker" 8 | minSdkVersion 17 9 | targetSdkVersion 26 10 | versionCode 1 11 | versionName "1.0" 12 | 13 | } 14 | 15 | buildTypes { 16 | release { 17 | minifyEnabled false 18 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 19 | } 20 | } 21 | 22 | compileOptions { 23 | sourceCompatibility JavaVersion.VERSION_1_8 24 | targetCompatibility JavaVersion.VERSION_1_8 25 | } 26 | 27 | } 28 | 29 | dependencies { 30 | implementation fileTree(dir: 'libs', include: ['*.jar']) 31 | implementation project(':andlinker') 32 | 33 | // support 34 | implementation 'com.android.support:appcompat-v7:26.1.0' 35 | implementation 'com.android.support.constraint:constraint-layout:1.0.2' 36 | 37 | // butterknife 38 | implementation deps.butterKnife.runtime 39 | annotationProcessor deps.butterKnife.compiler 40 | 41 | // rxjava 42 | implementation deps.rx.java2 43 | implementation deps.rx.android2 44 | } 45 | -------------------------------------------------------------------------------- /sample/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile 22 | -------------------------------------------------------------------------------- /sample/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/BindingActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import android.graphics.Rect; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.os.Bundle; 6 | import android.util.Log; 7 | import android.view.View; 8 | import android.widget.Toast; 9 | 10 | import com.codezjx.andlinker.AndLinker; 11 | import com.codezjx.andlinker.Call; 12 | import com.codezjx.andlinker.Callback; 13 | import com.codezjx.andlinker.adapter.OriginalCallAdapterFactory; 14 | import com.codezjx.andlinker.adapter.rxjava2.RxJava2CallAdapterFactory; 15 | import com.codezjx.andlinker.annotation.RemoteInterface; 16 | 17 | import java.util.List; 18 | 19 | import butterknife.ButterKnife; 20 | import butterknife.OnClick; 21 | import io.reactivex.Observable; 22 | import io.reactivex.android.schedulers.AndroidSchedulers; 23 | import io.reactivex.schedulers.Schedulers; 24 | 25 | public class BindingActivity extends AppCompatActivity implements AndLinker.BindCallback { 26 | 27 | private static final String TAG = "BindingActivity"; 28 | private static final String REMOTE_SERVICE_PKG = "com.example.andlinker"; 29 | public static final String REMOTE_SERVICE_ACTION = "com.example.andlinker.REMOTE_SERVICE_ACTION"; 30 | 31 | private AndLinker mLinker; 32 | private IRemoteService mRemoteService; 33 | private IRemoteTask mRemoteTask; 34 | 35 | @Override 36 | protected void onCreate(Bundle savedInstanceState) { 37 | super.onCreate(savedInstanceState); 38 | setContentView(R.layout.activity_binding); 39 | ButterKnife.bind(this); 40 | 41 | AndLinker.enableLogger(true); 42 | mLinker = new AndLinker.Builder(this) 43 | .packageName(REMOTE_SERVICE_PKG) 44 | .action(REMOTE_SERVICE_ACTION) 45 | // Specify the callback executor by yourself 46 | //.addCallAdapterFactory(OriginalCallAdapterFactory.create(callbackExecutor)) 47 | .addCallAdapterFactory(OriginalCallAdapterFactory.create()) // Basic 48 | .addCallAdapterFactory(RxJava2CallAdapterFactory.create()) // RxJava2 49 | .build(); 50 | mLinker.setBindCallback(this); 51 | mLinker.registerObject(mRemoteCallback); 52 | mLinker.bind(); 53 | } 54 | 55 | @Override 56 | public void onBind() { 57 | Log.d(TAG, "AndLinker onBind()"); 58 | mRemoteService = mLinker.create(IRemoteService.class); 59 | mRemoteService.init("msg from client"); 60 | mRemoteTask = mLinker.create(IRemoteTask.class); 61 | } 62 | 63 | @Override 64 | public void onUnBind() { 65 | Log.d(TAG, "AndLinker onUnBind()"); 66 | mRemoteService = null; 67 | mRemoteTask = null; 68 | } 69 | 70 | @OnClick({R.id.btn_pid, R.id.btn_basic_types, R.id.btn_call_adapter, R.id.btn_rxjava2_call_adapter, 71 | R.id.btn_callback, R.id.btn_directional, R.id.btn_oneway}) 72 | public void onClick(View view) { 73 | if (mRemoteService == null || mRemoteTask == null || !mLinker.isBind()) { 74 | Log.e(TAG, "AndLinker was not bind to the service."); 75 | return; 76 | } 77 | switch (view.getId()) { 78 | case R.id.btn_pid: 79 | Toast.makeText(this, "Server pid: " + mRemoteService.getPid(), Toast.LENGTH_SHORT).show(); 80 | mRemoteService.getPid(); 81 | break; 82 | case R.id.btn_basic_types: 83 | mRemoteService.basicTypes(1, 2L, true, 3.0f, 4.0d, "str"); 84 | break; 85 | case R.id.btn_call_adapter: 86 | Call call = mRemoteTask.remoteCalculate(10, 20); 87 | 88 | // Synchronous Request 89 | // int result = call.execute(); 90 | // Log.d("BindingActivity", "remoteCalculate() result:" + result); 91 | 92 | // Asynchronous Request 93 | call.enqueue(new Callback() { 94 | @Override 95 | public void onResponse(Call call, Integer response) { 96 | Toast.makeText(BindingActivity.this, "remoteCalculate() onResponse: " + response, Toast.LENGTH_SHORT).show(); 97 | } 98 | 99 | @Override 100 | public void onFailure(Call call, Throwable t) { 101 | Toast.makeText(BindingActivity.this, "remoteCalculate() failure: " + t.getMessage(), Toast.LENGTH_SHORT).show(); 102 | } 103 | }); 104 | break; 105 | case R.id.btn_rxjava2_call_adapter: 106 | mRemoteTask.getDatas() 107 | .subscribeOn(Schedulers.io()) 108 | .observeOn(AndroidSchedulers.mainThread()) 109 | .subscribe(datas -> Toast.makeText(this, "getDatas() return: " + datas, Toast.LENGTH_LONG).show()); 110 | break; 111 | case R.id.btn_callback: 112 | mRemoteService.registerCallback(mRemoteCallback); 113 | break; 114 | case R.id.btn_directional: 115 | int[] arr = {1, 2, 3}; 116 | ParcelableObj parcelableObj = new ParcelableObj(); 117 | Rect rect = new Rect(10, 20, 30, 40); 118 | mRemoteService.directionalParamMethod(arr, parcelableObj, rect); 119 | Toast.makeText(this, "After directionalParamMethod parcelableObj: " + parcelableObj 120 | + " rect: " + rect, Toast.LENGTH_LONG).show(); 121 | break; 122 | case R.id.btn_oneway: 123 | mRemoteService.onewayMethod("oneway"); 124 | Toast.makeText(this, "After oneway method client.", Toast.LENGTH_SHORT).show(); 125 | break; 126 | default: 127 | break; 128 | } 129 | } 130 | 131 | @Override 132 | protected void onDestroy() { 133 | super.onDestroy(); 134 | mLinker.unRegisterObject(mRemoteCallback); 135 | mLinker.unbind(); 136 | mLinker.setBindCallback(null); 137 | } 138 | 139 | private final IRemoteCallback mRemoteCallback = new IRemoteCallback() { 140 | 141 | @Override 142 | public void onInit(String msg) { 143 | Log.d(TAG, "Server callback onInit msg:" + msg); 144 | } 145 | 146 | @Override 147 | public void onStart(String status) { 148 | Log.d(TAG, "Server callback onStart status:" + status); 149 | } 150 | 151 | @Override 152 | public void onValueChange(int value) { 153 | // Invoke when server side callback 154 | Toast.makeText(BindingActivity.this, "Server callback value: " + value, Toast.LENGTH_SHORT).show(); 155 | } 156 | }; 157 | 158 | 159 | /** 160 | * Copy the original interface, wrap the return type of the method, keep the original interface name and method name. 161 | */ 162 | @RemoteInterface 163 | public interface IRemoteTask { 164 | 165 | Call remoteCalculate(int a, int b); 166 | 167 | Observable> getDatas(); 168 | 169 | } 170 | } 171 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/IBaseCallback.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | /** 4 | * Created by codezjx on 9/6/24. 5 | */ 6 | interface IBaseCallback { 7 | void onInit(String msg); 8 | } 9 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/IBaseService.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | /** 4 | * Created by codezjx on 9/5/24. 5 | */ 6 | public interface IBaseService { 7 | void init(String msg); 8 | } 9 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/IRemoteCallback.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import com.codezjx.andlinker.annotation.RemoteInterface; 4 | 5 | /** 6 | * Created by codezjx on 2018/3/13.
7 | */ 8 | @RemoteInterface 9 | public interface IRemoteCallback extends IBaseCallback { 10 | 11 | void onStart(String status); 12 | 13 | void onValueChange(int value); 14 | } -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/IRemoteService.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import android.graphics.Rect; 4 | 5 | import com.codezjx.andlinker.annotation.Callback; 6 | import com.codezjx.andlinker.annotation.In; 7 | import com.codezjx.andlinker.annotation.Inout; 8 | import com.codezjx.andlinker.annotation.OneWay; 9 | import com.codezjx.andlinker.annotation.Out; 10 | import com.codezjx.andlinker.annotation.RemoteInterface; 11 | 12 | /** 13 | * Created by codezjx on 2018/3/12.
14 | */ 15 | @RemoteInterface 16 | public interface IRemoteService extends IBaseService { 17 | 18 | int getPid(); 19 | 20 | void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, 21 | double aDouble, String aString); 22 | 23 | void registerCallback(@Callback IRemoteCallback callback); 24 | 25 | void directionalParamMethod(@In int[] arr, @Out ParcelableObj obj, @Inout Rect rect); 26 | 27 | @OneWay 28 | void onewayMethod(String msg); 29 | } -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/IRemoteTask.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import com.codezjx.andlinker.annotation.RemoteInterface; 4 | 5 | import java.util.List; 6 | 7 | /** 8 | * Created by codezjx on 2018/3/14.
9 | */ 10 | @RemoteInterface 11 | public interface IRemoteTask { 12 | 13 | int remoteCalculate(int a, int b); 14 | 15 | List getDatas(); 16 | 17 | } 18 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/ParcelableObj.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import android.os.Parcel; 4 | 5 | import com.codezjx.andlinker.SuperParcelable; 6 | 7 | /** 8 | * Created by codezjx on 2018/3/14.
9 | */ 10 | public class ParcelableObj implements SuperParcelable { 11 | 12 | private int mType; 13 | private float mValue; 14 | private String mMsg; 15 | 16 | 17 | @Override 18 | public int describeContents() { 19 | return 0; 20 | } 21 | 22 | @Override 23 | public void writeToParcel(Parcel dest, int flags) { 24 | dest.writeInt(this.mType); 25 | dest.writeFloat(this.mValue); 26 | dest.writeString(this.mMsg); 27 | } 28 | 29 | public ParcelableObj() { 30 | } 31 | 32 | public ParcelableObj(int type, float value, String msg) { 33 | mType = type; 34 | mValue = value; 35 | mMsg = msg; 36 | } 37 | 38 | protected ParcelableObj(Parcel in) { 39 | readFromParcel(in); 40 | } 41 | 42 | public static final Creator CREATOR = new Creator() { 43 | @Override 44 | public ParcelableObj createFromParcel(Parcel source) { 45 | return new ParcelableObj(source); 46 | } 47 | 48 | @Override 49 | public ParcelableObj[] newArray(int size) { 50 | return new ParcelableObj[size]; 51 | } 52 | }; 53 | 54 | @Override 55 | public void readFromParcel(Parcel in) { 56 | mType = in.readInt(); 57 | mValue = in.readFloat(); 58 | mMsg = in.readString(); 59 | } 60 | 61 | public int getType() { 62 | return mType; 63 | } 64 | 65 | public void setType(int type) { 66 | mType = type; 67 | } 68 | 69 | public float getValue() { 70 | return mValue; 71 | } 72 | 73 | public void setValue(float value) { 74 | mValue = value; 75 | } 76 | 77 | public String getMsg() { 78 | return mMsg; 79 | } 80 | 81 | public void setMsg(String msg) { 82 | mMsg = msg; 83 | } 84 | 85 | @Override 86 | public String toString() { 87 | return "ParcelableObj{" + 88 | "mType=" + mType + 89 | ", mValue=" + mValue + 90 | ", mMsg='" + mMsg + '\'' + 91 | '}'; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /sample/src/main/java/com/example/andlinker/RemoteService.java: -------------------------------------------------------------------------------- 1 | package com.example.andlinker; 2 | 3 | import android.app.Service; 4 | import android.content.Intent; 5 | import android.graphics.Rect; 6 | import android.os.Handler; 7 | import android.os.IBinder; 8 | import android.os.Looper; 9 | import android.util.Log; 10 | import android.widget.Toast; 11 | 12 | import com.codezjx.andlinker.AndLinkerBinder; 13 | 14 | import java.util.ArrayList; 15 | import java.util.Arrays; 16 | import java.util.List; 17 | 18 | public class RemoteService extends Service { 19 | 20 | private static final String TAG = "RemoteService"; 21 | private Handler mHandler = new Handler(Looper.getMainLooper()); 22 | private AndLinkerBinder mLinkerBinder; 23 | 24 | @Override 25 | public void onCreate() { 26 | super.onCreate(); 27 | Log.d(TAG, "Service onCreate()"); 28 | mLinkerBinder = AndLinkerBinder.Factory.newBinder(); 29 | mLinkerBinder.registerObject(mRemoteService); 30 | mLinkerBinder.registerObject(mRemoteTask); 31 | } 32 | 33 | @Override 34 | public IBinder onBind(Intent intent) { 35 | Log.d(TAG, "Service onBind()"); 36 | return mLinkerBinder; 37 | } 38 | 39 | @Override 40 | public void onDestroy() { 41 | super.onDestroy(); 42 | Log.d(TAG, "Service onDestroy()"); 43 | mLinkerBinder.unRegisterObject(mRemoteService); 44 | mLinkerBinder.unRegisterObject(mRemoteTask); 45 | } 46 | 47 | private final IRemoteService mRemoteService = new IRemoteService() { 48 | 49 | @Override 50 | public void init(String msg) { 51 | Log.d(TAG, "Call init() in server: " + msg); 52 | } 53 | 54 | @Override 55 | public int getPid() { 56 | return android.os.Process.myPid(); 57 | } 58 | 59 | @Override 60 | public void basicTypes(int anInt, long aLong, boolean aBoolean, 61 | float aFloat, double aDouble, String aString) { 62 | final String msg = "Execute basicTypes() in server: " + anInt + ", " + aLong + ", " + aBoolean 63 | + ", " + aFloat + ", " + aDouble + ", " + aString; 64 | mHandler.post(() -> Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show()); 65 | } 66 | 67 | @Override 68 | public void registerCallback(IRemoteCallback callback) { 69 | callback.onInit("Message from server."); 70 | callback.onStart(null); 71 | callback.onValueChange(1234); 72 | } 73 | 74 | @Override 75 | public void directionalParamMethod(int[] arr, ParcelableObj obj, Rect rect) { 76 | Log.d(TAG, "directionalParamMethod @In param: " + Arrays.toString(arr)); 77 | Log.d(TAG, "directionalParamMethod @Out param: " + obj); 78 | Log.d(TAG, "directionalParamMethod @Inout param: " + rect); 79 | // Rewrite @Out and @Inout parameter 80 | obj.setType(123); 81 | obj.setValue(43.21f); 82 | obj.setMsg("Message from server"); 83 | rect.set(100, 200, 300, 400); 84 | } 85 | 86 | @Override 87 | public void onewayMethod(String msg) { 88 | Log.d(TAG, "Call oneway method: " + msg); 89 | // Try to block method 90 | try { 91 | Thread.sleep(3000); 92 | } catch (InterruptedException e) { 93 | e.printStackTrace(); 94 | } 95 | Log.d(TAG, "After oneway method server."); 96 | } 97 | }; 98 | 99 | private final IRemoteTask mRemoteTask = new IRemoteTask() { 100 | @Override 101 | public int remoteCalculate(int a, int b) { 102 | Log.d(TAG, "Call remoteCalculate(): " + a + ", " + b); 103 | // Simulate slow task 104 | try { 105 | Thread.sleep(3000); 106 | } catch (InterruptedException e) { 107 | e.printStackTrace(); 108 | } 109 | return (a + b) * 100; 110 | } 111 | 112 | @Override 113 | public List getDatas() { 114 | Log.d(TAG, "Call getDatas()."); 115 | // Simulate slow task 116 | try { 117 | Thread.sleep(3000); 118 | } catch (InterruptedException e) { 119 | e.printStackTrace(); 120 | } 121 | ArrayList datas = new ArrayList<>(); 122 | datas.add(new ParcelableObj(1, 11.1f, "hello")); 123 | datas.add(new ParcelableObj(2, 22.2f, "world")); 124 | return datas; 125 | } 126 | }; 127 | } 128 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 12 | 13 | 19 | 22 | 25 | 26 | 27 | 28 | 34 | 35 | -------------------------------------------------------------------------------- /sample/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 10 | 12 | 14 | 16 | 18 | 20 | 22 | 24 | 26 | 28 | 30 | 32 | 34 | 36 | 38 | 40 | 42 | 44 | 46 | 48 | 50 | 52 | 54 | 56 | 58 | 60 | 62 | 64 | 66 | 68 | 70 | 72 | 74 | 75 | -------------------------------------------------------------------------------- /sample/src/main/res/layout/activity_binding.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 |