you can use something like the following:
private val ACTION_SET_POWEROFF_ALARM = "org.codeaurora.poweroffalarm.action.SET_ALARM"
private val ACTION_CANCEL_POWEROFF_ALARM = "org.codeaurora.poweroffalarm.action.CANCEL_ALARM"
private val POWER_OFF_ALARM_PACKAGE = "com.qualcomm.qti.poweroffalarm"
private val TIME = "time"
private fun setPowerOffAlarm(context: Context, timeInMillis: Long) {
val intent = Intent(ACTION_SET_POWEROFF_ALARM)
intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND)
intent.setPackage(POWER_OFF_ALARM_PACKAGE)
val rightNow = Calendar.getInstance()
rightNow.set(Calendar.SECOND, 0);
rightNow.set(Calendar.MILLISECOND, 0);
intent.putExtra(TIME, rightNow.timeInMillis + timeInMillis)
context.sendBroadcast(intent)
Log.i { "PWR STATE: pwr off Alarm is set" }
}
This is copied from the Android source code of the Default Clock App located at: DeskClock/src/com/android/deskclock/alarms/AlarmStateManager.java
Search for this function in the source code and see how they do it similarly. We basically send a broadcast to the com.qualcomm.qti.poweroffalarm
package which will then create a power off alarm as you would do in the DeskClock app.
If we look at the decompiled source code of the com.qualcomm.qti.poweroffalarm
we see that the manifest states something like the following:
<receiver android:name="com.qualcomm.qti.poweroffalarm.PowerOffAlarmDialog$ShutDownReceiver" android:permission="org.codeaurora.permission.POWER_OFF_ALARM">
<intent-filter>
<action android:name="org.codeaurora.poweroffalarm.action.ALARM_POWER_OFF"/>
</intent-filter>
</receiver>
This means we also require this permission for the qcom package to accept the broadcasted intent. We therefore set it in our AndroidManifest.xml:
<uses-permission android:name="org.codeaurora.permission.POWER_OFF_ALARM" />
And then also request it:
private val PERMISSION_POWER_OFF_ALARM = "org.codeaurora.permission.POWER_OFF_ALARM"
private val CODE_FOR_ALARM_PERMISSION = 1
if (ContextCompat.checkSelfPermission(this, PERMISSION_POWER_OFF_ALARM)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
arrayOf(PERMISSION_POWER_OFF_ALARM), CODE_FOR_ALARM_PERMISSION);
}
Finally we want to call the SetAlarm function. We specify the time in milliseconds from now until we want the alarm to ring. For example in two minutes:
setPowerOffAlarm(context, 120000)