| 1 | """Implementation Vibrator for Android.""" |
| 2 | |
| 3 | from jnius import autoclass, cast |
| 4 | from plyer.facades import Vibrator |
| 5 | from plyer.platforms.android import activity |
| 6 | from plyer.platforms.android import SDK_INT |
| 7 | |
| 8 | Context = autoclass("android.content.Context") |
| 9 | vibrator_service = activity.getSystemService(Context.VIBRATOR_SERVICE) |
| 10 | vibrator = cast("android.os.Vibrator", vibrator_service) |
| 11 | if SDK_INT >= 26: |
| 12 | VibrationEffect = autoclass("android.os.VibrationEffect") |
| 13 | |
| 14 | |
| 15 | class AndroidVibrator(Vibrator): |
| 16 | """Android Vibrator class. |
| 17 | |
| 18 | Supported features: |
| 19 | * vibrate for some period of time. |
| 20 | * vibrate from given pattern. |
| 21 | * cancel vibration. |
| 22 | * check whether Vibrator exists. |
| 23 | """ |
| 24 | |
| 25 | def _vibrate(self, time=None, **kwargs): |
| 26 | if vibrator: |
| 27 | if SDK_INT >= 26: |
| 28 | vibrator.vibrate( |
| 29 | VibrationEffect.createOneShot( |
| 30 | int(1000 * time), VibrationEffect.DEFAULT_AMPLITUDE |
| 31 | ) |
| 32 | ) |
| 33 | else: |
| 34 | vibrator.vibrate(int(1000 * time)) |
| 35 | |
| 36 | def _pattern(self, pattern=None, repeat=None, **kwargs): |
| 37 | pattern = [int(1000 * time) for time in pattern] |
| 38 | |
| 39 | if vibrator: |
| 40 | if SDK_INT >= 26: |
| 41 | vibrator.vibrate( |
| 42 | VibrationEffect.createWaveform(pattern, repeat) |
| 43 | ) |
| 44 | else: |
| 45 | vibrator.vibrate(pattern, repeat) |
| 46 | |
| 47 | def _exists(self, **kwargs): |
| 48 | if SDK_INT >= 11: |
| 49 | return vibrator.hasVibrator() |
| 50 | elif vibrator_service is None: |
| 51 | raise NotImplementedError() |
| 52 | return True |
| 53 | |
| 54 | def _cancel(self, **kwargs): |
| 55 | vibrator.cancel() |
| 56 | |
| 57 | |
| 58 | def instance(): |
| 59 | """Returns Vibrator with android features. |
| 60 | |
| 61 | :return: instance of class AndroidVibrator |
| 62 | """ |
| 63 | return AndroidVibrator() |