使用AlermManager设置闹钟

直接上代码
activity_main.xml

<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=".MainActivity">
    <TimePicker
        android:id="@+id/time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/set"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:text="设置闹钟"/>
</RelativeLayout>

MainActivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final TimePicker timePicker = findViewById(R.id.time);
        timePicker.setIs24HourView(true);//设置使用24小时制
        Button button = findViewById(R.id.set);
        //为"设置闹钟"按钮添加单击监听事件
        button.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                //设置闹钟
                Intent intent = new Intent
                        (MainActivity.this,AlarmActivity.class);
                PendingIntent pendingIntent = PendingIntent.getActivity(
                        MainActivity.this,0,intent,0);
                AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                Calendar c = Calendar.getInstance();//获取日历对象
                c.set(Calendar.HOUR_OF_DAY,timePicker.getCurrentHour());//设置闹钟小时数
                c.set(Calendar.MINUTE,timePicker.getCurrentMinute());//设置闹钟分钟数
                c.set(Calendar.SECOND,0);//
                alarm.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent);
                Toast.makeText(MainActivity.this,"设置闹钟成功",Toast.LENGTH_SHORT).show();
            }
        });
    }

效果:
使用AlermManager设置闹钟

闹钟类型:

ELAPSED_REALTIME:指定的延时后提醒(不唤醒系统)
ELAPSED_REALTIME_WAKEUP:

相关推荐