我有一个Timepicker空件和一个imagebutton,实现选择好时间,点击imagebutton,到点响铃,请帮我写完整的可以运行的代码
时间: 2023-03-25 21:03:28 浏览: 130
好的,以下是可以实现你所描述的功能的代码:
```
// 在布局文件中添加Timepicker和imagebutton
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageButton
android:id="@+id/imageButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/alarm_icon" />
// 在Activity中添加以下代码
public class MainActivity extends AppCompatActivity {
private TimePicker timePicker;
private ImageButton imageButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
imageButton = findViewById(R.id.imageButton);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// 创建Intent,用于启动闹钟
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, , intent, );
// 获取AlarmManager实例
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
// 设置闹钟时间
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, );
// 如果闹钟时间已经过去,则将闹钟时间设置为明天同一时间
if (calendar.getTimeInMillis() < System.currentTimeMillis()) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
// 设置闹钟
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(MainActivity.this, "闹钟已设置", Toast.LENGTH_SHORT).show();
}
});
}
}
// 创建AlarmReceiver类,用于接收闹钟广播
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 播放闹钟铃声
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
Ringtone ringtone = RingtoneManager.getRingtone(context, uri);
ringtone.play();
// 显示通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.alarm_icon)
.setContentTitle("闹钟提醒")
.setContentText("时间到了!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(, builder.build());
}
}
```
这段代码实现了在Timepicker中选择时间,点击imagebutton后设置闹钟,并在闹钟时间到达时播放铃声和显示通知的功能。
阅读全文