一、首先创建设置闹钟的布局页面activity_alarm_manager.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".AlarmManagerActivity">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<Button
android:id="@+id/btn_alarm"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/timePicker"
android:layout_centerHorizontal="true"
android:text="设置闹钟" />
</RelativeLayout>
二、创建AlarmActivity用于设置其到达指定时间后,弹出的一个对话,这个要在清单文件中注册
public class AlarmActivity extends AppCompatActivity {
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("传递正能量")
.setIcon(R.drawable.ic_baseline_report)
.setMessage("要么出众,要么出局")
.setNegativeButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//确定
}
}).show();
}
}
三、在activity_alarm_manager.xml对应的Activity中设置闹钟
public class AlarmManagerActivity extends AppCompatActivity {
private TimePicker timePicker;
private Button btn_alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm_manager);
timePicker = findViewById(R.id.timePicker);
btn_alarm = findViewById(R.id.btn_alarm);
btn_alarm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//设置闹钟
Intent intent = new Intent(AlarmManagerActivity.this, AlarmActivity.class);
//获取显示闹钟的PendingIntent
//PendingIntent是对Intent的描述,主要用来处理即将发生的事情,这个Intent会由其他程序进行调用,这里是由闹钟调用
PendingIntent pendingIntent = PendingIntent.getActivity(AlarmManagerActivity.this, 0, intent, 0);
//获取AlarmManager对象
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//获取日历对象
Calendar c = Calendar.getInstance();
//设置闹钟的小时数
c.set(Calendar.HOUR_OF_DAY, timePicker.getHour());
//设置闹钟的分钟数
c.set(Calendar.MINUTE, timePicker.getMinute());
//设置闹钟的秒数
c.set(Calendar.SECOND, 0);
//第一个参数:闹钟类型
//ELAPSED_REALTIME:在指定的延时后提醒(不唤醒系统)
//ELAPSED_REALTIME_WAKEUP:在指定的延时后提醒(唤醒系统)
//RTC:到达指定时间提醒(不唤醒系统)
//RTC_WAKEUP:到达指定时间提醒(唤醒系统)
//第二参数:指定时间,获取日历对象对应时间的毫秒数
//第三个参数:用于指定当闹钟唤醒时,所指定的页面
alarm.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
Toast.makeText(AlarmManagerActivity.this, "闹钟设置成功!", Toast.LENGTH_SHORT).show();
}
});
}
}
效果如图所示:
|