添加权限(不需要动态申请权限)
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
1、向系统中添加闹钟数据
时间到了后会自动响铃提醒
fun addAlertClock(context: Activity, item: AlertItem) {
val dayIntDef = mutableListOf(
Calendar.MONDAY,
Calendar.TUESDAY,
Calendar.WEDNESDAY,
Calendar.THURSDAY,
Calendar.FRIDAY,
Calendar.SATURDAY,
Calendar.SUNDAY
)
val ALERT_REQUEST_CODE = 100
val intent = Intent(AlarmClock.ACTION_SET_ALARM)
intent.putExtra(AlarmClock.EXTRA_HOUR, item.hour)//小时 0-23
intent.putExtra(AlarmClock.EXTRA_MINUTES, item.minute)//分钟 0-59
intent.putExtra(AlarmClock.EXTRA_MESSAGE, item.message)//闹钟备注名称呼
val days = ArrayList(item.days.map { dayIntDef[it - 1] })
intent.putIntegerArrayListExtra(AlarmClock.EXTRA_DAYS, days)//周几响铃 周一-周日 设置7个就是每天
//intent.putExtra(AlarmClock.EXTRA_RINGTONE, uri.toString())//设置铃声uri 可不设
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)//是否跳过设置UI
intent.putExtra(AlarmClock.EXTRA_VIBRATE, true)//是否震动
context.startActivityForResult(intent, ALERT_REQUEST_CODE)//不会有结果返回
}
class AlertItem {
var hour = 0//小时
var minute = 0//分钟
var days = LinkedHashSet<Int>()//空: 每天 1-7 表示周一到周日
var message: String = ""
}
2、取消闹钟
fun delAlertClock(context: Activity, item: AlertItem) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
val intent = Intent(AlarmClock.ACTION_DISMISS_ALARM)
if (item.message.isNotEmpty()) {
intent.putExtra(
AlarmClock.EXTRA_ALARM_SEARCH_MODE, AlarmClock.ALARM_SEARCH_MODE_LABEL
)
intent.putExtra(AlarmClock.EXTRA_MESSAGE, item.message)
intent.putExtra(AlarmClock.EXTRA_HOUR, item.hour)
intent.putExtra(AlarmClock.EXTRA_MINUTES, item.minute)
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
} else {
intent.putExtra(
AlarmClock.EXTRA_ALARM_SEARCH_MODE, AlarmClock.ALARM_SEARCH_MODE_TIME
)
val pm = item.hour > 12
val hour = if (item.hour > 12) item.hour - 12 else item.hour
intent.putExtra(AlarmClock.EXTRA_IS_PM, pm)
intent.putExtra(AlarmClock.EXTRA_HOUR, hour)
intent.putExtra(AlarmClock.EXTRA_MINUTES, item.minute)
intent.putExtra(AlarmClock.EXTRA_SKIP_UI, true)
}
context.startActivity(intent)
}
}
但是没有效果,会跳转到系统闹钟界面,需要手动关闭;如果有人能取消成功,麻烦留言提醒,十分感谢。
网友评论