Android自定义闹钟功能
Android闹钟alarmManager+PendingIntent的使用方法,供大家参考,具体内容如下
这次给大家分享两种闹钟:
第一种是当到达闹钟时间后执行一次相应的操作
alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
第二种是当到达闹钟时间后每隔一段时间执行操作
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),5000, pendingIntent);
下面看效果图:
设置两种闹钟
选择闹钟时间
闹钟一到打开一个界面
下面看代码:
public class Alarm2Activity extends AppCompatActivity { private AlarmManager alarmManager; private PendingIntent pendingIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_alarm2); //实例化闹钟个管理器 alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); } //设置闹钟(只响一次) public void startAlarmOne(View view){ //获取当前系统的时间 Calendar calendar=Calendar.getInstance(); int hour=calendar.get(Calendar.HOUR_OF_DAY); int minute=calendar.get(Calendar.MINUTE); //弹出时间对话框(选择时间) TimePickerDialog timePickerDialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int i, int i1) { //获取当前系统的时间 Calendar c=Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY,i); c.set(Calendar.MINUTE,i1); //打开一个Activity Intent intent=new Intent(); intent.setAction("com.example.myandroid_27.ALARM"); PendingIntent pendingIntent= PendingIntent.getBroadcast(Alarm2Activity.this,0x101,intent,0); //设置闹钟 alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent); } },hour,minute,true); timePickerDialog.show(); } //设置闹钟(在多长时间后闹钟响然后继续计时) public void startAlarmTwo(View view){ //获取当前系统的时间 Calendar calendar=Calendar.getInstance(); int h=calendar.get(Calendar.HOUR_OF_DAY); int m=calendar.get(Calendar.MINUTE); //弹出时间对话框(选择时间) TimePickerDialog timePickerDialog=new TimePickerDialog(this, new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(TimePicker timePicker, int i, int i1) { //获取选择的闹钟时间 Calendar c=Calendar.getInstance(); c.set(Calendar.HOUR_OF_DAY,i); c.set(Calendar.MINUTE,i1); //打开一个Activity Intent intent=new Intent(); intent.setAction("com.example.myandroid_27.ALARM"); pendingIntent = PendingIntent.getBroadcast(Alarm2Activity.this,0x102,intent,0); //闹钟什么时候继续执行 alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),5000, pendingIntent); } },h,m,true); timePickerDialog.show(); } //关闭周期闹钟 public void startAlarmThree(View view){ alarmManager.cancel(pendingIntent); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)