添加權(quán)限(不需要動態(tài)申請權(quán)限)
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
1旋奢、向系統(tǒng)中添加鬧鐘數(shù)據(jù)
時間到了后會自動響鈴提醒
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)//不會有結(jié)果返回
}
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)
}
}
但是沒有效果,會跳轉(zhuǎn)到系統(tǒng)鬧鐘界面至朗,需要手動關閉屉符;如果有人能取消成功,麻煩留言提醒锹引,十分感謝矗钟。