您可以使用以下内容:
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" }
}
这是从位于以下位置的默认时钟应用程序的 Android 源代码复制而来的:DeskClock/src/com/android/deskclock/alarms/AlarmStateManager.java
在源代码中搜索这个函数,看看他们是如何做类似的。我们基本上会向com.qualcomm.qti.poweroffalarm
包发送一个广播,然后它会像在 DeskClock 应用程序中那样创建一个关机警报。
如果我们查看反编译的源代码,com.qualcomm.qti.poweroffalarm
我们会看到清单声明如下:
<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>
这意味着我们还需要 qcom 包的此权限才能接受广播的意图。因此,我们将其设置在 AndroidManifest.xml 中:
<uses-permission android:name="org.codeaurora.permission.POWER_OFF_ALARM" />
然后也请求它:
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);
}
最后我们要调用 SetAlarm 函数。我们指定从现在到我们希望闹钟响起的时间(以毫秒为单位)。例如在两分钟内:
setPowerOffAlarm(context, 120000)