├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── app ├── .gitignore ├── build.gradle ├── screen.png └── src │ └── main │ ├── AndroidManifest.xml │ ├── java │ └── com │ │ └── example │ │ └── sensorannotations │ │ ├── AccelerometerManager.java │ │ └── MainActivity.java │ └── res │ ├── layout │ └── activity_main.xml │ ├── mipmap-hdpi │ └── ic_launcher.png │ ├── mipmap-mdpi │ └── ic_launcher.png │ ├── mipmap-xhdpi │ └── ic_launcher.png │ ├── mipmap-xxhdpi │ └── ic_launcher.png │ ├── mipmap-xxxhdpi │ └── ic_launcher.png │ ├── values-w820dp │ └── dimens.xml │ └── values │ ├── colors.xml │ ├── dimens.xml │ ├── strings.xml │ └── styles.xml ├── build.gradle ├── config └── quality │ ├── checkstyle │ └── checkstyle-config.xml │ ├── findbugs │ └── android-exclude-filter.xml │ ├── pmd │ └── pmd-ruleset.xml │ └── quality.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── sensorannotations-annotations ├── build.gradle └── src │ └── main │ └── java │ └── com │ └── dvoiss │ └── sensorannotations │ ├── OnAccuracyChanged.java │ ├── OnSensorChanged.java │ ├── OnSensorNotAvailable.java │ ├── OnTrigger.java │ └── internal │ └── ListenerMethod.java ├── sensorannotations-compiler ├── .gitignore ├── build.gradle └── src │ └── main │ ├── java │ └── com │ │ └── dvoiss │ │ └── sensorannotations │ │ ├── AnnotatedMethod.java │ │ ├── AnnotatedMethodsPerClass.java │ │ ├── SensorAnnotationsFileBuilder.java │ │ ├── SensorAnnotationsProcessor.java │ │ └── exception │ │ └── ProcessingException.java │ └── resources │ └── META-INF │ └── services │ └── javax.annotation.processing.Processor ├── sensorannotations-lib ├── build.gradle ├── proguard-rules.txt └── src │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── dvoiss │ │ └── sensorannotations │ │ ├── SensorAnnotations.java │ │ └── internal │ │ ├── EventListenerWrapper.java │ │ ├── SensorBinder.java │ │ ├── SensorEventListenerWrapper.java │ │ └── TriggerEventListenerWrapper.java │ └── test │ └── java │ └── com │ └── dvoiss │ └── sensorannotations │ ├── BindAllAnnotationsTest.java │ ├── BindOnAccuracyChangedTest.java │ ├── BindOnSensorChangedTest.java │ ├── BindOnSensorNotAvailableTest.java │ ├── BindOnTriggerTest.java │ ├── SensorAnnotationsTest.java │ └── TestUtils.java └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the ART/Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | out/ 15 | 16 | # Gradle files 17 | .gradle/ 18 | build/ 19 | 20 | # Local configuration file (sdk path, etc) 21 | local.properties 22 | 23 | # Proguard folder generated by Eclipse 24 | proguard/ 25 | 26 | # Log Files 27 | *.log 28 | 29 | # Android Studio Navigation editor temp files 30 | .navigation/ 31 | 32 | # Android Studio captures folder 33 | captures/ 34 | 35 | # Intellij 36 | *.iml 37 | .idea/workspace.xml 38 | 39 | # Keystore files 40 | *.jks 41 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: android 2 | 3 | android: 4 | components: 5 | - tools 6 | - platform-tools 7 | - build-tools-24.0.2 8 | - android-24 9 | - extra-android-support 10 | - extra-android-m2repository 11 | 12 | jdk: 13 | - oraclejdk8 14 | 15 | before_cache: 16 | - rm -f $HOME/.gradle/caches/modules-2/modules-2.lock 17 | 18 | cache: 19 | directories: 20 | - $HOME/.m2 21 | - $HOME/.gradle 22 | 23 | sudo: false 24 | 25 | script: 26 | - chmod +x ./gradlew 27 | - ./gradlew clean check 28 | 29 | notifications: 30 | email: false 31 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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 {yyyy} {name of copyright owner} 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. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SensorAnnotations 2 | 3 | Annotate methods to use as listeners for sensor events. 4 | 5 | [![Build Status](https://img.shields.io/travis/dvoiss/SensorAnnotations.svg?style=flat-square)](https://travis-ci.org/dvoiss/SensorAnnotations) 6 | [![Download](https://api.bintray.com/packages/dvoiss/maven/sensorannotations/images/download.svg)](https://bintray.com/dvoiss/maven/sensorannotations/_latestVersion) 7 | [![Android Arsenal](https://img.shields.io/badge/Android%20Arsenal-Sensor%20Annotations-brightgreen.svg?style=flat)](http://android-arsenal.com/details/1/4593) 8 | [![Awesome Android #22](https://img.shields.io/badge/Awesome%20Android-%2322-green.svg?style=true)](https://android.libhunt.com/newsletter/22) 9 | 10 | ```java 11 | public class MyActivity extends Activity { 12 | /** 13 | * Perform actions as accelerometer data changes... 14 | */ 15 | @OnSensorChanged(Sensor.TYPE_ACCELEROMETER) 16 | void accelerometerSensorChanged(@NonNull SensorEvent event) { 17 | doSomething(event.values); 18 | } 19 | 20 | /** 21 | * If the sensor isn't available, update UI accordingly... 22 | */ 23 | @OnSensorNotAvailable(Sensor.TYPE_ACCELEROMETER) 24 | void testTemperatureSensorNotAvailable() { 25 | hideAccelerometerUi(); 26 | } 27 | 28 | @Override protected void onResume() { 29 | super.onResume(); 30 | SensorAnnotations.bind(this); 31 | } 32 | 33 | @Override protected void onPause() { 34 | super.onPause(); 35 | SensorAnnotations.unbind(this); // Unbind to save the user's battery life. 36 | } 37 | } 38 | ``` 39 | 40 | There are four possible annotations: `@OnSensorChanged`, `@OnAccuracyChanged`, `@OnSensorNotAvailable`, and `@OnTrigger`. The annotated methods must have the method signatures specified in the [Sensors Overview](https://developer.android.com/guide/topics/sensors/sensors_overview.html) Android docs. 41 | 42 | ```java 43 | @OnSensorChanged(Sensor.TYPE_HEART_RATE) 44 | void method(@NonNull SensorEvent event) {} 45 | 46 | // or the following syntax can be used which accepts a delay value: 47 | @OnSensorChanged(value = Sensor.TYPE_LIGHT, delay = SensorManager.SENSOR_DELAY_NORMAL) 48 | void method(@NonNull SensorEvent event) {} 49 | 50 | @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD) 51 | void method(@NonNull Sensor sensor, int accuracy) {} 52 | 53 | @OnSensorNotAvailable(Sensor.TYPE_AMBIENT_TEMPERATURE) 54 | void method() {} 55 | 56 | @OnTrigger 57 | void method(@NonNull TriggerEvent event) {} 58 | ``` 59 | 60 | For information about sensor delays and accuracy events see the ["Monitoring Sensor Events"](https://developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-monitor) portion of the Android docs. 61 | 62 | Calling `SensorAnnotations.bind` should be done when you want to start receiving sensor events. Because this consumes battery life you need to call `unbind` when you are finished. The `bind` method needs to take a `Context` object. There are two variations: 63 | 64 | ```java 65 | SensorAnnotations.bind(context); 66 | // Use this alternative to bind to a different target. See the example application. 67 | SensorAnnotations.bind(this, context); 68 | ``` 69 | 70 | The `@OnTrigger` annotation is a specific annotation for sensors of `TYPE_SIGNIFICANT_MOTION` (introduced in 4.3). This type has a different method and parameter than the others. For more info see the Android docs on [Using the Significant Motion Sensor](https://developer.android.com/guide/topics/sensors/sensors_motion.html#sensors-motion-significant). 71 | 72 | ## View the Demo app for usage 73 | 74 | ![SensorAnnotations Sample App](https://raw.github.com/dvoiss/SensorAnnotations/master/app/screen.png) 75 | 76 | ## How does it work? 77 | 78 | A binding class is created for each class that has annotations. In the example app, the classes `MainActivity` and `AccelerometerManager` will have two classes generated at compile time: `MainActivity$$SensorBinder` and `AccelerometerManager$$SensorBinder`. Because these classes are generated at compile time no reflection is needed. 79 | 80 | These classes register the listener with the sensor system service. If the sensor isn't available on the device and a method has been annotated with `@OnSensorNotAvailable` it will be invoked. If an accuracy event occurs and a method has been annotated with `@OnAccuracyChanged` it will be invoked. The `TYPE_SIGNIFICANT_MOTION` sensor doesn't have an accuracy callback. 81 | 82 | ## Use in your project 83 | 84 | ```groovy 85 | buildscript { 86 | dependencies { 87 | classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8' 88 | } 89 | } 90 | 91 | apply plugin: 'com.neenbedankt.android-apt' 92 | 93 | dependencies { 94 | compile 'com.dvoiss:sensorannotations:0.1.0' 95 | apt 'com.dvoiss:sensorannotations-compiler:0.1.0' 96 | } 97 | ``` 98 | 99 | Using Android Gradle Plugin version 2.2.0+: 100 | 101 | ```groovy 102 | dependencies { 103 | compile 'com.dvoiss:sensorannotations:0.1.0' 104 | annotationProcessor 'com.dvoiss:sensorannotations-compiler:0.1.0' 105 | } 106 | ``` 107 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | apply from: '../config/quality/quality.gradle' 3 | 4 | android { 5 | compileSdkVersion rootProject.ext.compileSdkVersion 6 | buildToolsVersion rootProject.ext.buildToolsVersion 7 | 8 | defaultConfig { 9 | applicationId "com.example.sensorannotations" 10 | minSdkVersion rootProject.ext.minSdkVersion 11 | targetSdkVersion rootProject.ext.compileSdkVersion 12 | versionCode 1 13 | versionName "1.0" 14 | } 15 | 16 | buildTypes { 17 | release { 18 | minifyEnabled true 19 | } 20 | debug { 21 | minifyEnabled true 22 | debuggable true 23 | } 24 | } 25 | 26 | lintOptions { 27 | abortOnError false 28 | } 29 | 30 | compileOptions { 31 | sourceCompatibility sourceCompatibilityVersion 32 | targetCompatibility targetCompatibilityVersion 33 | } 34 | } 35 | 36 | dependencies { 37 | annotationProcessor project(':sensorannotations-compiler') 38 | annotationProcessor 'com.jakewharton:butterknife-compiler:8.4.0' 39 | 40 | compile project(':sensorannotations-lib') 41 | compile deps.appcompat 42 | compile 'com.jakewharton:butterknife:8.4.0' 43 | } 44 | -------------------------------------------------------------------------------- /app/screen.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/screen.png -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 11 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/sensorannotations/AccelerometerManager.java: -------------------------------------------------------------------------------- 1 | package com.example.sensorannotations; 2 | 3 | import android.hardware.Sensor; 4 | import android.hardware.SensorEvent; 5 | import android.support.annotation.NonNull; 6 | import android.widget.CompoundButton; 7 | import android.widget.TextView; 8 | import android.widget.ToggleButton; 9 | import com.dvoiss.sensorannotations.OnAccuracyChanged; 10 | import com.dvoiss.sensorannotations.OnSensorChanged; 11 | import com.dvoiss.sensorannotations.OnSensorNotAvailable; 12 | import com.dvoiss.sensorannotations.SensorAnnotations; 13 | 14 | class AccelerometerManager { 15 | @NonNull private final MainActivity mMainActivity; 16 | 17 | private TextView mAccelerometerManagerTextView; 18 | 19 | AccelerometerManager(@NonNull MainActivity mainActivity) { 20 | mMainActivity = mainActivity; 21 | 22 | mAccelerometerManagerTextView = 23 | (TextView) mMainActivity.findViewById(R.id.accelerometer_event_output); 24 | 25 | ToggleButton accelerometerButton = 26 | (ToggleButton) mMainActivity.findViewById(R.id.accelerometer_button); 27 | 28 | accelerometerButton.setOnCheckedChangeListener( 29 | new CompoundButton.OnCheckedChangeListener() { 30 | @Override 31 | public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 32 | if (isChecked) { 33 | // Example of binding to another object, a Context is still needed: 34 | SensorAnnotations.bind(AccelerometerManager.this, buttonView.getContext()); 35 | } else { 36 | SensorAnnotations.unbind(AccelerometerManager.this); 37 | mMainActivity.updateTextViewWithSensorNotBound( 38 | mAccelerometerManagerTextView); 39 | } 40 | } 41 | }); 42 | } 43 | 44 | // region Accelerometer Tests 45 | 46 | @OnSensorChanged(Sensor.TYPE_ACCELEROMETER) 47 | void testTemperatureSensorChanged(@NonNull SensorEvent event) { 48 | mMainActivity.updateTextViewWithEventData(mAccelerometerManagerTextView, event); 49 | } 50 | 51 | @OnSensorNotAvailable(Sensor.TYPE_ACCELEROMETER) 52 | void testTemperatureSensorNotAvailable() { 53 | mMainActivity.updateTextViewWithSensorNotAvailable(mAccelerometerManagerTextView); 54 | } 55 | 56 | @OnAccuracyChanged(Sensor.TYPE_ACCELEROMETER) 57 | void testTemperatureAccuracyChanged(@NonNull Sensor sensor, int accuracy) { 58 | mMainActivity.logAccuracyChangedForSensor(sensor, accuracy); 59 | } 60 | 61 | // endregion 62 | } 63 | -------------------------------------------------------------------------------- /app/src/main/java/com/example/sensorannotations/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.example.sensorannotations; 2 | 3 | import android.annotation.TargetApi; 4 | import android.hardware.Sensor; 5 | import android.hardware.SensorEvent; 6 | import android.hardware.TriggerEvent; 7 | import android.os.Build; 8 | import android.os.Bundle; 9 | import android.support.annotation.NonNull; 10 | import android.support.v7.app.AppCompatActivity; 11 | import android.util.Log; 12 | import android.widget.TextView; 13 | import butterknife.BindView; 14 | import butterknife.ButterKnife; 15 | import com.dvoiss.sensorannotations.OnAccuracyChanged; 16 | import com.dvoiss.sensorannotations.OnSensorChanged; 17 | import com.dvoiss.sensorannotations.OnSensorNotAvailable; 18 | import com.dvoiss.sensorannotations.OnTrigger; 19 | import com.dvoiss.sensorannotations.SensorAnnotations; 20 | 21 | public class MainActivity extends AppCompatActivity { 22 | 23 | AccelerometerManager mAccelerometerManager; 24 | 25 | @BindView(R.id.magnetic_field_event_output) TextView mMagneticFieldEventOutputTextView; 26 | @BindView(R.id.light_event_output) TextView mLightEventOutputTextView; 27 | @BindView(R.id.heart_rate_event_output) TextView mHeartRateEventOutputTextView; 28 | @BindView(R.id.significant_motion_event_output) TextView mSignificantMotionEventOutputTextView; 29 | 30 | @Override 31 | protected void onCreate(Bundle savedInstanceState) { 32 | super.onCreate(savedInstanceState); 33 | setContentView(R.layout.activity_main); 34 | ButterKnife.bind(this); 35 | 36 | // Accelerometer is an example of binding to another object. 37 | mAccelerometerManager = new AccelerometerManager(this); 38 | } 39 | 40 | @Override 41 | protected void onResume() { 42 | super.onResume(); 43 | 44 | // Binding should be done when the sensors are needed, 45 | // in this example the onResume is used, 46 | // in the AccelerometerManager class it is when a button is clicked. 47 | 48 | SensorAnnotations.bind(this); 49 | } 50 | 51 | @Override 52 | protected void onPause() { 53 | super.onPause(); 54 | 55 | // Read the Sensors Overview docs: 56 | // developer.android.com/guide/topics/sensors/sensors_overview.html#sensors-practices 57 | // 58 | // "Be sure to unregister a sensor's listener when you 59 | // are done using the sensor or when the sensor activity pauses. 60 | // 61 | // If a sensor listener is registered and its activity is paused, the sensor will 62 | // continue to acquire data and use battery resources unless you unregister the sensor." 63 | 64 | SensorAnnotations.unbind(this); 65 | SensorAnnotations.unbind(mAccelerometerManager); 66 | } 67 | 68 | // region Magnetic Field Tests 69 | 70 | @OnSensorChanged(Sensor.TYPE_MAGNETIC_FIELD) 71 | void testMagneticFieldSensorChanged(@NonNull SensorEvent event) { 72 | updateTextViewWithEventData(mMagneticFieldEventOutputTextView, event); 73 | } 74 | 75 | @OnSensorNotAvailable(Sensor.TYPE_MAGNETIC_FIELD) 76 | void testMagneticFieldSensorNotAvailable() { 77 | updateTextViewWithSensorNotAvailable(mMagneticFieldEventOutputTextView); 78 | } 79 | 80 | @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD) 81 | void testMagneticFieldAccuracyChanged(@NonNull Sensor sensor, int accuracy) { 82 | logAccuracyChangedForSensor(sensor, accuracy); 83 | } 84 | 85 | // endregion 86 | 87 | // region Heart Rate Tests 88 | 89 | @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) 90 | @OnSensorChanged(Sensor.TYPE_HEART_RATE) 91 | public void testHeartRateSensorChanged(@NonNull SensorEvent event) { 92 | updateTextViewWithEventData(mHeartRateEventOutputTextView, event); 93 | } 94 | 95 | @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) 96 | @OnSensorNotAvailable(Sensor.TYPE_HEART_RATE) 97 | public void testHeartRateSensorNotAvailable() { 98 | updateTextViewWithSensorNotAvailable(mHeartRateEventOutputTextView); 99 | } 100 | 101 | @TargetApi(Build.VERSION_CODES.KITKAT_WATCH) 102 | @OnAccuracyChanged(Sensor.TYPE_HEART_RATE) 103 | public void testHeartRateAccuracyChanged(@NonNull Sensor sensor, int accuracy) { 104 | logAccuracyChangedForSensor(sensor, accuracy); 105 | } 106 | 107 | // endregion 108 | 109 | // region Light Tests 110 | 111 | @OnSensorChanged(Sensor.TYPE_LIGHT) 112 | public void testLightSensorChanged(@NonNull SensorEvent event) { 113 | updateTextViewWithEventData(mLightEventOutputTextView, event); 114 | } 115 | 116 | @OnSensorNotAvailable(Sensor.TYPE_LIGHT) 117 | public void testLightSensorNotAvailable() { 118 | updateTextViewWithSensorNotAvailable(mLightEventOutputTextView); 119 | } 120 | 121 | @OnAccuracyChanged(Sensor.TYPE_LIGHT) 122 | public void testLightAccuracyChanged(@NonNull Sensor sensor, int accuracy) { 123 | logAccuracyChangedForSensor(sensor, accuracy); 124 | } 125 | 126 | // endregion 127 | 128 | // region Significant Motion Tests 129 | 130 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 131 | @OnTrigger 132 | public void testSignificantMotionTrigger(@NonNull TriggerEvent event) { 133 | updateTextViewWithEventData(mSignificantMotionEventOutputTextView, event); 134 | } 135 | 136 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 137 | @OnSensorNotAvailable(Sensor.TYPE_SIGNIFICANT_MOTION) 138 | public void testSignificantMotionSensorNotAvailable() { 139 | updateTextViewWithSensorNotAvailable(mSignificantMotionEventOutputTextView); 140 | } 141 | 142 | // endregion 143 | 144 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 145 | void updateTextViewWithEventData(@NonNull TextView textView, @NonNull TriggerEvent event) { 146 | updateTextViewWithEventData(textView, event.timestamp, event.values); 147 | } 148 | 149 | void updateTextViewWithEventData(@NonNull TextView textView, @NonNull SensorEvent event) { 150 | updateTextViewWithEventData(textView, event.timestamp, event.values); 151 | } 152 | 153 | void updateTextViewWithEventData(@NonNull TextView textView, long timestamp, float[] values) { 154 | StringBuilder builder = new StringBuilder(String.valueOf(timestamp)).append(": ("); 155 | for (int i = 0; i < values.length; i++) { 156 | if (i != 0) { 157 | builder.append(", "); 158 | } 159 | builder.append(values[i]); 160 | } 161 | builder.append(')'); 162 | 163 | textView.setText(builder); 164 | } 165 | 166 | void updateTextViewWithSensorNotAvailable(@NonNull TextView textView) { 167 | textView.setText(getString(R.string.sensor_not_available)); 168 | } 169 | 170 | void updateTextViewWithSensorNotBound(@NonNull TextView textView) { 171 | textView.setText(getString(R.string.sensor_not_bound)); 172 | } 173 | 174 | void logAccuracyChangedForSensor(@NonNull Sensor sensor, int accuracy) { 175 | Log.i(getClass().getSimpleName(), sensor.getName() + " accuracy: " + accuracy); 176 | } 177 | } 178 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 11 | 12 | 13 | 17 | 18 | 23 | 24 | 25 | 30 | 31 | 36 | 37 | 38 | 43 | 44 | 49 | 50 | 51 | 56 | 57 | 62 | 63 | 64 | 72 | 73 | 77 | 78 | 83 | 84 | 85 | -------------------------------------------------------------------------------- /app/src/main/res/mipmap-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/src/main/res/mipmap-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/src/main/res/mipmap-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/src/main/res/mipmap-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/src/main/res/mipmap-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/mipmap-xxxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /app/src/main/res/values-w820dp/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 64dp 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/colors.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | #3F51B5 4 | #303F9F 5 | #FF4081 6 | 7 | -------------------------------------------------------------------------------- /app/src/main/res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 16dp 4 | 16dp 5 | 6 | -------------------------------------------------------------------------------- /app/src/main/res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | SensorAnnotations Demo 3 | 4 | Light Event Info 5 | Heart Rate Event Info 6 | Magnetic Field Event Info 7 | Significant Motion Event Info 8 | 9 | Accelerometer Event Info 10 | Begin Using Accelerometer 11 | Stop Using Accelerometer 12 | 13 | No Events Received Yet… 14 | Sensor Not Available 15 | Sensor Not Bound 16 | 17 | -------------------------------------------------------------------------------- /app/src/main/res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | buildscript { 2 | repositories { 3 | jcenter() 4 | maven { url 'https://plugins.gradle.org/m2/' } 5 | } 6 | dependencies { 7 | classpath 'com.android.tools.build:gradle:2.2.2' 8 | classpath 'com.novoda:bintray-release:0.3.4' 9 | } 10 | } 11 | 12 | allprojects { 13 | repositories { 14 | jcenter() 15 | } 16 | } 17 | 18 | ext { 19 | version = "0.1.0" 20 | 21 | sourceCompatibilityVersion = JavaVersion.VERSION_1_7 22 | targetCompatibilityVersion = JavaVersion.VERSION_1_7 23 | compileSdkVersion = 24 24 | buildToolsVersion = '24.0.2' 25 | minSdkVersion = 9 26 | supportVersion = '24.2.1' 27 | 28 | deps = [ 29 | // Common 30 | android : 'com.google.android:android:4.1.1.4', 31 | checker : 'org.checkerframework:checker-qual:2.1.4', 32 | javapoet : 'com.squareup:javapoet:1.7.0', 33 | autocommon : 'com.google.auto:auto-common:0.6', 34 | appcompat : "com.android.support:appcompat-v7:$supportVersion", 35 | supportannotations: "com.android.support:support-annotations:$supportVersion", 36 | 37 | // Test 38 | junit : 'junit:junit:4.12', 39 | truth : 'com.google.truth:truth:0.28', 40 | compiletesting : 'com.google.testing.compile:compile-testing:0.9', 41 | robolectric : 'org.robolectric:robolectric:3.1.2', 42 | mockito : 'org.mockito:mockito-core:1.+' 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /config/quality/checkstyle/checkstyle-config.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 34 | 35 | 36 | 37 | 38 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 80 | 82 | 84 | 86 | 87 | 88 | 89 | 90 | 91 | 92 | 93 | 95 | 97 | 98 | 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | 118 | 120 | 121 | 122 | 123 | 124 | 126 | 127 | 128 | 129 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 140 | 141 | 142 | 143 | 144 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 154 | 155 | 156 | 157 | 158 | 160 | 161 | 162 | 163 | 164 | 166 | 167 | 168 | 169 | 170 | 171 | -------------------------------------------------------------------------------- /config/quality/findbugs/android-exclude-filter.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /config/quality/pmd/pmd-ruleset.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | Custom ruleset for ribot Android application 8 | 9 | .*/R.java 10 | .*/gen/.* 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /config/quality/quality.gradle: -------------------------------------------------------------------------------- 1 | /** 2 | * Set up Checkstyle, Findbugs and PMD to perform extensive code analysis. 3 | * 4 | * Gradle tasks added: 5 | * - checkstyle 6 | * - findbugs 7 | * - pmd 8 | * 9 | * The three tasks above are added as dependencies of the check task so running check will 10 | * run all of them. 11 | **/ 12 | 13 | apply plugin: 'checkstyle' 14 | apply plugin: 'findbugs' 15 | apply plugin: 'pmd' 16 | 17 | def qualityConfigDir = "$project.rootDir/config/quality" 18 | def reportsDir = "$project.buildDir/reports" 19 | 20 | dependencies { 21 | checkstyle 'com.puppycrawl.tools:checkstyle:6.5' 22 | } 23 | 24 | //check.dependsOn 'checkstyle', 'findbugs', 'pmd' 25 | 26 | def getFindBugsDependencies(project) { 27 | if (project.hasProperty('android')) { 28 | return ['compileDebugSources', 'compileReleaseSources'] 29 | } else { 30 | return ['compileJava'] 31 | } 32 | } 33 | 34 | allprojects { project -> 35 | checkstyle { 36 | ignoreFailures = true 37 | configFile = rootProject.file("$qualityConfigDir/checkstyle/checkstyle-config.xml") 38 | } 39 | 40 | findbugs { 41 | ignoreFailures = true 42 | } 43 | 44 | task checkstyle(type: Checkstyle, group: 'Verification', description: 'Runs code style checks') { 45 | source 'src' 46 | include '**/*.java' 47 | 48 | reports { 49 | html.enabled = true 50 | html { 51 | destination "$reportsDir/checkstyle/checkstyle.html" 52 | } 53 | xml.enabled = false 54 | xml { 55 | destination "$reportsDir/checkstyle/checkstyle.xml" 56 | } 57 | } 58 | 59 | classpath = files() 60 | } 61 | 62 | task findbugs(type: FindBugs, 63 | group: 'Verification', 64 | description: 'Inspect java bytecode for bugs', 65 | dependsOn: getFindBugsDependencies(project)) { 66 | 67 | ignoreFailures = true 68 | effort = "max" 69 | reportLevel = "high" 70 | excludeFilter = new File("$qualityConfigDir/findbugs/android-exclude-filter.xml") 71 | classes = files("$project.rootDir/app/build/intermediates/classes") 72 | 73 | source 'src' 74 | include '**/*.java' 75 | exclude '**/gen/**' 76 | 77 | reports { 78 | xml.enabled = false 79 | html.enabled = true 80 | xml { 81 | destination "$reportsDir/findbugs/findbugs.xml" 82 | } 83 | html { 84 | destination "$reportsDir/findbugs/findbugs.html" 85 | } 86 | } 87 | 88 | classpath = files() 89 | } 90 | 91 | 92 | task pmd(type: Pmd, group: 'Verification', description: 'Inspect sourcecode for bugs') { 93 | ruleSetFiles = files("$qualityConfigDir/pmd/pmd-ruleset.xml") 94 | ignoreFailures = true 95 | ruleSets = [] 96 | 97 | source 'src' 98 | include '**/*.java' 99 | exclude '**/gen/**' 100 | 101 | reports { 102 | xml.enabled = true 103 | html.enabled = true 104 | xml { 105 | destination "$reportsDir/pmd/pmd.xml" 106 | } 107 | html { 108 | destination "$reportsDir/pmd/pmd.html" 109 | } 110 | } 111 | } 112 | } 113 | -------------------------------------------------------------------------------- /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=-Xmx1536m 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/dvoiss/SensorAnnotations/31a0346d6e564df6ae3881b07254475df0b27809/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | #Mon Dec 28 10:00:20 PST 2015 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-2.14.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 | -------------------------------------------------------------------------------- /sensorannotations-annotations/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'com.novoda.bintray-release' 3 | apply from: '../config/quality/quality.gradle' 4 | 5 | sourceCompatibility = rootProject.ext.sourceCompatibilityVersion 6 | targetCompatibility = rootProject.ext.targetCompatibilityVersion 7 | 8 | dependencies { 9 | compileOnly deps.android 10 | } 11 | 12 | publish { 13 | userOrg = 'dvoiss' 14 | groupId = 'com.dvoiss' 15 | artifactId = 'sensorannotations-annotations' 16 | publishVersion = rootProject.ext.version 17 | description = 'Annotate methods to use as listeners for a specific sensor.' 18 | website = 'https://github.com/dvoiss/sensorannotations' 19 | } 20 | -------------------------------------------------------------------------------- /sensorannotations-annotations/src/main/java/com/dvoiss/sensorannotations/OnAccuracyChanged.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.internal.ListenerMethod; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import static android.hardware.SensorManager.SENSOR_DELAY_NORMAL; 10 | 11 | @Retention(RetentionPolicy.CLASS) 12 | @Target(ElementType.METHOD) 13 | @ListenerMethod(parameters = { "android.hardware.Sensor", "int" }) 14 | public @interface OnAccuracyChanged { 15 | int value() default -1; 16 | 17 | int delay() default SENSOR_DELAY_NORMAL; 18 | } 19 | -------------------------------------------------------------------------------- /sensorannotations-annotations/src/main/java/com/dvoiss/sensorannotations/OnSensorChanged.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.internal.ListenerMethod; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | import static android.hardware.SensorManager.SENSOR_DELAY_NORMAL; 10 | 11 | @Retention(RetentionPolicy.CLASS) 12 | @Target(ElementType.METHOD) 13 | @ListenerMethod(parameters = { "android.hardware.SensorEvent" }) 14 | public @interface OnSensorChanged { 15 | int value() default -1; 16 | 17 | int delay() default SENSOR_DELAY_NORMAL; 18 | } 19 | -------------------------------------------------------------------------------- /sensorannotations-annotations/src/main/java/com/dvoiss/sensorannotations/OnSensorNotAvailable.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.internal.ListenerMethod; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.CLASS) 10 | @Target(ElementType.METHOD) 11 | @ListenerMethod 12 | public @interface OnSensorNotAvailable { 13 | int value() default -1; 14 | } 15 | -------------------------------------------------------------------------------- /sensorannotations-annotations/src/main/java/com/dvoiss/sensorannotations/OnTrigger.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.internal.ListenerMethod; 4 | import java.lang.annotation.ElementType; 5 | import java.lang.annotation.Retention; 6 | import java.lang.annotation.RetentionPolicy; 7 | import java.lang.annotation.Target; 8 | 9 | @Retention(RetentionPolicy.CLASS) 10 | @Target(ElementType.METHOD) 11 | @ListenerMethod(parameters = { "android.hardware.TriggerEvent" }) 12 | public @interface OnTrigger {} 13 | -------------------------------------------------------------------------------- /sensorannotations-annotations/src/main/java/com/dvoiss/sensorannotations/internal/ListenerMethod.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.internal; 2 | 3 | import java.lang.annotation.Retention; 4 | import java.lang.annotation.Target; 5 | 6 | import static java.lang.annotation.ElementType.ANNOTATION_TYPE; 7 | import static java.lang.annotation.RetentionPolicy.RUNTIME; 8 | 9 | @Retention(RUNTIME) 10 | @Target(ANNOTATION_TYPE) 11 | public @interface ListenerMethod { 12 | String[] parameters() default {}; 13 | } 14 | -------------------------------------------------------------------------------- /sensorannotations-compiler/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /sensorannotations-compiler/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'java' 2 | apply plugin: 'com.novoda.bintray-release' 3 | apply from: '../config/quality/quality.gradle' 4 | 5 | sourceCompatibility = rootProject.ext.sourceCompatibilityVersion 6 | targetCompatibility = rootProject.ext.targetCompatibilityVersion 7 | 8 | dependencies { 9 | compileOnly project(':sensorannotations-annotations') 10 | compile deps.javapoet 11 | compile deps.checker 12 | compile deps.autocommon 13 | } 14 | 15 | publish { 16 | userOrg = 'dvoiss' 17 | groupId = 'com.dvoiss' 18 | artifactId = 'sensorannotations-compiler' 19 | publishVersion = rootProject.ext.version 20 | description = 'Annotate methods to use as listeners for a specific sensor.' 21 | website = 'https://github.com/dvoiss/sensorannotations' 22 | } 23 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/java/com/dvoiss/sensorannotations/AnnotatedMethod.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import java.lang.annotation.Annotation; 4 | import javax.lang.model.element.ExecutableElement; 5 | import org.checkerframework.checker.nullness.qual.NonNull; 6 | 7 | import static com.dvoiss.sensorannotations.SensorAnnotationsFileBuilder.TYPE_SIGNIFICANT_MOTION; 8 | 9 | /** 10 | * This is a wrapper class that holds information about the method that was annotated ({@link 11 | * #mAnnotatedMethodElement}) and the values specified in the annotation. 12 | */ 13 | class AnnotatedMethod { 14 | private static final int INVALID_SENSOR = -1; 15 | static final int INVALID_DELAY = -1; 16 | 17 | @NonNull private final ExecutableElement mAnnotatedMethodElement; 18 | 19 | private final int mSensorType; 20 | private final int mDelay; 21 | 22 | AnnotatedMethod(@NonNull ExecutableElement methodElement, 23 | @NonNull Class annotationClass) throws IllegalArgumentException { 24 | Annotation annotation = methodElement.getAnnotation(annotationClass); 25 | mAnnotatedMethodElement = methodElement; 26 | mDelay = getDelayFromAnnotation(annotation); 27 | mSensorType = getSensorTypeFromAnnotation(annotation); 28 | 29 | if (mSensorType == INVALID_SENSOR) { 30 | throw new IllegalArgumentException(String.format( 31 | "No sensor type specified in @%s for method %s." 32 | + " Set a sensor type such as Sensor.TYPE_ACCELEROMETER.", 33 | annotationClass.getSimpleName(), methodElement.getSimpleName().toString())); 34 | } 35 | } 36 | 37 | int getSensorType() { 38 | return mSensorType; 39 | } 40 | 41 | int getDelay() { 42 | return mDelay; 43 | } 44 | 45 | @NonNull ExecutableElement getExecutableElement() { 46 | return mAnnotatedMethodElement; 47 | } 48 | 49 | /** 50 | * Return the sensor type set on the annotation. 51 | * 52 | * @param annotation The annotation we want to inspect for the sensor type. 53 | * @return The sensor type or {@link #INVALID_SENSOR}. 54 | */ 55 | private int getSensorTypeFromAnnotation(@NonNull Annotation annotation) { 56 | if (annotation instanceof OnSensorChanged) { 57 | return ((OnSensorChanged) annotation).value(); 58 | } else if (annotation instanceof OnAccuracyChanged) { 59 | return ((OnAccuracyChanged) annotation).value(); 60 | } else if (annotation instanceof OnSensorNotAvailable) { 61 | return ((OnSensorNotAvailable) annotation).value(); 62 | } else if (annotation instanceof OnTrigger) { 63 | return TYPE_SIGNIFICANT_MOTION; 64 | } 65 | 66 | return INVALID_SENSOR; 67 | } 68 | 69 | /** 70 | * Return the sensor mDelay value on the annotation or return a sentinel value if no value is 71 | * found. 72 | * 73 | * @param annotation The annotation we want to inspect for the delay value. 74 | * @return The delay value or {@link #INVALID_DELAY}. 75 | */ 76 | private int getDelayFromAnnotation(@NonNull Annotation annotation) { 77 | if (annotation instanceof OnSensorChanged) { 78 | return ((OnSensorChanged) annotation).delay(); 79 | } else if (annotation instanceof OnAccuracyChanged) { 80 | return ((OnAccuracyChanged) annotation).delay(); 81 | } 82 | 83 | return INVALID_DELAY; 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/java/com/dvoiss/sensorannotations/AnnotatedMethodsPerClass.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.exception.ProcessingException; 4 | import java.lang.annotation.Annotation; 5 | import java.util.HashMap; 6 | import java.util.LinkedHashMap; 7 | import java.util.Map; 8 | import org.checkerframework.checker.nullness.qual.NonNull; 9 | 10 | /** 11 | * This wrapper class holds all the annotations found in a given class {@link 12 | * #mEnclosingClassName}. 13 | * 14 | * The {@link #mItemsMap} is a map with sensor types as the key and a value of a map between the 15 | * annotation class to the method annotated. 16 | */ 17 | class AnnotatedMethodsPerClass { 18 | @NonNull private String mEnclosingClassName; 19 | @NonNull private Map> mItemsMap = new LinkedHashMap<>(); 20 | 21 | AnnotatedMethodsPerClass(@NonNull String enclosingClassName) { 22 | this.mEnclosingClassName = enclosingClassName; 23 | } 24 | 25 | void add(@NonNull Class annotationClass, @NonNull AnnotatedMethod method) 26 | throws ProcessingException { 27 | Map annotationMap = mItemsMap.get(method.getSensorType()); 28 | if (annotationMap == null) { 29 | annotationMap = new HashMap<>(); 30 | } 31 | 32 | if (annotationMap.get(annotationClass) != null) { 33 | String error = 34 | String.format("@%s is already annotated on a different method in class %s", 35 | annotationClass.getSimpleName(), method.getExecutableElement().getSimpleName()); 36 | throw new ProcessingException(method.getExecutableElement(), error); 37 | } 38 | 39 | annotationMap.put(annotationClass, method); 40 | mItemsMap.put(method.getSensorType(), annotationMap); 41 | } 42 | 43 | boolean hasAnnotationsOfType(Class annotationClass) { 44 | for (Map values : mItemsMap.values()) { 45 | if (values.get(annotationClass) != null) { 46 | return true; 47 | } 48 | } 49 | 50 | return false; 51 | } 52 | 53 | @NonNull String getEnclosingClassName() { 54 | return mEnclosingClassName; 55 | } 56 | 57 | @NonNull Map> getItemsMap() { 58 | return mItemsMap; 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/java/com/dvoiss/sensorannotations/SensorAnnotationsFileBuilder.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.exception.ProcessingException; 4 | import com.dvoiss.sensorannotations.internal.ListenerMethod; 5 | import com.google.common.base.Joiner; 6 | import com.squareup.javapoet.ClassName; 7 | import com.squareup.javapoet.CodeBlock; 8 | import com.squareup.javapoet.FieldSpec; 9 | import com.squareup.javapoet.JavaFile; 10 | import com.squareup.javapoet.MethodSpec; 11 | import com.squareup.javapoet.MethodSpec.Builder; 12 | import com.squareup.javapoet.ParameterSpec; 13 | import com.squareup.javapoet.ParameterizedTypeName; 14 | import com.squareup.javapoet.TypeName; 15 | import com.squareup.javapoet.TypeSpec; 16 | import java.io.IOException; 17 | import java.io.Writer; 18 | import java.lang.annotation.Annotation; 19 | import java.util.ArrayList; 20 | import java.util.List; 21 | import java.util.Map; 22 | import javax.annotation.processing.Filer; 23 | import javax.annotation.processing.ProcessingEnvironment; 24 | import javax.lang.model.element.ExecutableElement; 25 | import javax.lang.model.element.Modifier; 26 | import javax.lang.model.element.PackageElement; 27 | import javax.lang.model.element.TypeElement; 28 | import javax.lang.model.element.VariableElement; 29 | import javax.lang.model.type.TypeMirror; 30 | import javax.lang.model.util.Elements; 31 | import javax.tools.JavaFileObject; 32 | import org.checkerframework.checker.nullness.qual.NonNull; 33 | import org.checkerframework.checker.nullness.qual.Nullable; 34 | 35 | import static com.dvoiss.sensorannotations.AnnotatedMethod.INVALID_DELAY; 36 | 37 | class SensorAnnotationsFileBuilder { 38 | /** 39 | * The suffix will be added to the name of the generated class. 40 | */ 41 | private static final String SUFFIX = "$$SensorBinder"; 42 | 43 | static final int TYPE_SIGNIFICANT_MOTION = 17; 44 | 45 | // region Static Types that are used in the methods below to create types and specs. 46 | 47 | private static final ClassName LISTENER_WRAPPER = 48 | ClassName.get("com.dvoiss.sensorannotations.internal", "EventListenerWrapper"); 49 | private static final ClassName SENSOR_EVENT_LISTENER_WRAPPER = 50 | ClassName.get("com.dvoiss.sensorannotations.internal", "SensorEventListenerWrapper"); 51 | private static final ClassName TRIGGER_EVENT_LISTENER_WRAPPER = 52 | ClassName.get("com.dvoiss.sensorannotations.internal", "TriggerEventListenerWrapper"); 53 | private static final ClassName SENSOR_BINDER = 54 | ClassName.get("com.dvoiss.sensorannotations.internal", "SensorBinder"); 55 | 56 | private static final ClassName SENSOR = ClassName.get("android.hardware", "Sensor"); 57 | private static final ClassName SENSOR_MANAGER = 58 | ClassName.get("android.hardware", "SensorManager"); 59 | private static final ClassName SENSOR_EVENT = ClassName.get("android.hardware", "SensorEvent"); 60 | private static final ClassName TRIGGER_EVENT = 61 | ClassName.get("android.hardware", "TriggerEvent"); 62 | private static final ClassName SENSOR_EVENT_LISTENER = 63 | ClassName.get("android.hardware", "SensorEventListener"); 64 | private static final ClassName TRIGGER_EVENT_LISTENER = 65 | ClassName.get("android.hardware", "TriggerEventListener"); 66 | private static final ClassName CONTEXT = ClassName.get("android.content", "Context"); 67 | 68 | private static final ClassName LIST = ClassName.get("java.util", "List"); 69 | private static final ClassName ARRAY_LIST = ClassName.get("java.util", "ArrayList"); 70 | 71 | private static final FieldSpec LISTENER_WRAPPERS_FIELD = 72 | FieldSpec.builder(ParameterizedTypeName.get(LIST, LISTENER_WRAPPER), "listeners") 73 | .addModifiers(Modifier.PRIVATE, Modifier.FINAL) 74 | .build(); 75 | private static final FieldSpec SENSOR_MANAGER_FIELD = 76 | FieldSpec.builder(SENSOR_MANAGER, "sensorManager") 77 | .addModifiers(Modifier.PRIVATE, Modifier.FINAL) 78 | .build(); 79 | private static final MethodSpec UNBIND_METHOD = 80 | getBaseMethodBuilder("unbind").beginControlFlow("if (this.$N != null)", 81 | SENSOR_MANAGER_FIELD) 82 | .beginControlFlow("for ($T wrapper : $N)", LISTENER_WRAPPER, LISTENER_WRAPPERS_FIELD) 83 | .addStatement("wrapper.unregisterListener($N)", SENSOR_MANAGER_FIELD) 84 | .endControlFlow() 85 | .endControlFlow() 86 | .build(); 87 | 88 | // endregion 89 | 90 | /** 91 | * Generates the code for our "Sensor Binder" class and writes it to the same package as the 92 | * annotated class. 93 | * 94 | * @param groupedMethodsMap Map of annotated methods per class. 95 | * @param elementUtils ElementUtils class from {@link ProcessingEnvironment}. 96 | * @param filer File writer class from {@link ProcessingEnvironment}. 97 | * @throws IOException 98 | * @throws ProcessingException 99 | */ 100 | static void generateCode(@NonNull Map groupedMethodsMap, 101 | @NonNull Elements elementUtils, @NonNull Filer filer) 102 | throws IOException, ProcessingException { 103 | for (AnnotatedMethodsPerClass groupedMethods : groupedMethodsMap.values()) { 104 | // If we've annotated methods in an activity called "ExampleActivity" then that will be 105 | // the enclosing type element. 106 | TypeElement enclosingClassTypeElement = 107 | elementUtils.getTypeElement(groupedMethods.getEnclosingClassName()); 108 | 109 | // Create the parameterized type that our generated class will implement, 110 | // (such as "SensorBinder"). 111 | ParameterizedTypeName parameterizedInterface = ParameterizedTypeName.get(SENSOR_BINDER, 112 | TypeName.get(enclosingClassTypeElement.asType())); 113 | 114 | // Create the target parameter that will be used in the constructor and bind method, 115 | // (such as "ExampleActivity"). 116 | ParameterSpec targetParameter = 117 | ParameterSpec.builder(TypeName.get(enclosingClassTypeElement.asType()), "target") 118 | .addModifiers(Modifier.FINAL) 119 | .build(); 120 | 121 | MethodSpec constructor = 122 | createConstructor(targetParameter, groupedMethods.getItemsMap()); 123 | MethodSpec bindMethod = createBindMethod(targetParameter, groupedMethods); 124 | 125 | TypeSpec sensorBinderClass = 126 | TypeSpec.classBuilder(enclosingClassTypeElement.getSimpleName() + SUFFIX) 127 | .addModifiers(Modifier.FINAL) 128 | .addSuperinterface(parameterizedInterface) 129 | .addField(SENSOR_MANAGER_FIELD) 130 | .addField(LISTENER_WRAPPERS_FIELD) 131 | .addMethod(constructor) 132 | .addMethod(bindMethod) 133 | .addMethod(UNBIND_METHOD) 134 | .build(); 135 | 136 | // Output our generated file with the same package as the target class. 137 | PackageElement packageElement = elementUtils.getPackageOf(enclosingClassTypeElement); 138 | JavaFileObject jfo = 139 | filer.createSourceFile(enclosingClassTypeElement.getQualifiedName() + SUFFIX); 140 | Writer writer = jfo.openWriter(); 141 | JavaFile.builder(packageElement.toString(), sensorBinderClass) 142 | .addFileComment("This class is generated code from Sensor Lib. Do not modify!") 143 | .addStaticImport(CONTEXT, "SENSOR_SERVICE") 144 | .build() 145 | .writeTo(writer); 146 | writer.close(); 147 | } 148 | } 149 | 150 | /** 151 | * Create the constructor for our generated class. 152 | * 153 | * @param targetParameter The target class that has annotated methods. 154 | * @param itemsMap A map of sensor types found in the annotations with the annotated methods. 155 | * @return {@link MethodSpec} representing the constructor of our generated class. 156 | */ 157 | @NonNull 158 | private static MethodSpec createConstructor(@NonNull ParameterSpec targetParameter, 159 | @NonNull Map> itemsMap) throws ProcessingException { 160 | ParameterSpec contextParameter = ParameterSpec.builder(CONTEXT, "context").build(); 161 | Builder constructorBuilder = MethodSpec.constructorBuilder() 162 | .addModifiers(Modifier.PUBLIC) 163 | .addParameter(contextParameter) 164 | .addParameter(targetParameter) 165 | .addStatement("this.$N = ($T) $N.getSystemService(SENSOR_SERVICE)", 166 | SENSOR_MANAGER_FIELD, SENSOR_MANAGER, contextParameter) 167 | .addStatement("this.$N = new $T()", LISTENER_WRAPPERS_FIELD, ARRAY_LIST); 168 | 169 | // Loop through the sensor types that we have annotations for and create the listeners which 170 | // will call the annotated methods on our target class. 171 | for (Integer sensorType : itemsMap.keySet()) { 172 | Map annotationMap = itemsMap.get(sensorType); 173 | AnnotatedMethod sensorChangedAnnotatedMethod = annotationMap.get(OnSensorChanged.class); 174 | AnnotatedMethod accuracyChangedAnnotatedMethod = 175 | annotationMap.get(OnAccuracyChanged.class); 176 | AnnotatedMethod triggerAnnotatedMethod = annotationMap.get(OnTrigger.class); 177 | 178 | if (sensorType == TYPE_SIGNIFICANT_MOTION && (accuracyChangedAnnotatedMethod != null 179 | || sensorChangedAnnotatedMethod != null)) { 180 | throw new ProcessingException(null, String.format( 181 | "@%s and @%s are not supported for the \"TYPE_SIGNIFICANT_MOTION\" type. Use @%s for this type.", 182 | OnSensorChanged.class.getSimpleName(), OnAccuracyChanged.class.getSimpleName(), 183 | OnTrigger.class.getSimpleName())); 184 | } else if (sensorType != TYPE_SIGNIFICANT_MOTION && triggerAnnotatedMethod != null) { 185 | throw new ProcessingException(null, String.format( 186 | "The @%s is only supported for the \"TYPE_SIGNIFICANT_MOTION\" type.", 187 | OnTrigger.class.getSimpleName())); 188 | } 189 | 190 | CodeBlock listenerWrapperCodeBlock; 191 | if (triggerAnnotatedMethod != null) { 192 | listenerWrapperCodeBlock = createTriggerListenerWrapper(triggerAnnotatedMethod); 193 | constructorBuilder.addCode(listenerWrapperCodeBlock); 194 | } else if (sensorChangedAnnotatedMethod != null 195 | || accuracyChangedAnnotatedMethod != null) { 196 | listenerWrapperCodeBlock = 197 | createSensorListenerWrapper(sensorType, sensorChangedAnnotatedMethod, 198 | accuracyChangedAnnotatedMethod); 199 | constructorBuilder.addCode(listenerWrapperCodeBlock); 200 | } 201 | } 202 | 203 | return constructorBuilder.build(); 204 | } 205 | 206 | /** 207 | * Create an {@code EventListenerWrapper} that contains the {@code TriggerEventListener} and 208 | * calls the annotated methods on our target. 209 | * 210 | * @param triggerAnnotatedMethod Method annotated with {@link OnTrigger}. 211 | * @return {@link CodeBlock} of the {@code EventListenerWrapper}. 212 | */ 213 | @NonNull 214 | private static CodeBlock createTriggerListenerWrapper( 215 | @NonNull AnnotatedMethod triggerAnnotatedMethod) throws ProcessingException { 216 | checkAnnotatedMethodForErrors(triggerAnnotatedMethod.getExecutableElement(), 217 | OnTrigger.class); 218 | 219 | CodeBlock listenerBlock = CodeBlock.builder() 220 | .add("new $T() {\n", TRIGGER_EVENT_LISTENER) 221 | .indent() 222 | .add(createOnTriggerListenerMethod(triggerAnnotatedMethod).toString()) 223 | .unindent() 224 | .add("}") 225 | .build(); 226 | 227 | return CodeBlock.builder() 228 | .addStatement("this.$N.add(new $T($L))", LISTENER_WRAPPERS_FIELD, 229 | TRIGGER_EVENT_LISTENER_WRAPPER, listenerBlock) 230 | .build(); 231 | } 232 | 233 | /** 234 | * Create an {@code EventListenerWrapper} that contains the {@code 235 | * SensorEventListener} and calls the annotated methods on our target. 236 | * 237 | * @param sensorType The {@code Sensor} type. 238 | * @param sensorChangedAnnotatedMethod Method annotated with {@link OnSensorChanged}. 239 | * @param accuracyChangedAnnotatedMethod Method annotated with {@link OnAccuracyChanged}. 240 | * @return {@link CodeBlock} of the {@code EventListenerWrapper}. 241 | */ 242 | @NonNull 243 | private static CodeBlock createSensorListenerWrapper(int sensorType, 244 | @Nullable AnnotatedMethod sensorChangedAnnotatedMethod, 245 | @Nullable AnnotatedMethod accuracyChangedAnnotatedMethod) throws ProcessingException { 246 | if (sensorChangedAnnotatedMethod != null) { 247 | checkAnnotatedMethodForErrors(sensorChangedAnnotatedMethod.getExecutableElement(), 248 | OnSensorChanged.class); 249 | } 250 | if (accuracyChangedAnnotatedMethod != null) { 251 | checkAnnotatedMethodForErrors(accuracyChangedAnnotatedMethod.getExecutableElement(), 252 | OnAccuracyChanged.class); 253 | } 254 | 255 | CodeBlock listenerBlock = CodeBlock.builder() 256 | .add("new $T() {\n", SENSOR_EVENT_LISTENER) 257 | .indent() 258 | .add(createOnSensorChangedListenerMethod(sensorChangedAnnotatedMethod).toString()) 259 | .add(createOnAccuracyChangedListenerMethod(accuracyChangedAnnotatedMethod).toString()) 260 | .unindent() 261 | .add("}") 262 | .build(); 263 | 264 | int delay = 265 | getDelayForListener(sensorChangedAnnotatedMethod, accuracyChangedAnnotatedMethod); 266 | 267 | if (delay == INVALID_DELAY) { 268 | String error = 269 | String.format("@%s or @%s needs a delay value specified in the annotation", 270 | OnSensorChanged.class.getSimpleName(), OnAccuracyChanged.class.getSimpleName()); 271 | throw new ProcessingException(null, error); 272 | } 273 | 274 | return CodeBlock.builder() 275 | .addStatement("this.$N.add(new $T($L, $L, $L))", LISTENER_WRAPPERS_FIELD, 276 | SENSOR_EVENT_LISTENER_WRAPPER, sensorType, delay, listenerBlock) 277 | .build(); 278 | } 279 | 280 | /** 281 | * Creates the implementation of {@code TriggerEventListener#onTrigger(TriggerEvent)} which 282 | * calls the annotated method on our target class. 283 | * 284 | * @param annotatedMethod Method annotated with {@code OnTrigger}. 285 | * @return {@link MethodSpec} of {@code TriggerEventListener#onTrigger(TriggerEvent)}. 286 | */ 287 | @NonNull 288 | private static MethodSpec createOnTriggerListenerMethod( 289 | @NonNull AnnotatedMethod annotatedMethod) { 290 | ParameterSpec triggerEventParameter = ParameterSpec.builder(TRIGGER_EVENT, "event").build(); 291 | ExecutableElement triggerExecutableElement = annotatedMethod.getExecutableElement(); 292 | return getBaseMethodBuilder("onTrigger").addParameter(triggerEventParameter) 293 | .addStatement("target.$L($N)", triggerExecutableElement.getSimpleName(), 294 | triggerEventParameter) 295 | .build(); 296 | } 297 | 298 | /** 299 | * Creates the implementation of {@code SensorEventListener#onSensorChanged(SensorEvent)} which 300 | * calls the annotated method on our target class. 301 | * 302 | * @param annotatedMethod Method annotated with {@code OnSensorChanged}. 303 | * @return {@link MethodSpec} of {@code SensorEventListener#onSensorChanged(SensorEvent)}. 304 | */ 305 | @NonNull 306 | private static MethodSpec createOnSensorChangedListenerMethod( 307 | @Nullable AnnotatedMethod annotatedMethod) { 308 | ParameterSpec sensorEventParameter = ParameterSpec.builder(SENSOR_EVENT, "event").build(); 309 | Builder methodBuilder = 310 | getBaseMethodBuilder("onSensorChanged").addParameter(sensorEventParameter); 311 | 312 | if (annotatedMethod != null) { 313 | ExecutableElement sensorChangedExecutableElement = 314 | annotatedMethod.getExecutableElement(); 315 | methodBuilder.addStatement("target.$L($N)", 316 | sensorChangedExecutableElement.getSimpleName(), sensorEventParameter); 317 | } 318 | 319 | return methodBuilder.build(); 320 | } 321 | 322 | /** 323 | * Creates the implementation of {@code SensorEventListener#onAccuracyChanged(Sensor, int)} 324 | * which calls the annotated method on our target class. 325 | * 326 | * @param annotatedMethod Method annotated with {@link OnAccuracyChanged}. 327 | * @return {@link MethodSpec} of {@code SensorEventListener#onAccuracyChanged(Sensor, int)}. 328 | */ 329 | @NonNull 330 | private static MethodSpec createOnAccuracyChangedListenerMethod( 331 | @Nullable AnnotatedMethod annotatedMethod) { 332 | ParameterSpec sensorParameter = ParameterSpec.builder(SENSOR, "sensor").build(); 333 | ParameterSpec accuracyParameter = ParameterSpec.builder(TypeName.INT, "accuracy").build(); 334 | Builder methodBuilder = 335 | getBaseMethodBuilder("onAccuracyChanged").addParameter(sensorParameter) 336 | .addParameter(accuracyParameter); 337 | 338 | if (annotatedMethod != null) { 339 | ExecutableElement accuracyChangedExecutableElement = 340 | annotatedMethod.getExecutableElement(); 341 | methodBuilder.addStatement("target.$L($N, $N)", 342 | accuracyChangedExecutableElement.getSimpleName(), sensorParameter, 343 | accuracyParameter); 344 | } 345 | 346 | return methodBuilder.build(); 347 | } 348 | 349 | /** 350 | * Returns a delay to be used when registering the listener for the sensor. Both {@link 351 | * OnSensorChanged} and {@link OnAccuracyChanged} can have 352 | * a delay property set but only one can be used when registering the listener. 353 | *

354 | * We try {@link OnSensorChanged} first, then {@link OnAccuracyChanged}, otherwise we return a 355 | * sentinel value that will be used for errors. 356 | * 357 | * @param sensorChangedAnnotatedMethod The method wrapper for the method with the {@link 358 | * OnSensorChanged} annotation. 359 | * @param accuracyChangedAnnotatedMethod The method wrapper for the method with the {@link 360 | * OnAccuracyChanged} annotation. 361 | * @return A delay value for the sensor listener. 362 | */ 363 | private static int getDelayForListener(@Nullable AnnotatedMethod sensorChangedAnnotatedMethod, 364 | @Nullable AnnotatedMethod accuracyChangedAnnotatedMethod) { 365 | if (sensorChangedAnnotatedMethod != null 366 | && sensorChangedAnnotatedMethod.getDelay() != INVALID_DELAY) { 367 | return sensorChangedAnnotatedMethod.getDelay(); 368 | } else if (accuracyChangedAnnotatedMethod != null 369 | && accuracyChangedAnnotatedMethod.getDelay() != INVALID_DELAY) { 370 | return accuracyChangedAnnotatedMethod.getDelay(); 371 | } 372 | 373 | return INVALID_DELAY; 374 | } 375 | 376 | /** 377 | * Create the bind method for our generated class. 378 | * 379 | * @param targetParameter The target class that has annotated methods. 380 | * @param annotatedMethodsPerClass The annotated methods that are in a given class. 381 | * @return {@link MethodSpec} of the generated class bind method. 382 | */ 383 | @NonNull 384 | private static MethodSpec createBindMethod(@NonNull ParameterSpec targetParameter, 385 | @NonNull AnnotatedMethodsPerClass annotatedMethodsPerClass) throws ProcessingException { 386 | Map> itemsMap = annotatedMethodsPerClass.getItemsMap(); 387 | 388 | Builder bindMethodBuilder = getBaseMethodBuilder("bind").addParameter(targetParameter) 389 | .addStatement("int sensorType") 390 | .addStatement("$T sensor", SENSOR) 391 | .beginControlFlow("for ($T wrapper : $N)", LISTENER_WRAPPER, LISTENER_WRAPPERS_FIELD) 392 | .addStatement("sensorType = wrapper.getSensorType()") 393 | .addStatement("sensor = wrapper.getSensor($N)", SENSOR_MANAGER_FIELD); 394 | 395 | if (annotatedMethodsPerClass.hasAnnotationsOfType(OnSensorNotAvailable.class)) { 396 | bindMethodBuilder.beginControlFlow("if (sensor == null)"); 397 | 398 | // Iterate through our map of sensor types and check whether an OnSensorNotAvailable 399 | // annotation exists, if so and the sensor is unavailable call the method. 400 | List sensorTypes = new ArrayList<>(); 401 | sensorTypes.addAll(itemsMap.keySet()); 402 | for (int i = 0; i < sensorTypes.size(); i++) { 403 | Integer sensorType = sensorTypes.get(i); 404 | Map annotationMap = itemsMap.get(sensorType); 405 | AnnotatedMethod annotatedMethod = annotationMap.get(OnSensorNotAvailable.class); 406 | 407 | if (annotatedMethod != null) { 408 | checkAnnotatedMethodForErrors(annotatedMethod.getExecutableElement(), 409 | OnSensorNotAvailable.class); 410 | 411 | if (i == 0) { 412 | bindMethodBuilder.beginControlFlow("if (sensorType == $L)", sensorType); 413 | } else { 414 | bindMethodBuilder.nextControlFlow("else if (sensorType == $L)", sensorType); 415 | } 416 | 417 | bindMethodBuilder.addStatement("$N.$L()", targetParameter, 418 | annotatedMethod.getExecutableElement().getSimpleName()); 419 | } 420 | } 421 | 422 | bindMethodBuilder.endControlFlow().addStatement("continue").endControlFlow(); 423 | } 424 | 425 | return bindMethodBuilder.addStatement("wrapper.registerListener($N)", SENSOR_MANAGER_FIELD) 426 | .endControlFlow() 427 | .build(); 428 | } 429 | 430 | /** 431 | * Return a {@link Builder} with the given method name and default properties. 432 | * 433 | * @param name The name of the method. 434 | * @return A base {@link Builder} to use for methods. 435 | */ 436 | @NonNull 437 | private static Builder getBaseMethodBuilder(@NonNull String name) { 438 | return MethodSpec.methodBuilder(name) 439 | .addModifiers(Modifier.PUBLIC) 440 | .returns(void.class) 441 | .addAnnotation(Override.class); 442 | } 443 | 444 | /** 445 | * Check the annotated method for the correct parameters needed based on the annotation. 446 | * 447 | * @param element The annotated element. 448 | * @param annotation The annotation class being checked. 449 | * @throws ProcessingException 450 | */ 451 | private static void checkAnnotatedMethodForErrors(@NonNull ExecutableElement element, 452 | @NonNull Class annotation) throws ProcessingException { 453 | ListenerMethod method = annotation.getAnnotation(ListenerMethod.class); 454 | String[] expectedParameters = method.parameters(); 455 | List parameters = element.getParameters(); 456 | if (parameters.size() != expectedParameters.length) { 457 | String error = String.format("@%s methods can only have %s parameter(s). (%s.%s)", 458 | annotation.getSimpleName(), method.parameters().length, 459 | element.getEnclosingElement().getSimpleName(), element.getSimpleName()); 460 | throw new ProcessingException(element, error); 461 | } 462 | 463 | for (int i = 0; i < parameters.size(); i++) { 464 | VariableElement parameter = parameters.get(i); 465 | TypeMirror methodParameterType = parameter.asType(); 466 | String expectedType = expectedParameters[i]; 467 | if (!expectedType.equals(methodParameterType.toString())) { 468 | String error = String.format( 469 | "Method parameters are not valid for @%s annotated method. Expected parameters of type(s): %s. (%s.%s)", 470 | annotation.getSimpleName(), Joiner.on(", ").join(expectedParameters), 471 | element.getEnclosingElement().getSimpleName(), element.getSimpleName()); 472 | throw new ProcessingException(element, error); 473 | } 474 | } 475 | } 476 | } 477 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/java/com/dvoiss/sensorannotations/SensorAnnotationsProcessor.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.dvoiss.sensorannotations.exception.ProcessingException; 4 | import java.io.IOException; 5 | import java.lang.annotation.Annotation; 6 | import java.util.HashSet; 7 | import java.util.LinkedHashMap; 8 | import java.util.Map; 9 | import java.util.Set; 10 | import javax.annotation.processing.AbstractProcessor; 11 | import javax.annotation.processing.Filer; 12 | import javax.annotation.processing.Messager; 13 | import javax.annotation.processing.ProcessingEnvironment; 14 | import javax.annotation.processing.RoundEnvironment; 15 | import javax.lang.model.SourceVersion; 16 | import javax.lang.model.element.Element; 17 | import javax.lang.model.element.ElementKind; 18 | import javax.lang.model.element.ExecutableElement; 19 | import javax.lang.model.element.Modifier; 20 | import javax.lang.model.element.TypeElement; 21 | import javax.lang.model.util.Elements; 22 | import javax.tools.Diagnostic; 23 | import org.checkerframework.checker.nullness.qual.NonNull; 24 | import org.checkerframework.checker.nullness.qual.Nullable; 25 | 26 | /** 27 | * The main annotation processor for the library. See {@link SensorAnnotationsFileBuilder} for more 28 | * info. 29 | */ 30 | public class SensorAnnotationsProcessor extends AbstractProcessor { 31 | private static final boolean DEBUG_LOGGING = false; 32 | 33 | @NonNull private Elements mElementUtils; 34 | @NonNull private Filer mFiler; 35 | @NonNull private Messager mMessager; 36 | 37 | /** 38 | * Mapping between classes and a wrapper object containing all the annotated methods on it. 39 | */ 40 | @NonNull private final Map mGroupedMethodsMap = 41 | new LinkedHashMap<>(); 42 | 43 | @Override 44 | public synchronized void init(@NonNull ProcessingEnvironment env) { 45 | super.init(env); 46 | mMessager = processingEnv.getMessager(); 47 | mFiler = processingEnv.getFiler(); 48 | mElementUtils = processingEnv.getElementUtils(); 49 | } 50 | 51 | @Override 52 | public boolean process(@NonNull Set annotations, 53 | @NonNull RoundEnvironment roundEnv) { 54 | try { 55 | processAnnotation(OnSensorChanged.class, roundEnv); 56 | processAnnotation(OnAccuracyChanged.class, roundEnv); 57 | processAnnotation(OnSensorNotAvailable.class, roundEnv); 58 | processAnnotation(OnTrigger.class, roundEnv); 59 | } catch (ProcessingException e) { 60 | error(e.getElement(), e.getMessage()); 61 | } 62 | 63 | try { 64 | warn(null, "Preparing to create %d generated classes.", mGroupedMethodsMap.size()); 65 | 66 | // If we've gotten here we've found all the annotations and grouped them accordingly. 67 | // Now generate the SensorBinder classes. 68 | SensorAnnotationsFileBuilder.generateCode(mGroupedMethodsMap, mElementUtils, mFiler); 69 | 70 | // Clear the map so a future processing round doesn't re-process the same annotations. 71 | mGroupedMethodsMap.clear(); 72 | } catch (IOException e) { 73 | error(null, e.getMessage()); 74 | } catch (ProcessingException e) { 75 | error(e.getElement(), e.getMessage()); 76 | } 77 | 78 | return true; 79 | } 80 | 81 | private void processAnnotation(Class annotationClass, 82 | @NonNull RoundEnvironment roundEnv) throws ProcessingException { 83 | Set elements = roundEnv.getElementsAnnotatedWith(annotationClass); 84 | 85 | warn(null, "Processing %d elements annotated with @%s", elements.size(), elements); 86 | 87 | for (Element element : elements) { 88 | if (element.getKind() != ElementKind.METHOD) { 89 | throw new ProcessingException(element, 90 | String.format("Only methods can be annotated with @%s", 91 | annotationClass.getSimpleName())); 92 | } else { 93 | ExecutableElement executableElement = (ExecutableElement) element; 94 | 95 | try { 96 | processMethod(executableElement, annotationClass); 97 | } catch (IllegalArgumentException e) { 98 | throw new ProcessingException(executableElement, e.getMessage()); 99 | } 100 | } 101 | } 102 | } 103 | 104 | private void processMethod(ExecutableElement executableElement, 105 | Class annotationClass) throws ProcessingException { 106 | AnnotatedMethod annotatedMethod = new AnnotatedMethod(executableElement, annotationClass); 107 | 108 | checkMethodValidity(annotatedMethod); 109 | 110 | TypeElement enclosingClass = findEnclosingClass(annotatedMethod); 111 | if (enclosingClass == null) { 112 | throw new ProcessingException(null, 113 | String.format("Can not find enclosing class for method %s", 114 | annotatedMethod.getExecutableElement().getSimpleName().toString())); 115 | } else { 116 | String enclosingClassName = enclosingClass.getQualifiedName().toString(); 117 | AnnotatedMethodsPerClass groupedMethods = mGroupedMethodsMap.get(enclosingClassName); 118 | if (groupedMethods == null) { 119 | groupedMethods = new AnnotatedMethodsPerClass(enclosingClassName); 120 | mGroupedMethodsMap.put(enclosingClassName, groupedMethods); 121 | } 122 | 123 | groupedMethods.add(annotationClass, annotatedMethod); 124 | } 125 | } 126 | 127 | private void checkMethodValidity(@NonNull AnnotatedMethod item) throws ProcessingException { 128 | ExecutableElement methodElement = item.getExecutableElement(); 129 | Set modifiers = methodElement.getModifiers(); 130 | 131 | // The annotated method needs to be accessible by the generated class which will have 132 | // the same package. Public or "package private" (default) methods are required. 133 | if (modifiers.contains(Modifier.PRIVATE) || modifiers.contains(Modifier.PROTECTED)) { 134 | throw new ProcessingException(methodElement, 135 | String.format("The method %s can not be private or protected.", 136 | methodElement.getSimpleName().toString())); 137 | } 138 | 139 | // We cannot annotate abstract methods, we need to annotate the actual implementation of 140 | // the method on the implementing class. 141 | if (modifiers.contains(Modifier.ABSTRACT)) { 142 | throw new ProcessingException(methodElement, String.format( 143 | "The method %s is abstract. You can't annotate abstract methods with @%s", 144 | methodElement.getSimpleName().toString(), AnnotatedMethod.class.getSimpleName())); 145 | } 146 | } 147 | 148 | @Nullable 149 | private TypeElement findEnclosingClass(@NonNull AnnotatedMethod annotatedMethod) { 150 | TypeElement enclosingClass; 151 | 152 | ExecutableElement methodElement = annotatedMethod.getExecutableElement(); 153 | while (true) { 154 | Element enclosingElement = methodElement.getEnclosingElement(); 155 | if (enclosingElement.getKind() == ElementKind.CLASS) { 156 | enclosingClass = (TypeElement) enclosingElement; 157 | break; 158 | } 159 | } 160 | 161 | return enclosingClass; 162 | } 163 | 164 | @NonNull 165 | @Override 166 | public Set getSupportedAnnotationTypes() { 167 | Set types = new HashSet<>(); 168 | types.add(OnSensorChanged.class.getCanonicalName()); 169 | types.add(OnAccuracyChanged.class.getCanonicalName()); 170 | types.add(OnSensorNotAvailable.class.getCanonicalName()); 171 | types.add(OnTrigger.class.getCanonicalName()); 172 | return types; 173 | } 174 | 175 | @NonNull 176 | @Override 177 | public SourceVersion getSupportedSourceVersion() { 178 | return SourceVersion.latestSupported(); 179 | } 180 | 181 | private void error(@Nullable Element e, @NonNull String msg, @Nullable Object... args) { 182 | mMessager.printMessage(Diagnostic.Kind.ERROR, String.format(msg, args), e); 183 | } 184 | 185 | private void warn(@Nullable Element e, @NonNull String msg, @Nullable Object... args) { 186 | if (DEBUG_LOGGING) { 187 | mMessager.printMessage(Diagnostic.Kind.WARNING, String.format(msg, args), e); 188 | } 189 | } 190 | } 191 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/java/com/dvoiss/sensorannotations/exception/ProcessingException.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.exception; 2 | 3 | import javax.lang.model.element.Element; 4 | import org.checkerframework.checker.nullness.qual.Nullable; 5 | 6 | /** 7 | * Processor exception class for errors that occur during processing. 8 | */ 9 | public class ProcessingException extends Exception { 10 | @Nullable private final Element mElement; 11 | 12 | public ProcessingException(@Nullable Element element, @Nullable String message) { 13 | super(message); 14 | this.mElement = element; 15 | } 16 | 17 | @Nullable 18 | public Element getElement() { 19 | return mElement; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /sensorannotations-compiler/src/main/resources/META-INF/services/javax.annotation.processing.Processor: -------------------------------------------------------------------------------- 1 | com.dvoiss.sensorannotations.SensorAnnotationsProcessor 2 | -------------------------------------------------------------------------------- /sensorannotations-lib/build.gradle: -------------------------------------------------------------------------------- 1 | import org.gradle.internal.jvm.Jvm 2 | 3 | apply plugin: 'com.android.library' 4 | apply plugin: 'com.novoda.bintray-release' 5 | apply from: '../config/quality/quality.gradle' 6 | 7 | android { 8 | compileSdkVersion rootProject.ext.compileSdkVersion 9 | buildToolsVersion rootProject.ext.buildToolsVersion 10 | 11 | defaultConfig { 12 | minSdkVersion rootProject.ext.minSdkVersion 13 | consumerProguardFiles 'proguard-rules.txt' 14 | testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner' 15 | } 16 | 17 | compileOptions { 18 | sourceCompatibility sourceCompatibilityVersion 19 | targetCompatibility targetCompatibilityVersion 20 | } 21 | } 22 | 23 | dependencies { 24 | compile project(':sensorannotations-annotations') 25 | compile deps.supportannotations 26 | 27 | testCompile project(':sensorannotations-compiler') 28 | testCompile deps.junit 29 | testCompile deps.truth 30 | testCompile deps.robolectric 31 | testCompile deps.compiletesting 32 | testCompile files(Jvm.current().getRuntimeJar()) 33 | testCompile files(Jvm.current().getToolsJar()) 34 | } 35 | 36 | publish { 37 | userOrg = 'dvoiss' 38 | groupId = 'com.dvoiss' 39 | artifactId = 'sensorannotations' 40 | publishVersion = rootProject.ext.version 41 | description = 'Annotate methods to use as listeners for a specific sensor.' 42 | website = 'https://github.com/dvoiss/sensorannotations' 43 | } 44 | -------------------------------------------------------------------------------- /sensorannotations-lib/proguard-rules.txt: -------------------------------------------------------------------------------- 1 | -keep public class * implements com.dvoiss.sensorannotations.internal.Sensorbinder { public (...); } 2 | 3 | -keep class com.dvoiss.sensorannotations.* 4 | -keepclasseswithmembernames class * { @com.dvoiss.sensorannotations.* ; } 5 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/java/com/dvoiss/sensorannotations/SensorAnnotations.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import android.content.Context; 4 | import android.support.annotation.NonNull; 5 | import android.support.annotation.Nullable; 6 | import android.util.Log; 7 | import com.dvoiss.sensorannotations.internal.SensorBinder; 8 | import java.lang.reflect.InvocationTargetException; 9 | import java.util.LinkedHashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * Annotating methods as listeners for use with Android sensors. 14 | * 15 | * Binding needs a {@link Context} object to use to find the sensor manager. Binding can also be 16 | * done on a specific object with {@linkplain #bind(Object, Context)}. 17 | * 18 | * Per the best practices guidelines for sensors (Sensors 19 | * Best Practices), SensorAnnotations needs to be able to unregister listeners. This is best 20 | * done in an onPause method of the activity lifecycle. 21 | * 22 | * A good portion of this class is based on ButterKnife's binding code 23 | * (https://github.com/JakeWharton/butterknife). 24 | */ 25 | public class SensorAnnotations { 26 | private static final boolean DEBUG_LOGGING = BuildConfig.DEBUG; 27 | private static final String TAG = SensorAnnotations.class.getSimpleName(); 28 | 29 | private static final String ANDROID_PREFIX = "android."; 30 | private static final String JAVA_PREFIX = "java."; 31 | 32 | /** 33 | * The suffix will be added to the name of the generated class. 34 | */ 35 | private static final String SUFFIX = "$$SensorBinder"; 36 | 37 | static final SensorBinder NO_OP_VIEW_BINDER = new SensorBinder() { 38 | @Override 39 | public void bind(Object target) {} 40 | 41 | @Override 42 | public void unbind() {} 43 | }; 44 | 45 | static final Map, SensorBinder> BINDER_CACHE = new LinkedHashMap<>(); 46 | 47 | /** 48 | * Binding needs a context object to find the {@code SensorManager}. Binding will call the bind 49 | * method of the {@link SensorBinder} which will register a {@code SensorEventListener} that 50 | * will call the annotated methods. 51 | * 52 | * @param context {@link Context} Context object needed for finding the {@code SensorManager}. 53 | */ 54 | public static void bind(@Nullable Context context) { 55 | bind(context, context); 56 | } 57 | 58 | /** 59 | * Alternative bind method for binding to classes that are not {@code Context} objects. 60 | * 61 | * @param target The target object being bound to. 62 | * @param context {@link Context} Context object needed for finding the {@code SensorManager}. 63 | */ 64 | public static void bind(@Nullable Object target, @Nullable Context context) { 65 | if (target == null || context == null) { 66 | throw new RuntimeException("Bind method only accepts non-null parameters."); 67 | } 68 | 69 | Class targetClass = target.getClass(); 70 | try { 71 | if (DEBUG_LOGGING) { 72 | Log.d(TAG, "Looking up sensor binder for " + targetClass.getName()); 73 | } 74 | 75 | SensorBinder sensorBinder = findSensorBinderToBind(target, context); 76 | if (sensorBinder != null) { 77 | //noinspection unchecked 78 | sensorBinder.bind(target); 79 | } 80 | } catch (Exception e) { 81 | throw new RuntimeException("Unable to bind sensors for " + targetClass.getName(), e); 82 | } 83 | } 84 | 85 | /** 86 | * Unbinding is important to do in {@code onPause} methods so we can un-register the {@code 87 | * SensorEventListener} Check the cache for the sensor binder and unbind. 88 | * 89 | * @param target The target object being bound to. 90 | */ 91 | public static void unbind(@Nullable Object target) { 92 | if (target == null) { 93 | throw new RuntimeException( 94 | "Null value for target parameter passed into unbind method."); 95 | } 96 | 97 | Class targetClass = target.getClass(); 98 | try { 99 | if (DEBUG_LOGGING) { 100 | Log.d(TAG, "Looking up sensor binder for " + targetClass.getName()); 101 | } 102 | 103 | SensorBinder sensorBinder = checkCacheForSensorBinderClass(target); 104 | if (sensorBinder != null) { 105 | sensorBinder.unbind(); 106 | } 107 | } catch (Exception e) { 108 | throw new RuntimeException("Unable to unbind sensors for " + targetClass.getName(), e); 109 | } 110 | } 111 | 112 | /** 113 | * Find the class generated by the annotation processor that we need to bind. 114 | * 115 | * @param target The target object being bound to. 116 | * @param context {@link Context} Context object needed for finding the {@code SensorManager}. 117 | * @return The {@link SensorBinder} for the target or {@link #NO_OP_VIEW_BINDER}. 118 | * @throws IllegalAccessException 119 | * @throws InstantiationException 120 | */ 121 | private static SensorBinder findSensorBinderToBind(@Nullable Object target, 122 | @Nullable Context context) throws IllegalAccessException, InstantiationException { 123 | if (target == null || context == null) { 124 | if (DEBUG_LOGGING) { 125 | Log.d(TAG, "Null parameters are not valid."); 126 | } 127 | return NO_OP_VIEW_BINDER; 128 | } 129 | 130 | SensorBinder sensorBinder = checkCacheForSensorBinderClass(target); 131 | if (sensorBinder != null) { 132 | if (DEBUG_LOGGING) { 133 | Log.d(TAG, "Loaded cached sensor binder."); 134 | } 135 | return sensorBinder; 136 | } 137 | 138 | Class targetClass = target.getClass(); 139 | String className = targetClass.getName(); 140 | if (className.startsWith(ANDROID_PREFIX) || className.startsWith(JAVA_PREFIX)) { 141 | if (DEBUG_LOGGING) { 142 | Log.d(TAG, "Reached framework class. Abandoning search."); 143 | } 144 | return NO_OP_VIEW_BINDER; 145 | } 146 | 147 | try { 148 | Class viewBindingClass = Class.forName(className + SUFFIX); 149 | 150 | sensorBinder = 151 | (SensorBinder) viewBindingClass.getConstructor(Context.class, targetClass) 152 | .newInstance(context, target); 153 | 154 | if (sensorBinder == null) { 155 | if (DEBUG_LOGGING) { 156 | Log.d(TAG, "Could not instantiate constructor for class."); 157 | } 158 | return NO_OP_VIEW_BINDER; 159 | } 160 | 161 | if (DEBUG_LOGGING) { 162 | Log.d(TAG, "Loaded sensor binder class."); 163 | } 164 | } catch (ClassNotFoundException e) { 165 | if (DEBUG_LOGGING) { 166 | Log.d(TAG, "Not found. Trying superclass " + targetClass.getSuperclass().getName()); 167 | } 168 | sensorBinder = findSensorBinderToBind(targetClass.getSuperclass(), context); 169 | } catch (NoSuchMethodException e) { 170 | if (DEBUG_LOGGING) { 171 | Log.d(TAG, "Could not find constructor for class. Abandoning search."); 172 | } 173 | sensorBinder = NO_OP_VIEW_BINDER; 174 | } catch (InvocationTargetException e) { 175 | if (DEBUG_LOGGING) { 176 | Log.d(TAG, "Could not instantiate constructor for class."); 177 | } 178 | sensorBinder = NO_OP_VIEW_BINDER; 179 | } 180 | 181 | BINDER_CACHE.put(targetClass, sensorBinder); 182 | 183 | return sensorBinder; 184 | } 185 | 186 | /** 187 | * Check the cache for a {@link SensorBinder} that matches the target parameter. 188 | * 189 | * @param target The target object being bound to. 190 | * @return The cached {@link SensorBinder} for the target or null. 191 | */ 192 | private static SensorBinder checkCacheForSensorBinderClass(@NonNull Object target) { 193 | Class targetClass = target.getClass(); 194 | SensorBinder sensorBinder = BINDER_CACHE.get(targetClass); 195 | return sensorBinder != null ? sensorBinder : null; 196 | } 197 | } 198 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/java/com/dvoiss/sensorannotations/internal/EventListenerWrapper.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.internal; 2 | 3 | import android.hardware.Sensor; 4 | import android.hardware.SensorManager; 5 | import android.support.annotation.NonNull; 6 | 7 | /** 8 | * This is a helper class used for re-registering the event listener with the correct values. 9 | */ 10 | @SuppressWarnings({ "UnusedDeclaration" }) 11 | abstract public class EventListenerWrapper { 12 | private final int mSensorType; 13 | @NonNull private final T mEventListener; 14 | 15 | public EventListenerWrapper(int sensorType, @NonNull T eventListener) { 16 | this.mSensorType = sensorType; 17 | this.mEventListener = eventListener; 18 | } 19 | 20 | public int getSensorType() { 21 | return mSensorType; 22 | } 23 | 24 | @NonNull 25 | public T getEventListener() { 26 | return mEventListener; 27 | } 28 | 29 | @NonNull 30 | public Sensor getSensor(@NonNull SensorManager sensorManager) { 31 | return sensorManager.getDefaultSensor(mSensorType); 32 | } 33 | 34 | abstract public void registerListener(@NonNull SensorManager sensorManager); 35 | 36 | abstract public void unregisterListener(@NonNull SensorManager sensorManager); 37 | } 38 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/java/com/dvoiss/sensorannotations/internal/SensorBinder.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.internal; 2 | 3 | public interface SensorBinder { 4 | void bind(T target); 5 | 6 | void unbind(); 7 | } 8 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/java/com/dvoiss/sensorannotations/internal/SensorEventListenerWrapper.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.internal; 2 | 3 | import android.hardware.SensorEventListener; 4 | import android.hardware.SensorManager; 5 | import android.support.annotation.NonNull; 6 | 7 | /** 8 | * This is a helper class used for re-registering the event listener with the correct values. 9 | */ 10 | @SuppressWarnings({ "UnusedDeclaration" }) 11 | public class SensorEventListenerWrapper extends EventListenerWrapper { 12 | private final int mDelay; 13 | 14 | public SensorEventListenerWrapper(int sensorType, int delay, 15 | @NonNull SensorEventListener sensorEventListener) { 16 | super(sensorType, sensorEventListener); 17 | this.mDelay = delay; 18 | } 19 | 20 | public void registerListener(@NonNull SensorManager sensorManager) { 21 | sensorManager.registerListener(getEventListener(), getSensor(sensorManager), mDelay); 22 | } 23 | 24 | public void unregisterListener(@NonNull SensorManager sensorManager) { 25 | sensorManager.unregisterListener(getEventListener()); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/main/java/com/dvoiss/sensorannotations/internal/TriggerEventListenerWrapper.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations.internal; 2 | 3 | import android.annotation.TargetApi; 4 | import android.hardware.Sensor; 5 | import android.hardware.SensorManager; 6 | import android.hardware.TriggerEventListener; 7 | import android.os.Build; 8 | import android.support.annotation.NonNull; 9 | 10 | /** 11 | * This is a helper class used for re-registering the event listener with the correct values. 12 | */ 13 | @SuppressWarnings({ "UnusedDeclaration" }) 14 | public class TriggerEventListenerWrapper extends EventListenerWrapper { 15 | @TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR2) 16 | public TriggerEventListenerWrapper(@NonNull TriggerEventListener sensorEventListener) { 17 | super(Sensor.TYPE_SIGNIFICANT_MOTION, sensorEventListener); 18 | } 19 | 20 | public void registerListener(@NonNull SensorManager sensorManager) { 21 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 22 | sensorManager.requestTriggerSensor(getEventListener(), getSensor(sensorManager)); 23 | } 24 | } 25 | 26 | public void unregisterListener(@NonNull SensorManager sensorManager) { 27 | if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) { 28 | sensorManager.cancelTriggerSensor(getEventListener(), getSensor(sensorManager)); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/BindAllAnnotationsTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.dvoiss.sensorannotations.TestUtils.shouldGenerateBindingSource; 6 | 7 | public class BindAllAnnotationsTest { 8 | 9 | @Test 10 | public void bindAllSucceeds() { 11 | String source = "package test;\n" 12 | + "\n" 13 | + "import android.app.Activity;\n" 14 | + "import android.hardware.Sensor;\n" 15 | + "import android.hardware.SensorEvent;\n" 16 | + "import android.hardware.TriggerEvent;\n" 17 | + "import com.dvoiss.sensorannotations.OnAccuracyChanged;\n" 18 | + "import com.dvoiss.sensorannotations.OnSensorChanged;\n" 19 | + "import com.dvoiss.sensorannotations.OnSensorNotAvailable;\n" 20 | + "import com.dvoiss.sensorannotations.OnTrigger;\n" 21 | + "\n" 22 | + "public class Test extends Activity {\n" 23 | + " @OnSensorChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 24 | + " void testMagneticFieldSensorChanged(SensorEvent event) {}\n" 25 | + "\n" 26 | + " @OnSensorNotAvailable(Sensor.TYPE_MAGNETIC_FIELD)\n" 27 | + " void testMagneticFieldSensorNotAvailable() {}\n" 28 | + "\n" 29 | + " @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 30 | + " void testMagneticFieldAccuracyChanged(Sensor sensor, int accuracy) {}\n" 31 | + "\n" 32 | + " @OnTrigger\n" 33 | + " public void testSignificantMotionTrigger(TriggerEvent event) {}\n" 34 | + "}"; 35 | 36 | String bindingSource = "// This class is generated code from Sensor Lib. Do not modify!\n" 37 | + "package test;\n" 38 | + "\n" 39 | + "import static android.content.Context.SENSOR_SERVICE;\n" 40 | + "\n" 41 | + "import android.content.Context;\n" 42 | + "import android.hardware.Sensor;\n" 43 | + "import android.hardware.SensorEventListener;\n" 44 | + "import android.hardware.SensorManager;\n" 45 | + "import android.hardware.TriggerEventListener;\n" 46 | + "import com.dvoiss.sensorannotations.internal.EventListenerWrapper;\n" 47 | + "import com.dvoiss.sensorannotations.internal.SensorBinder;\n" 48 | + "import com.dvoiss.sensorannotations.internal.SensorEventListenerWrapper;\n" 49 | + "import com.dvoiss.sensorannotations.internal.TriggerEventListenerWrapper;\n" 50 | + "import java.lang.Override;\n" 51 | + "import java.util.ArrayList;\n" 52 | + "import java.util.List;\n" 53 | + "\n" 54 | + "final class Test$$SensorBinder implements SensorBinder {\n" 55 | + " private final SensorManager sensorManager;\n" 56 | + "\n" 57 | + " private final List listeners;\n" 58 | + "\n" 59 | + " public Test$$SensorBinder(Context context, final Test target) {\n" 60 | + " this.sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);\n" 61 | + " this.listeners = new ArrayList();\n" 62 | + " this.listeners.add(new SensorEventListenerWrapper(2, 3, new SensorEventListener() {\n" 63 | + " @java.lang.Override\n" 64 | + " public void onSensorChanged(android.hardware.SensorEvent event) {\n" 65 | + " target.testMagneticFieldSensorChanged(event);\n" 66 | + " }\n" 67 | + " @java.lang.Override\n" 68 | + " public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {\n" 69 | + " target.testMagneticFieldAccuracyChanged(sensor, accuracy);\n" 70 | + " }\n" 71 | + " }));\n" 72 | + " this.listeners.add(new TriggerEventListenerWrapper(new TriggerEventListener() {\n" 73 | + " @java.lang.Override\n" 74 | + " public void onTrigger(android.hardware.TriggerEvent event) {\n" 75 | + " target.testSignificantMotionTrigger(event);\n" 76 | + " }\n" 77 | + " }));\n" 78 | + " }\n" 79 | + "\n" 80 | + " @Override\n" 81 | + " public void bind(final Test target) {\n" 82 | + " int sensorType;\n" 83 | + " Sensor sensor;\n" 84 | + " for (EventListenerWrapper wrapper : listeners) {\n" 85 | + " sensorType = wrapper.getSensorType();\n" 86 | + " sensor = wrapper.getSensor(sensorManager);\n" 87 | + " if (sensor == null) {\n" 88 | + " if (sensorType == 2) {\n" 89 | + " target.testMagneticFieldSensorNotAvailable();\n" 90 | + " }" 91 | + " continue;\n" 92 | + " }\n" 93 | + " wrapper.registerListener(sensorManager);\n" 94 | + " }\n" 95 | + " }\n" 96 | + "\n" 97 | + " @Override\n" 98 | + " public void unbind() {\n" 99 | + " if (this.sensorManager != null) {\n" 100 | + " for (EventListenerWrapper wrapper : listeners) {\n" 101 | + " wrapper.unregisterListener(sensorManager);\n" 102 | + " }\n" 103 | + " }\n" 104 | + " }\n" 105 | + "}\n"; 106 | 107 | shouldGenerateBindingSource(source, bindingSource); 108 | } 109 | } 110 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/BindOnAccuracyChangedTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.dvoiss.sensorannotations.TestUtils.shouldFailWithError; 6 | import static com.dvoiss.sensorannotations.TestUtils.shouldGenerateBindingSource; 7 | 8 | public class BindOnAccuracyChangedTest { 9 | 10 | @Test 11 | public void bindOnAccuracyChangedFailsWithInvalidAnnotationParameter() { 12 | String source = "package test;\n" 13 | + "\n" 14 | + "import android.app.Activity;\n" 15 | + "import android.hardware.Sensor;\n" 16 | + "import com.dvoiss.sensorannotations.OnAccuracyChanged;\n" 17 | + "\n" 18 | + "public class Test extends Activity {\n" 19 | + " @OnAccuracyChanged\n" 20 | + " void testMagneticFieldAccuracyChanged(Sensor sensor, int accuracy) {}\n" 21 | + "}\n"; 22 | 23 | String error = 24 | "No sensor type specified in @OnAccuracyChanged for method testMagneticFieldAccuracyChanged. Set a sensor type such as Sensor.TYPE_ACCELEROMETER."; 25 | 26 | shouldFailWithError(source, error); 27 | } 28 | 29 | @Test 30 | public void bindOnAccuracyChangedFailsWithInvalidMethodParameter() { 31 | String source = "package test;\n" 32 | + "\n" 33 | + "import android.app.Activity;\n" 34 | + "import android.hardware.Sensor;\n" 35 | + "import com.dvoiss.sensorannotations.OnAccuracyChanged;\n" 36 | + "\n" 37 | + "public class Test extends Activity {\n" 38 | + " @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 39 | + " void testMagneticFieldAccuracyChanged(Object wrongType, int accuracy) {}\n" 40 | + "}\n"; 41 | 42 | String error = 43 | "Method parameters are not valid for @OnAccuracyChanged annotated method. Expected parameters of type(s): android.hardware.Sensor, int. (Test.testMagneticFieldAccuracyChanged)"; 44 | 45 | shouldFailWithError(source, error); 46 | } 47 | 48 | @Test 49 | public void bindOnAccuracyChangedFailsWithInvalidNumberOfMethodParameter() { 50 | String source = "package test;\n" 51 | + "\n" 52 | + "import android.app.Activity;\n" 53 | + "import android.hardware.Sensor;\n" 54 | + "import com.dvoiss.sensorannotations.OnAccuracyChanged;\n" 55 | + "\n" 56 | + "public class Test extends Activity {\n" 57 | + " @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 58 | + " void testMagneticFieldSensorChanged(Sensor sensor, int accuracy, int extra) {}\n" 59 | + "}\n"; 60 | 61 | String error = 62 | "@OnAccuracyChanged methods can only have 2 parameter(s). (Test.testMagneticFieldSensorChanged)"; 63 | 64 | shouldFailWithError(source, error); 65 | } 66 | 67 | @Test 68 | public void bindOnAccuracyChangedSucceeds() { 69 | String source = "package test;\n" 70 | + "\n" 71 | + "import android.app.Activity;\n" 72 | + "import android.hardware.Sensor;\n" 73 | + "import com.dvoiss.sensorannotations.OnAccuracyChanged;\n" 74 | + "\n" 75 | + "public class Test extends Activity {\n" 76 | + " @OnAccuracyChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 77 | + " void testMagneticFieldAccuracyChanged(Sensor sensor, int accuracy) {}\n" 78 | + "}\n"; 79 | 80 | String bindingSource = "// This class is generated code from Sensor Lib. Do not modify!\n" 81 | + "package test;\n" 82 | + "\n" 83 | + "import static android.content.Context.SENSOR_SERVICE;\n" 84 | + "\n" 85 | + "import android.content.Context;\n" 86 | + "import android.hardware.Sensor;\n" 87 | + "import android.hardware.SensorEventListener;\n" 88 | + "import android.hardware.SensorManager;\n" 89 | + "import com.dvoiss.sensorannotations.internal.EventListenerWrapper;\n" 90 | + "import com.dvoiss.sensorannotations.internal.SensorBinder;\n" 91 | + "import com.dvoiss.sensorannotations.internal.SensorEventListenerWrapper;\n" 92 | + "import java.lang.Override;\n" 93 | + "import java.util.ArrayList;\n" 94 | + "import java.util.List;\n" 95 | + "\n" 96 | + "final class Test$$SensorBinder implements SensorBinder {\n" 97 | + " private final SensorManager sensorManager;\n" 98 | + "\n" 99 | + " private final List listeners;\n" 100 | + "\n" 101 | + " public Test$$SensorBinder(Context context, final Test target) {\n" 102 | + " this.sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);\n" 103 | + " this.listeners = new ArrayList();\n" 104 | + " this.listeners.add(new SensorEventListenerWrapper(2, 3, new SensorEventListener() {\n" 105 | + " @java.lang.Override\n" 106 | + " public void onSensorChanged(android.hardware.SensorEvent event) {\n" 107 | + " }\n" 108 | + " @java.lang.Override\n" 109 | + " public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {\n" 110 | + " target.testMagneticFieldAccuracyChanged(sensor, accuracy);\n" 111 | + " }\n" 112 | + " }));\n" 113 | + " }\n" 114 | + "\n" 115 | + " @Override\n" 116 | + " public void bind(final Test target) {\n" 117 | + " int sensorType;\n" 118 | + " Sensor sensor;\n" 119 | + " for (EventListenerWrapper wrapper : listeners) {\n" 120 | + " sensorType = wrapper.getSensorType();\n" 121 | + " sensor = wrapper.getSensor(sensorManager);\n" 122 | + " wrapper.registerListener(sensorManager);\n" 123 | + " }\n" 124 | + " }\n" 125 | + "\n" 126 | + " @Override\n" 127 | + " public void unbind() {\n" 128 | + " if (this.sensorManager != null) {\n" 129 | + " for (EventListenerWrapper wrapper : listeners) {\n" 130 | + " wrapper.unregisterListener(sensorManager);\n" 131 | + " }\n" 132 | + " }\n" 133 | + " }\n" 134 | + "}\n"; 135 | 136 | shouldGenerateBindingSource(source, bindingSource); 137 | } 138 | } 139 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/BindOnSensorChangedTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.dvoiss.sensorannotations.TestUtils.shouldFailWithError; 6 | import static com.dvoiss.sensorannotations.TestUtils.shouldGenerateBindingSource; 7 | 8 | public class BindOnSensorChangedTest { 9 | 10 | @Test 11 | public void bindOnSensorChangedFailsWithInvalidAnnotationParameter() { 12 | String source = "package test;\n" 13 | + "\n" 14 | + "import android.app.Activity;\n" 15 | + "import android.hardware.Sensor;\n" 16 | + "import com.dvoiss.sensorannotations.OnSensorChanged;\n" 17 | + "\n" 18 | + "public class Test extends Activity {\n" 19 | + " @OnSensorChanged\n" 20 | + " void testMagneticFieldSensorChanged(SensorEvent event) {}\n" 21 | + "}\n"; 22 | 23 | String error = 24 | "No sensor type specified in @OnSensorChanged for method testMagneticFieldSensorChanged. Set a sensor type such as Sensor.TYPE_ACCELEROMETER."; 25 | 26 | shouldFailWithError(source, error); 27 | } 28 | 29 | @Test 30 | public void bindOnSensorChangedFailsWithInvalidMethodParameter() { 31 | String source = "package test;\n" 32 | + "\n" 33 | + "import android.app.Activity;\n" 34 | + "import android.hardware.Sensor;\n" 35 | + "import com.dvoiss.sensorannotations.OnSensorChanged;\n" 36 | + "\n" 37 | + "public class Test extends Activity {\n" 38 | + " @OnSensorChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 39 | + " void testMagneticFieldSensorChanged(Object wrongType) {}\n" 40 | + "}\n"; 41 | 42 | String error = 43 | "Method parameters are not valid for @OnSensorChanged annotated method. Expected parameters of type(s): android.hardware.SensorEvent. (Test.testMagneticFieldSensorChanged)"; 44 | 45 | shouldFailWithError(source, error); 46 | } 47 | 48 | @Test 49 | public void bindOnSensorChangedFailsWithInvalidNumberOfMethodParameter() { 50 | String source = "package test;\n" 51 | + "\n" 52 | + "import android.app.Activity;\n" 53 | + "import android.hardware.Sensor;\n" 54 | + "import com.dvoiss.sensorannotations.OnSensorChanged;\n" 55 | + "\n" 56 | + "public class Test extends Activity {\n" 57 | + " @OnSensorChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 58 | + " void testMagneticFieldSensorChanged(SensorEvent event, int extra) {}\n" 59 | + "}\n"; 60 | 61 | String error = 62 | "@OnSensorChanged methods can only have 1 parameter(s). (Test.testMagneticFieldSensorChanged)"; 63 | 64 | shouldFailWithError(source, error); 65 | } 66 | 67 | @Test 68 | public void bindOnSensorChangedSucceeds() { 69 | String source = "package test;\n" 70 | + "\n" 71 | + "import android.app.Activity;\n" 72 | + "import android.hardware.Sensor;\n" 73 | + "import android.hardware.SensorEvent;\n" 74 | + "import com.dvoiss.sensorannotations.OnSensorChanged;\n" 75 | + "\n" 76 | + "public class Test extends Activity {\n" 77 | + " @OnSensorChanged(Sensor.TYPE_MAGNETIC_FIELD)\n" 78 | + " void testMagneticFieldSensorChanged(SensorEvent event) {}\n" 79 | + "}\n"; 80 | 81 | String bindingSource = "// This class is generated code from Sensor Lib. Do not modify!\n" 82 | + "package test;\n" 83 | + "\n" 84 | + "import static android.content.Context.SENSOR_SERVICE;\n" 85 | + "\n" 86 | + "import android.content.Context;\n" 87 | + "import android.hardware.Sensor;\n" 88 | + "import android.hardware.SensorEventListener;\n" 89 | + "import android.hardware.SensorManager;\n" 90 | + "import com.dvoiss.sensorannotations.internal.EventListenerWrapper;\n" 91 | + "import com.dvoiss.sensorannotations.internal.SensorBinder;\n" 92 | + "import com.dvoiss.sensorannotations.internal.SensorEventListenerWrapper;\n" 93 | + "import java.lang.Override;\n" 94 | + "import java.util.ArrayList;\n" 95 | + "import java.util.List;\n" 96 | + "\n" 97 | + "final class Test$$SensorBinder implements SensorBinder {\n" 98 | + " private final SensorManager sensorManager;\n" 99 | + "\n" 100 | + " private final List listeners;\n" 101 | + "\n" 102 | + " public Test$$SensorBinder(Context context, final Test target) {\n" 103 | + " this.sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);\n" 104 | + " this.listeners = new ArrayList();\n" 105 | + " this.listeners.add(new SensorEventListenerWrapper(2, 3, new SensorEventListener() {\n" 106 | + " @java.lang.Override\n" 107 | + " public void onSensorChanged(android.hardware.SensorEvent event) {\n" 108 | + " target.testMagneticFieldSensorChanged(event);\n" 109 | + " }\n" 110 | + " @java.lang.Override\n" 111 | + " public void onAccuracyChanged(android.hardware.Sensor sensor, int accuracy) {\n" 112 | + " }\n" 113 | + " }));\n" 114 | + " }\n" 115 | + "\n" 116 | + " @Override\n" 117 | + " public void bind(final Test target) {\n" 118 | + " int sensorType;\n" 119 | + " Sensor sensor;\n" 120 | + " for (EventListenerWrapper wrapper : listeners) {\n" 121 | + " sensorType = wrapper.getSensorType();\n" 122 | + " sensor = wrapper.getSensor(sensorManager);\n" 123 | + " wrapper.registerListener(sensorManager);\n" 124 | + " }\n" 125 | + " }\n" 126 | + "\n" 127 | + " @Override\n" 128 | + " public void unbind() {\n" 129 | + " if (this.sensorManager != null) {\n" 130 | + " for (EventListenerWrapper wrapper : listeners) {\n" 131 | + " wrapper.unregisterListener(sensorManager);\n" 132 | + " }\n" 133 | + " }\n" 134 | + " }\n" 135 | + "}\n"; 136 | 137 | shouldGenerateBindingSource(source, bindingSource); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/BindOnSensorNotAvailableTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.dvoiss.sensorannotations.TestUtils.shouldFailWithError; 6 | import static com.dvoiss.sensorannotations.TestUtils.shouldGenerateBindingSource; 7 | 8 | public class BindOnSensorNotAvailableTest { 9 | 10 | @Test 11 | public void bindOnSensorNotAvailableWithInvalidAnnotationParameter() { 12 | String source = "package test;\n" 13 | + "\n" 14 | + "import android.app.Activity;\n" 15 | + "import android.hardware.Sensor;\n" 16 | + "import com.dvoiss.sensorannotations.OnSensorNotAvailable;\n" 17 | + "\n" 18 | + "public class Test extends Activity {\n" 19 | + " @OnSensorNotAvailable\n" 20 | + " void testMagneticFieldSensorNotAvailable() {}\n" 21 | + "}\n"; 22 | 23 | String error = 24 | "No sensor type specified in @OnSensorNotAvailable for method testMagneticFieldSensorNotAvailable. Set a sensor type such as Sensor.TYPE_ACCELEROMETER."; 25 | 26 | shouldFailWithError(source, error); 27 | } 28 | 29 | @Test 30 | public void bindOnSensorNotAvailableFailsWithInvalidNumberOfMethodParameter() { 31 | String source = "package test;\n" 32 | + "\n" 33 | + "import android.app.Activity;\n" 34 | + "import android.hardware.Sensor;\n" 35 | + "import com.dvoiss.sensorannotations.OnSensorNotAvailable;\n" 36 | + "\n" 37 | + "public class Test extends Activity {\n" 38 | + " @OnSensorNotAvailable(Sensor.TYPE_MAGNETIC_FIELD)\n" 39 | + " void testMagneticFieldSensorNotAvailable(int extra) {}\n" 40 | + "}\n"; 41 | 42 | String error = 43 | "@OnSensorNotAvailable methods can only have 0 parameter(s). (Test.testMagneticFieldSensorNotAvailable)"; 44 | 45 | shouldFailWithError(source, error); 46 | } 47 | 48 | @Test 49 | public void bindOnSensorNotAvailableSucceeds() { 50 | String source = "package test;\n" 51 | + "\n" 52 | + "import android.app.Activity;\n" 53 | + "import android.hardware.Sensor;\n" 54 | + "import com.dvoiss.sensorannotations.OnSensorNotAvailable;\n" 55 | + "\n" 56 | + "public class Test extends Activity {\n" 57 | + " @OnSensorNotAvailable(Sensor.TYPE_MAGNETIC_FIELD)\n" 58 | + " void testMagneticFieldSensorNotAvailable() {}\n" 59 | + "}"; 60 | 61 | String bindingSource = "// This class is generated code from Sensor Lib. Do not modify!\n" 62 | + "package test;\n" 63 | + "\n" 64 | + "import static android.content.Context.SENSOR_SERVICE;\n" 65 | + "\n" 66 | + "import android.content.Context;\n" 67 | + "import android.hardware.Sensor;\n" 68 | + "import android.hardware.SensorManager;\n" 69 | + "import com.dvoiss.sensorannotations.internal.EventListenerWrapper;\n" 70 | + "import com.dvoiss.sensorannotations.internal.SensorBinder;\n" 71 | + "import java.lang.Override;\n" 72 | + "import java.util.ArrayList;\n" 73 | + "import java.util.List;\n" 74 | + "\n" 75 | + "final class Test$$SensorBinder implements SensorBinder {\n" 76 | + " private final SensorManager sensorManager;\n" 77 | + "\n" 78 | + " private final List listeners;\n" 79 | + "\n" 80 | + " public Test$$SensorBinder(Context context, final Test target) {\n" 81 | + " this.sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);\n" 82 | + " this.listeners = new ArrayList();\n" 83 | + " }\n" 84 | + "\n" 85 | + " @Override\n" 86 | + " public void bind(final Test target) {\n" 87 | + " int sensorType;\n" 88 | + " Sensor sensor;\n" 89 | + " for (EventListenerWrapper wrapper : listeners) {\n" 90 | + " sensorType = wrapper.getSensorType();\n" 91 | + " sensor = wrapper.getSensor(sensorManager);\n" 92 | + " if (sensor == null) {\n" 93 | + " if (sensorType == 2) {\n" 94 | + " target.testMagneticFieldSensorNotAvailable();\n" 95 | + " }\n" 96 | + " continue;\n" 97 | + " }\n" 98 | + " wrapper.registerListener(sensorManager);\n" 99 | + " }\n" 100 | + " }\n" 101 | + "\n" 102 | + " @Override\n" 103 | + " public void unbind() {\n" 104 | + " if (this.sensorManager != null) {\n" 105 | + " for (EventListenerWrapper wrapper : listeners) {\n" 106 | + " wrapper.unregisterListener(sensorManager);\n" 107 | + " }\n" 108 | + " }\n" 109 | + " }\n" 110 | + "}\n"; 111 | 112 | shouldGenerateBindingSource(source, bindingSource); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/BindOnTriggerTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import org.junit.Test; 4 | 5 | import static com.dvoiss.sensorannotations.TestUtils.shouldFailWithError; 6 | import static com.dvoiss.sensorannotations.TestUtils.shouldGenerateBindingSource; 7 | 8 | public class BindOnTriggerTest { 9 | 10 | public void bindOnTriggerFailsWithInvalidMethodParameter() { 11 | String source = "package test;\n" 12 | + "\n" 13 | + "import android.app.Activity;\n" 14 | + "import com.dvoiss.sensorannotations.OnTrigger;\n" 15 | + "\n" 16 | + "public class Test extends Activity {\n" 17 | + " @OnTrigger\n" 18 | + " public void testSignificantMotionTrigger(Object wrongType) {}\n" 19 | + "}\n"; 20 | 21 | String error = 22 | "Method parameters are not valid for @OnTrigger annotated method. Expected parameters of type(s): android.hardware.TriggerEvent. (Test.testSignificantMotionTrigger)"; 23 | 24 | shouldFailWithError(source, error); 25 | } 26 | 27 | @Test 28 | public void bindOnTriggerFailsWithInvalidNumberOfMethodParameter() { 29 | String source = "package test;\n" 30 | + "\n" 31 | + "import android.app.Activity;\n" 32 | + "import android.hardware.TriggerEvent;\n" 33 | + "import com.dvoiss.sensorannotations.OnTrigger;\n" 34 | + "\n" 35 | + "public class Test extends Activity {\n" 36 | + " @OnTrigger\n" 37 | + " public void testSignificantMotionTrigger(TriggerEvent event, int extra) {}\n" 38 | + "}\n"; 39 | 40 | String error = 41 | "@OnTrigger methods can only have 1 parameter(s). (Test.testSignificantMotionTrigger)"; 42 | 43 | shouldFailWithError(source, error); 44 | } 45 | 46 | @Test 47 | public void bindOnTriggerSucceeds() { 48 | String source = "package test;\n" 49 | + "\n" 50 | + "import android.app.Activity;\n" 51 | + "import android.hardware.TriggerEvent;\n" 52 | + "import com.dvoiss.sensorannotations.OnTrigger;\n" 53 | + "\n" 54 | + "public class Test extends Activity {\n" 55 | + " @OnTrigger\n" 56 | + " public void testSignificantMotionTrigger(TriggerEvent event) {}\n" 57 | + "}\n"; 58 | 59 | String bindingSource = "// This class is generated code from Sensor Lib. Do not modify!\n" 60 | + "package test;\n" 61 | + "\n" 62 | + "import static android.content.Context.SENSOR_SERVICE;\n" 63 | + "\n" 64 | + "import android.content.Context;\n" 65 | + "import android.hardware.Sensor;\n" 66 | + "import android.hardware.SensorManager;\n" 67 | + "import android.hardware.TriggerEventListener;\n" 68 | + "import com.dvoiss.sensorannotations.internal.EventListenerWrapper;\n" 69 | + "import com.dvoiss.sensorannotations.internal.SensorBinder;\n" 70 | + "import com.dvoiss.sensorannotations.internal.TriggerEventListenerWrapper;\n" 71 | + "import java.lang.Override;\n" 72 | + "import java.util.ArrayList;\n" 73 | + "import java.util.List;\n" 74 | + "\n" 75 | + "final class Test$$SensorBinder implements SensorBinder {\n" 76 | + " private final SensorManager sensorManager;\n" 77 | + "\n" 78 | + " private final List listeners;\n" 79 | + "\n" 80 | + " public Test$$SensorBinder(Context context, final Test target) {\n" 81 | + " this.sensorManager = (SensorManager) context.getSystemService(SENSOR_SERVICE);\n" 82 | + " this.listeners = new ArrayList();\n" 83 | + " this.listeners.add(new TriggerEventListenerWrapper(new TriggerEventListener() {\n" 84 | + " @java.lang.Override\n" 85 | + " public void onTrigger(android.hardware.TriggerEvent event) {\n" 86 | + " target.testSignificantMotionTrigger(event);\n" 87 | + " }\n" 88 | + " }));\n" 89 | + " }\n" 90 | + "\n" 91 | + " @Override\n" 92 | + " public void bind(final Test target) {\n" 93 | + " int sensorType;\n" 94 | + " Sensor sensor;\n" 95 | + " for (EventListenerWrapper wrapper : listeners) {\n" 96 | + " sensorType = wrapper.getSensorType();\n" 97 | + " sensor = wrapper.getSensor(sensorManager);\n" 98 | + " wrapper.registerListener(sensorManager);\n" 99 | + " }\n" 100 | + " }\n" 101 | + "\n" 102 | + " @Override\n" 103 | + " public void unbind() {\n" 104 | + " if (this.sensorManager != null) {\n" 105 | + " for (EventListenerWrapper wrapper : listeners) {\n" 106 | + " wrapper.unregisterListener(sensorManager);\n" 107 | + " }\n" 108 | + " }\n" 109 | + " }\n" 110 | + "}\n"; 111 | 112 | shouldGenerateBindingSource(source, bindingSource); 113 | } 114 | } 115 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/SensorAnnotationsTest.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import android.content.Context; 4 | import com.dvoiss.sensorannotations.internal.SensorBinder; 5 | import org.junit.Before; 6 | import org.junit.Test; 7 | import org.junit.runner.RunWith; 8 | import org.robolectric.RobolectricTestRunner; 9 | import org.robolectric.annotation.Config; 10 | import org.robolectric.shadows.ShadowApplication; 11 | import org.robolectric.shadows.ShadowLog; 12 | 13 | import static com.dvoiss.sensorannotations.SensorAnnotations.NO_OP_VIEW_BINDER; 14 | import static com.google.common.truth.Truth.assertThat; 15 | 16 | @RunWith(RobolectricTestRunner.class) 17 | @Config(constants = BuildConfig.class, sdk = 21) 18 | public class SensorAnnotationsTest { 19 | private final Context mContext = ShadowApplication.getInstance().getApplicationContext(); 20 | 21 | @Before 22 | public void resetBinderCache() { 23 | ShadowLog.stream = System.out; 24 | SensorAnnotations.BINDER_CACHE.clear(); 25 | } 26 | 27 | @Test(expected = RuntimeException.class) 28 | public void validTargetAndNullContextParameterThrowsException() { 29 | class Example {} 30 | SensorAnnotations.bind(new Example(), null); 31 | } 32 | 33 | @Test(expected = RuntimeException.class) 34 | public void nullContextParameterThrowsException() { 35 | SensorAnnotations.bind(null); 36 | } 37 | 38 | @Test(expected = RuntimeException.class) 39 | public void nullTargetParameterThrowsException() { 40 | SensorAnnotations.bind(null, mContext); 41 | } 42 | 43 | @Test 44 | public void bindingFrameworkPackagesAreNotCached() { 45 | SensorAnnotations.bind(mContext); 46 | assertThat(SensorAnnotations.BINDER_CACHE).isEmpty(); 47 | SensorAnnotations.bind(new Object(), mContext); 48 | assertThat(SensorAnnotations.BINDER_CACHE).isEmpty(); 49 | } 50 | 51 | @Test 52 | public void findsNoOpViewBinderWithInvalidConstructor() { 53 | class Example {} 54 | Example example = new Example(); 55 | SensorAnnotations.bind(example, mContext); 56 | SensorBinder sensorBinder = SensorAnnotations.BINDER_CACHE.get(example.getClass()); 57 | assertThat(sensorBinder).isSameAs(NO_OP_VIEW_BINDER); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /sensorannotations-lib/src/test/java/com/dvoiss/sensorannotations/TestUtils.java: -------------------------------------------------------------------------------- 1 | package com.dvoiss.sensorannotations; 2 | 3 | import com.google.testing.compile.CompileTester; 4 | 5 | import static com.google.common.truth.Truth.assertAbout; 6 | import static com.google.testing.compile.JavaFileObjects.forSourceString; 7 | import static com.google.testing.compile.JavaSourceSubjectFactory.javaSource; 8 | 9 | class TestUtils { 10 | static void shouldFailWithError(String source, String error) { 11 | getBaseCompileTester(source).failsToCompile().withErrorContaining(error); 12 | } 13 | 14 | static void shouldGenerateBindingSource(String source, String bindingSource) { 15 | getBaseCompileTester(source).compilesWithoutError() 16 | .and() 17 | .generatesSources(forSourceString("test/Test$$SensorBinder", bindingSource)); 18 | } 19 | 20 | private static CompileTester getBaseCompileTester(String source) { 21 | return assertAbout(javaSource()).that(forSourceString("test.Test", source)) 22 | .withCompilerOptions("-Xlint:-processing") 23 | .processedWith(new SensorAnnotationsProcessor()); 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include ':app', ':sensorannotations-annotations', ':sensorannotations-compiler', ':sensorannotations-lib' 2 | --------------------------------------------------------------------------------