react-native-alarmageddon 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 react-native-alarmageddon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,292 @@
1
+ # react-native-alarmageddon
2
+
3
+ 🔔 **Native exact alarm scheduling for React Native with sound, snooze, and boot persistence.**
4
+
5
+ A powerful React Native library for scheduling alarms that:
6
+ - Use Android's `AlarmManager.setAlarmClock()` for exact timing
7
+ - Play alarm sounds at full volume
8
+ - Show full-screen notifications that wake the device
9
+ - Support snooze functionality
10
+ - Persist across device reboots
11
+ - Work even when the app is killed
12
+
13
+ ## Features
14
+
15
+ - ✅ **Exact Alarms**: Uses `setAlarmClock()` for precise alarm timing
16
+ - ✅ **Full-Screen Intent**: Wakes device and shows alarm UI
17
+ - ✅ **Sound & Vibration**: Plays alarm sound at max volume with vibration
18
+ - ✅ **Snooze Support**: Built-in snooze functionality
19
+ - ✅ **Boot Persistence**: Alarms automatically reschedule after reboot
20
+ - ✅ **Background Support**: Works when app is killed
21
+ - ✅ **Auto-Stop**: Configurable auto-stop timer
22
+ - ✅ **Event Emitter**: Listen for alarm state changes in JavaScript
23
+
24
+ ## Platform Support
25
+
26
+ | Platform | Status |
27
+ |----------|--------|
28
+ | Android | ✅ Full support |
29
+ | iOS | ⚠️ Stub only (uses NOT_IMPLEMENTED errors) |
30
+
31
+ > **Note**: iOS requires a different approach using `UNUserNotificationCenter`. Full iOS support is planned for a future release.
32
+
33
+ ## Installation
34
+
35
+ ```bash
36
+ npm install react-native-alarmageddon
37
+ # or
38
+ yarn add react-native-alarmageddon
39
+ ```
40
+
41
+ ### Android Setup
42
+
43
+ The library uses autolinking, so no manual linking is required for React Native 0.60+.
44
+
45
+ #### Permissions
46
+
47
+ The required permissions are automatically merged into your `AndroidManifest.xml`:
48
+
49
+ ```xml
50
+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
51
+ <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
52
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
53
+ <uses-permission android:name="android.permission.VIBRATE" />
54
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
55
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
56
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
57
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
58
+ ```
59
+
60
+ #### Android 12+ (API 31+) Requirements
61
+
62
+ Starting with Android 12, apps must request the `SCHEDULE_EXACT_ALARM` permission at runtime. This library handles this automatically, but you should call `ensurePermissions()` before scheduling alarms.
63
+
64
+ ## Usage
65
+
66
+ ### Basic Example
67
+
68
+ ```typescript
69
+ import RNAlarmModule from 'react-native-alarmageddon';
70
+
71
+ // Request permissions first
72
+ async function setupAlarms() {
73
+ const granted = await RNAlarmModule.ensurePermissions();
74
+ if (!granted) {
75
+ console.warn('Alarm permissions not granted');
76
+ return;
77
+ }
78
+
79
+ // Schedule an alarm for 5 minutes from now
80
+ const triggerTime = new Date(Date.now() + 5 * 60 * 1000);
81
+
82
+ await RNAlarmModule.scheduleAlarm({
83
+ id: 'wake-up-alarm',
84
+ datetimeISO: triggerTime.toISOString(),
85
+ title: 'Wake Up!',
86
+ body: 'Time to start your day',
87
+ snoozeMinutes: 10,
88
+ autoStopSeconds: 120,
89
+ vibrate: true,
90
+ });
91
+ }
92
+ ```
93
+
94
+ ### Listening for Alarm Events
95
+
96
+ ```typescript
97
+ import { useEffect, useState } from 'react';
98
+ import RNAlarmModule from 'react-native-alarmageddon';
99
+
100
+ function AlarmScreen() {
101
+ const [activeAlarmId, setActiveAlarmId] = useState<string | null>(null);
102
+
103
+ useEffect(() => {
104
+ // Check if an alarm is already playing when app opens
105
+ RNAlarmModule.getCurrentAlarmPlaying().then((info) => {
106
+ if (info) {
107
+ setActiveAlarmId(info.activeAlarmId);
108
+ }
109
+ });
110
+
111
+ // Subscribe to alarm state changes
112
+ const unsubscribe = RNAlarmModule.onAlarmStateChange((alarmId) => {
113
+ setActiveAlarmId(alarmId);
114
+ });
115
+
116
+ return unsubscribe;
117
+ }, []);
118
+
119
+ const handleStop = async () => {
120
+ if (activeAlarmId) {
121
+ await RNAlarmModule.stopCurrentAlarm(activeAlarmId);
122
+ }
123
+ };
124
+
125
+ const handleSnooze = async () => {
126
+ if (activeAlarmId) {
127
+ await RNAlarmModule.snoozeCurrentAlarm(activeAlarmId, 10);
128
+ }
129
+ };
130
+
131
+ if (!activeAlarmId) {
132
+ return null;
133
+ }
134
+
135
+ return (
136
+ <View>
137
+ <Text>Alarm is ringing!</Text>
138
+ <Button title="Stop" onPress={handleStop} />
139
+ <Button title="Snooze 10 min" onPress={handleSnooze} />
140
+ </View>
141
+ );
142
+ }
143
+ ```
144
+
145
+ ### Managing Alarms
146
+
147
+ ```typescript
148
+ import RNAlarmModule from 'react-native-alarmageddon';
149
+
150
+ // List all scheduled alarms
151
+ const alarms = await RNAlarmModule.listAlarms();
152
+ console.log('Scheduled alarms:', alarms);
153
+
154
+ // Cancel a specific alarm
155
+ await RNAlarmModule.cancelAlarm('wake-up-alarm');
156
+
157
+ // Snooze an alarm (reschedules it)
158
+ await RNAlarmModule.snoozeAlarm('wake-up-alarm', 5);
159
+ ```
160
+
161
+ ## API Reference
162
+
163
+ ### Types
164
+
165
+ ```typescript
166
+ type AlarmParams = {
167
+ id: string; // Unique identifier
168
+ datetimeISO: string; // ISO 8601 datetime string
169
+ title?: string; // Notification title (default: "Alarm")
170
+ body?: string; // Notification body (default: "")
171
+ soundUri?: string; // Custom sound URI (uses system default if omitted)
172
+ vibrate?: boolean; // Enable vibration (default: true)
173
+ snoozeMinutes?: number; // Snooze duration (default: 5)
174
+ autoStopSeconds?: number; // Auto-stop after N seconds (default: 60)
175
+ };
176
+
177
+ type StoredAlarm = {
178
+ id: string;
179
+ datetimeISO: string;
180
+ title: string;
181
+ body: string;
182
+ vibrate: boolean;
183
+ snoozeMinutes: number;
184
+ autoStopSeconds: number;
185
+ };
186
+
187
+ type PermissionResult = {
188
+ granted: boolean;
189
+ exactAlarmGranted?: boolean;
190
+ };
191
+
192
+ type ActiveAlarmInfo = {
193
+ activeAlarmId: string;
194
+ } | null;
195
+ ```
196
+
197
+ ### Methods
198
+
199
+ #### Permissions
200
+
201
+ | Method | Description |
202
+ |--------|-------------|
203
+ | `ensurePermissions()` | Request all required permissions. Returns `true` if granted. |
204
+ | `requestNotificationPermission()` | Request notification permission (Android 13+). |
205
+ | `requestExactAlarmPermission()` | Request exact alarm permission (Android 12+). Opens settings if needed. |
206
+ | `checkExactAlarmPermission()` | Check if exact alarm permission is granted. |
207
+ | `openExactAlarmSettings()` | Open system settings for exact alarm permission. |
208
+
209
+ #### Alarm Management
210
+
211
+ | Method | Description |
212
+ |--------|-------------|
213
+ | `scheduleAlarm(params)` | Schedule a new alarm. |
214
+ | `cancelAlarm(id)` | Cancel a scheduled alarm. |
215
+ | `listAlarms()` | Get all scheduled alarms. |
216
+ | `snoozeAlarm(id, minutes)` | Reschedule an alarm for N minutes from now. |
217
+
218
+ #### Active Alarm Control
219
+
220
+ | Method | Description |
221
+ |--------|-------------|
222
+ | `stopCurrentAlarm(id)` | Stop the currently playing alarm. |
223
+ | `snoozeCurrentAlarm(id, minutes)` | Stop and snooze the current alarm. |
224
+ | `getCurrentAlarmPlaying()` | Get info about the currently playing alarm. |
225
+
226
+ #### Events
227
+
228
+ | Method | Description |
229
+ |--------|-------------|
230
+ | `onAlarmStateChange(callback)` | Subscribe to alarm state changes. Returns unsubscribe function. |
231
+ | `addEventListener(event, callback)` | Add event listener. Returns subscription for removal. |
232
+
233
+ ## How It Works
234
+
235
+ ### Android Architecture
236
+
237
+ 1. **AlarmModule**: React Native bridge that schedules alarms via `AlarmManager`
238
+ 2. **AlarmReceiver**: `BroadcastReceiver` that triggers when alarm fires
239
+ 3. **AlarmService**: Foreground service that plays sound and shows notification
240
+ 4. **AlarmActivity**: Transparent activity that wakes the screen
241
+ 5. **BootReceiver**: Reschedules alarms after device reboot or time changes
242
+
243
+ ### Alarm Scheduling
244
+
245
+ The library uses `AlarmManager.setAlarmClock()` which:
246
+ - Is the most reliable way to schedule exact alarms on Android
247
+ - Shows an alarm icon in the status bar
248
+ - Can wake the device from Doze mode
249
+ - Survives app kills
250
+
251
+ ### Boot Persistence
252
+
253
+ The `BootReceiver` listens for:
254
+ - `BOOT_COMPLETED`: Device finished booting
255
+ - `LOCKED_BOOT_COMPLETED`: Direct boot completed
256
+ - `TIME_SET`: User changed system time
257
+ - `TIMEZONE_CHANGED`: Timezone changed
258
+ - `MY_PACKAGE_REPLACED`: App was updated
259
+
260
+ When any of these events occur, all future alarms are rescheduled.
261
+
262
+ ## Troubleshooting
263
+
264
+ ### Alarm not firing
265
+
266
+ 1. **Check permissions**: Ensure `SCHEDULE_EXACT_ALARM` is granted on Android 12+
267
+ 2. **Battery optimization**: Exclude your app from battery optimization
268
+ 3. **Verify time**: Ensure the scheduled time is in the future
269
+
270
+ ### Sound not playing
271
+
272
+ 1. **Check volume**: Ensure alarm volume is not muted
273
+ 2. **Custom sound**: Verify the sound URI is valid and accessible
274
+
275
+ ### Alarm not showing on lock screen
276
+
277
+ 1. **Notification permission**: Ensure `POST_NOTIFICATIONS` is granted on Android 13+
278
+ 2. **Lock screen settings**: Check device notification settings for lock screen visibility
279
+
280
+ ### After reboot, alarms are lost
281
+
282
+ This shouldn't happen with the library, but verify:
283
+ 1. The `BootReceiver` is properly declared in the manifest
284
+ 2. Your app hasn't been force-stopped
285
+
286
+ ## Contributing
287
+
288
+ Contributions are welcome! Please feel free to submit a Pull Request.
289
+
290
+ ## License
291
+
292
+ MIT License - see [LICENSE](LICENSE) for details.
@@ -0,0 +1,69 @@
1
+ def safeExtGet(prop, fallback) {
2
+ rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback
3
+ }
4
+
5
+ buildscript {
6
+ def kotlin_version = safeExtGet('kotlinVersion', '1.9.22')
7
+ repositories {
8
+ google()
9
+ mavenCentral()
10
+ }
11
+ dependencies {
12
+ classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
13
+ }
14
+ }
15
+
16
+ apply plugin: 'com.android.library'
17
+ apply plugin: 'kotlin-android'
18
+
19
+ android {
20
+ namespace 'com.rnalarmmodule'
21
+
22
+ compileSdkVersion safeExtGet('compileSdkVersion', 34)
23
+
24
+ defaultConfig {
25
+ minSdkVersion safeExtGet('minSdkVersion', 21)
26
+ targetSdkVersion safeExtGet('targetSdkVersion', 34)
27
+ }
28
+
29
+ sourceSets {
30
+ main {
31
+ java.srcDirs = ['src/main/java']
32
+ res.srcDirs = ['src/main/res']
33
+ }
34
+ }
35
+
36
+ compileOptions {
37
+ sourceCompatibility JavaVersion.VERSION_17
38
+ targetCompatibility JavaVersion.VERSION_17
39
+ }
40
+
41
+ kotlinOptions {
42
+ jvmTarget = '17'
43
+ }
44
+
45
+ lintOptions {
46
+ abortOnError false
47
+ }
48
+ }
49
+
50
+ repositories {
51
+ google()
52
+ mavenCentral()
53
+ }
54
+
55
+ dependencies {
56
+ def kotlin_version = safeExtGet('kotlinVersion', '1.9.22')
57
+
58
+ implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
59
+
60
+ // React Native dependency - works with both old and new architecture
61
+ if (rootProject.hasProperty('reactNativeVersion')) {
62
+ implementation "com.facebook.react:react-android:${rootProject.reactNativeVersion}"
63
+ } else {
64
+ implementation 'com.facebook.react:react-android:+'
65
+ }
66
+
67
+ implementation 'androidx.core:core-ktx:1.12.0'
68
+ implementation 'androidx.appcompat:appcompat:1.6.1'
69
+ }
@@ -0,0 +1,13 @@
1
+ # React Native Alarmageddon Android Build Configuration
2
+
3
+ # Version of Kotlin to use
4
+ AlarmModule_kotlinVersion=1.9.22
5
+
6
+ # Android SDK versions
7
+ AlarmModule_compileSdkVersion=34
8
+ AlarmModule_minSdkVersion=21
9
+ AlarmModule_targetSdkVersion=34
10
+
11
+ # Build configuration
12
+ android.useAndroidX=true
13
+ android.enableJetifier=true
@@ -0,0 +1,55 @@
1
+ <manifest xmlns:android="http://schemas.android.com/apk/res/android"
2
+ package="com.rnalarmmodule">
3
+
4
+ <!-- Permissions that will merge with host app -->
5
+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" />
6
+ <uses-permission android:name="android.permission.USE_EXACT_ALARM" />
7
+ <uses-permission android:name="android.permission.WAKE_LOCK" />
8
+ <uses-permission android:name="android.permission.VIBRATE" />
9
+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
10
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
11
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
12
+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE_MEDIA_PLAYBACK" />
13
+
14
+ <application>
15
+ <receiver
16
+ android:name=".AlarmReceiver"
17
+ android:exported="false">
18
+ <intent-filter>
19
+ <action android:name="com.rnalarmmodule.ALARM_TRIGGER" />
20
+ <action android:name="com.rnalarmmodule.ALARM_STOP" />
21
+ <action android:name="com.rnalarmmodule.ALARM_SNOOZE" />
22
+ </intent-filter>
23
+ </receiver>
24
+
25
+ <receiver
26
+ android:name=".BootReceiver"
27
+ android:exported="true"
28
+ android:directBootAware="true">
29
+ <intent-filter>
30
+ <action android:name="android.intent.action.BOOT_COMPLETED" />
31
+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />
32
+ <action android:name="android.intent.action.TIME_SET" />
33
+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />
34
+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />
35
+ </intent-filter>
36
+ </receiver>
37
+
38
+ <activity
39
+ android:name=".AlarmActivity"
40
+ android:exported="false"
41
+ android:showOnLockScreen="true"
42
+ android:turnScreenOn="true"
43
+ android:showWhenLocked="true"
44
+ android:theme="@android:style/Theme.NoDisplay"
45
+ android:noHistory="true"
46
+ android:excludeFromRecents="true"
47
+ android:launchMode="singleInstance"
48
+ android:taskAffinity="" />
49
+
50
+ <service
51
+ android:name=".AlarmService"
52
+ android:exported="false"
53
+ android:foregroundServiceType="mediaPlayback" />
54
+ </application>
55
+ </manifest>
@@ -0,0 +1,79 @@
1
+ package com.rnalarmmodule
2
+
3
+ import android.app.Activity
4
+ import android.app.KeyguardManager
5
+ import android.content.Context
6
+ import android.os.Build
7
+ import android.os.Bundle
8
+ import android.util.Log
9
+ import android.view.WindowManager
10
+
11
+ class AlarmActivity : Activity() {
12
+
13
+ companion object {
14
+ private const val TAG = "AlarmActivity"
15
+ }
16
+
17
+ override fun onCreate(savedInstanceState: Bundle?) {
18
+ super.onCreate(savedInstanceState)
19
+
20
+ Log.d(TAG, "onCreate - waking up screen for alarm")
21
+
22
+ // Enable showing on lock screen and turning screen on
23
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
24
+ setShowWhenLocked(true)
25
+ setTurnScreenOn(true)
26
+
27
+ val keyguardManager = getSystemService(Context.KEYGUARD_SERVICE) as KeyguardManager
28
+ keyguardManager.requestDismissKeyguard(this, null)
29
+ } else {
30
+ @Suppress("DEPRECATION")
31
+ window.addFlags(
32
+ WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
33
+ WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD or
34
+ WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON or
35
+ WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
36
+ )
37
+ }
38
+
39
+ // Keep screen on while alarm is active
40
+ window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
41
+
42
+ // Get alarm details from intent
43
+ val alarmId = intent.getStringExtra("alarmId")
44
+ val title = intent.getStringExtra("title") ?: "Alarm"
45
+ val body = intent.getStringExtra("body") ?: ""
46
+ val snoozeMinutes = intent.getIntExtra("snoozeMinutes", 5)
47
+
48
+ Log.d(TAG, "Alarm triggered: id=$alarmId, title=$title")
49
+
50
+ // Try to launch the main app
51
+ launchMainApp(alarmId)
52
+ }
53
+
54
+ private fun launchMainApp(alarmId: String?) {
55
+ try {
56
+ val launchIntent = packageManager.getLaunchIntentForPackage(packageName)
57
+ if (launchIntent != null) {
58
+ launchIntent.addFlags(
59
+ android.content.Intent.FLAG_ACTIVITY_NEW_TASK or
60
+ android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP or
61
+ android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP
62
+ )
63
+ launchIntent.putExtra("alarmId", alarmId)
64
+ launchIntent.putExtra("fromAlarm", true)
65
+ startActivity(launchIntent)
66
+ }
67
+ } catch (e: Exception) {
68
+ Log.e(TAG, "Failed to launch main app: ${e.message}", e)
69
+ }
70
+
71
+ // Finish this transparent activity
72
+ finish()
73
+ }
74
+
75
+ override fun onDestroy() {
76
+ super.onDestroy()
77
+ Log.d(TAG, "onDestroy")
78
+ }
79
+ }