有两个活动:一个是Main,用来设定闹钟,另一个是闹钟到点提示的活动Alarm
Main布局文件
<?xml version="1.0" encoding="utf-8"?> <TimePicker 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" android:orientation="vertical" tools:context=".MainActivity"> <TimePicker android:id="@+id/time" android:layout_width="wrap_content" android:layout_height="wrap_content"/> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="设置闹钟" /> </TimePicker>
两个活动的java代码
package com.example.myalarmi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.DialogInterface; import android.os.Bundle; public class AlarmActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AlertDialog alertDialog = new AlertDialog.Builder(this).create(); alertDialog.setTitle("标题"); alertDialog.setMessage("内容"); alertDialog.setButton( DialogInterface.BUTTON_POSITIVE, "", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } } ); alertDialog.show(); } }
package com.example.myalarmi; import androidx.annotation.RequiresApi; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TimePicker; import android.widget.Toast; import java.util.Calendar; import java.util.Map; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final TimePicker timePicker = (TimePicker)findViewById(R.id.time); timePicker.setIs24HourView(true); Button button = (Button)findViewById(R.id.button); button.setOnClickListener(new View.OnClickListener() { @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onClick(View v) { Intent intent = new Intent( MainActivity.this, AlarmActivity.class ); //获取显示闹钟的PendingIntent PendingIntent pendingIntent = PendingIntent.getActivity( MainActivity.this,0,intent,0 ); AlarmManager alarmManager = (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); alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis(),pendingIntent); } }); } }