init
This commit is contained in:
@@ -0,0 +1,228 @@
|
||||
package com.dcntrlized.alarm
|
||||
|
||||
import android.app.NotificationChannel
|
||||
import android.app.NotificationManager
|
||||
import android.content.Context
|
||||
import android.media.AudioAttributes
|
||||
import android.media.AudioManager
|
||||
import android.media.MediaPlayer
|
||||
import android.media.RingtoneManager
|
||||
import android.os.Build
|
||||
import android.os.VibrationEffect
|
||||
import android.os.Vibrator
|
||||
import android.os.VibratorManager
|
||||
import android.util.Log
|
||||
|
||||
/**
|
||||
* Max-volume alarm playback.
|
||||
*
|
||||
* Escalation ladder, in order:
|
||||
* 1. `STREAM_ALARM` at `setVolume(1f)` — the only stream that ignores the
|
||||
* media volume and, on most devices, keeps ringing in silent mode;
|
||||
* 2. a `Vibrator` waveform alongside the audio, so a muted ringer still
|
||||
* reaches the user;
|
||||
* 3. (see [AlarmNotifier]) a high-priority notification with a "Raise your
|
||||
* volume" action when the OS refuses the alarm stream entirely.
|
||||
*
|
||||
* We never report success unless the alarm stream was actually raised, so the
|
||||
* UI can tell the truth about which rung of the ladder carried the alarm.
|
||||
*/
|
||||
object AlarmPlayer {
|
||||
private const val TAG = "AlarmPlayer"
|
||||
|
||||
private var player: MediaPlayer? = null
|
||||
private var vibrator: Vibrator? = null
|
||||
|
||||
/** Vibration pattern: wait 0, buzz 700, rest 400, repeated from index 1. */
|
||||
private val VIBRATION_PATTERN = longArrayOf(0L, 700L, 400L)
|
||||
|
||||
@Synchronized
|
||||
fun play(context: Context, alertId: String, autoStopSeconds: Int): Boolean {
|
||||
stop(context)
|
||||
val volumeRaised = raiseAlarmStream(context)
|
||||
|
||||
try {
|
||||
val uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM)
|
||||
?: RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE)
|
||||
val mp = MediaPlayer()
|
||||
mp.setAudioAttributes(
|
||||
AudioAttributes.Builder()
|
||||
.setUsage(AudioAttributes.USAGE_ALARM)
|
||||
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
|
||||
.build()
|
||||
)
|
||||
mp.setDataSource(context, uri)
|
||||
mp.isLooping = true
|
||||
mp.setVolume(1f, 1f)
|
||||
mp.prepare()
|
||||
mp.start()
|
||||
player = mp
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "alarm audio failed: ${e.message}")
|
||||
}
|
||||
|
||||
startVibration(context)
|
||||
AlarmNotifier.showAlarmNotification(context, alertId, volumeRaised, autoStopSeconds)
|
||||
return volumeRaised
|
||||
}
|
||||
|
||||
@Synchronized
|
||||
fun stop(context: Context) {
|
||||
try {
|
||||
player?.let {
|
||||
if (it.isPlaying) it.stop()
|
||||
it.release()
|
||||
}
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "player stop failed: ${e.message}")
|
||||
} finally {
|
||||
player = null
|
||||
}
|
||||
try {
|
||||
vibrator?.cancel()
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "vibrator cancel failed: ${e.message}")
|
||||
} finally {
|
||||
vibrator = null
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Raise the alarm stream and report whether the OS let us.
|
||||
*
|
||||
* `setStreamVolume` is a no-op on some OEM builds and throws
|
||||
* `SecurityException` under DND. Both are reported as `false` rather than
|
||||
* swallowed, because the notification fallback depends on knowing.
|
||||
*/
|
||||
private fun raiseAlarmStream(context: Context): Boolean {
|
||||
val am = context.getSystemService(Context.AUDIO_SERVICE) as? AudioManager ?: return false
|
||||
return try {
|
||||
val max = am.getStreamMaxVolume(AudioManager.STREAM_ALARM)
|
||||
am.setStreamVolume(AudioManager.STREAM_ALARM, max, 0)
|
||||
am.getStreamVolume(AudioManager.STREAM_ALARM) >= max
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "could not raise STREAM_ALARM: ${e.message}")
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
private fun startVibration(context: Context) {
|
||||
val v: Vibrator? = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
|
||||
(context.getSystemService(Context.VIBRATOR_MANAGER_SERVICE) as? VibratorManager)?.defaultVibrator
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
context.getSystemService(Context.VIBRATOR_SERVICE) as? Vibrator
|
||||
}
|
||||
if (v == null || !v.hasVibrator()) return
|
||||
try {
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
v.vibrate(VibrationEffect.createWaveform(VIBRATION_PATTERN, 1))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
v.vibrate(VIBRATION_PATTERN, 1)
|
||||
}
|
||||
vibrator = v
|
||||
} catch (e: Exception) {
|
||||
Log.w(TAG, "vibration failed: ${e.message}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Notification channels + the alarm notification, including the volume fallback. */
|
||||
object AlarmNotifier {
|
||||
const val CHANNEL_ALARM = "alarm_trigger"
|
||||
const val CHANNEL_SERVICE = "alarm_armed"
|
||||
|
||||
fun ensureChannels(context: Context) {
|
||||
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
|
||||
val alarm = NotificationChannel(
|
||||
CHANNEL_ALARM,
|
||||
"Alarm triggers",
|
||||
NotificationManager.IMPORTANCE_HIGH
|
||||
).apply {
|
||||
description = "Fires at full volume when an alert is triggered"
|
||||
enableVibration(true)
|
||||
setShowBadge(true)
|
||||
// The alarm is the payload: bypass DND where the user allows it.
|
||||
setBypassDnd(true)
|
||||
lockscreenVisibility = android.app.Notification.VISIBILITY_PUBLIC
|
||||
}
|
||||
nm.createNotificationChannel(alarm)
|
||||
|
||||
val service = NotificationChannel(
|
||||
CHANNEL_SERVICE,
|
||||
"Armed alert",
|
||||
NotificationManager.IMPORTANCE_LOW
|
||||
).apply {
|
||||
description = "Keeps the connection to the alarm service open while armed"
|
||||
setShowBadge(false)
|
||||
}
|
||||
nm.createNotificationChannel(service)
|
||||
}
|
||||
|
||||
/**
|
||||
* High-priority alarm notification. When `volumeRaised` is false the
|
||||
* notification carries a "Raise your volume" action, because the OS refused
|
||||
* the forced alarm stream and the user has to do it.
|
||||
*/
|
||||
fun showAlarmNotification(
|
||||
context: Context,
|
||||
alertId: String,
|
||||
volumeRaised: Boolean,
|
||||
autoStopSeconds: Int
|
||||
) {
|
||||
ensureChannels(context)
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
|
||||
val open = android.app.PendingIntent.getActivity(
|
||||
context,
|
||||
alertId.hashCode(),
|
||||
AlarmActivity.intent(context, alertId, "", autoStopSeconds),
|
||||
android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
|
||||
val builder = android.app.Notification.Builder(context, CHANNEL_ALARM)
|
||||
.setContentTitle("Alarm")
|
||||
.setContentText(if (volumeRaised) "Alarm ringing" else "Raise your volume to hear the alarm")
|
||||
.setSmallIcon(android.R.drawable.ic_lock_idle_alarm)
|
||||
.setCategory(android.app.Notification.CATEGORY_ALARM)
|
||||
.setPriority(android.app.Notification.PRIORITY_MAX)
|
||||
.setAutoCancel(false)
|
||||
.setOngoing(true)
|
||||
.setVisibility(android.app.Notification.VISIBILITY_PUBLIC)
|
||||
.setContentIntent(open)
|
||||
.setFullScreenIntent(open, true)
|
||||
|
||||
if (!volumeRaised) {
|
||||
val raise = android.app.PendingIntent.getActivity(
|
||||
context,
|
||||
alertId.hashCode() + 1,
|
||||
android.content.Intent(android.provider.Settings.ACTION_SOUND_SETTINGS),
|
||||
android.app.PendingIntent.FLAG_UPDATE_CURRENT or android.app.PendingIntent.FLAG_IMMUTABLE
|
||||
)
|
||||
builder.addAction(
|
||||
android.app.Notification.Action.Builder(
|
||||
null,
|
||||
"Raise your volume",
|
||||
raise
|
||||
).build()
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
nm.notify(NOTIFICATION_ID_ALARM, builder.build())
|
||||
} catch (e: SecurityException) {
|
||||
Log.w("AlarmNotifier", "notify failed (POST_NOTIFICATIONS?): ${e.message}")
|
||||
}
|
||||
}
|
||||
|
||||
fun cancelAlarm(context: Context) {
|
||||
val nm = context.getSystemService(NotificationManager::class.java) ?: return
|
||||
nm.cancel(NOTIFICATION_ID_ALARM)
|
||||
}
|
||||
|
||||
const val NOTIFICATION_ID_ALARM = 4711
|
||||
const val NOTIFICATION_ID_SERVICE = 4712
|
||||
}
|
||||
Reference in New Issue
Block a user