请帮我写完整的可以运行的代码。利用一个Timepicker控件和一个imagebutton实现闹钟功能。通过点击按钮,开启闹钟,当到达Timepicker上的时间后,播放MP3音乐;再次点击按钮,关闭闹钟和关闭铃声,如再次点击则又开启闹钟。
时间: 2023-09-07 13:04:05 浏览: 108
### 回答1:
好的,以下是可以运行的代码:
```
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TimePicker timePicker;
private ImageButton alarmButton;
private MediaPlayer mediaPlayer;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
private boolean isAlarmSet = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
alarmButton = findViewById(R.id.alarmButton);
// 初始化闹钟管理器和PendingIntent
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, , intent, );
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// 初始化MediaPlayer
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
// 设置闹钟按钮的点击事件
alarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isAlarmSet) {
// 获取用户设置的时间
int hour = timePicker.getCurrentHour();
int minute = timePicker.getCurrentMinute();
// 设置闹钟时间
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, );
long alarmTime = calendar.getTimeInMillis();
// 设置闹钟
alarmManager.set(AlarmManager.RTC_WAKEUP, alarmTime, pendingIntent);
// 更新按钮状态和提示信息
isAlarmSet = true;
alarmButton.setImageResource(R.drawable.ic_alarm_off);
Toast.makeText(MainActivity.this, "闹钟已设置", Toast.LENGTH_SHORT).show();
} else {
// 取消闹钟
alarmManager.cancel(pendingIntent);
// 停止播放铃声
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
// 更新按钮状态和提示信息
isAlarmSet = false;
alarmButton.setImageResource(R.drawable.ic_alarm_on);
Toast.makeText(MainActivity.this, "闹钟已取消", Toast.LENGTH_SHORT).show();
}
}
});
}
// 定义闹钟响铃时的广播接收器
public static class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// 播放铃声
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.alarm);
mediaPlayer.start();
// 显示通知
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, "default")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("闹钟提醒")
.setContentText("时间到了!")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);
notificationManager.notify(, builder.build());
}
}
}
```
需要注意的是,这段代码中使用了一个 `AlarmReceiver` 广播接收器来处理闹钟响铃时的逻辑。在使用时,需要在 AndroidManifest.xml 文件中注册该广播接收器:
```
<receiver android:name=".MainActivity$AlarmReceiver" />
```
另外,为了让铃声能够正常播放,需要在 AndroidManifest.xml 文件中添加以下权限:
```
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
```
### 回答2:
下面是一个可以实现闹钟功能的Android代码示例:
首先,我们需要在布局文件中定义一个TimePicker控件和一个ImageButton按钮。例如,在activity_main.xml文件中添加以下代码:
```xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="16dp"
android:paddingTop="16dp"
android:paddingRight="16dp"
android:paddingBottom="16dp"
tools:context=".MainActivity">
<TimePicker
android:id="@+id/timePicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true" />
<ImageButton
android:id="@+id/alarmButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/timePicker"
android:layout_centerHorizontal="true"
android:src="@android:drawable/ic_lock_idle_alarm" />
</RelativeLayout>
```
然后,在MainActivity.java文件中编写以下代码实现闹钟功能:
```java
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class MainActivity extends AppCompatActivity {
private TimePicker timePicker;
private ImageButton alarmButton;
private Calendar alarmTime;
private boolean isAlarmSet = false;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
alarmButton = findViewById(R.id.alarmButton);
alarmTime = Calendar.getInstance();
alarmTime.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
alarmTime.set(Calendar.MINUTE, timePicker.getCurrentMinute());
alarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isAlarmSet) {
startAlarm();
} else {
stopAlarm();
}
}
});
}
private void startAlarm() {
mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound);
mediaPlayer.setLooping(true);
mediaPlayer.start();
isAlarmSet = true;
alarmButton.setImageResource(android.R.drawable.ic_media_pause);
}
private void stopAlarm() {
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer = null;
}
isAlarmSet = false;
alarmButton.setImageResource(android.R.drawable.ic_lock_idle_alarm);
}
}
```
此示例使用了一个MediaPlayer对象来播放音乐,音乐文件名为alarm_sound.mp3。请先将alarm_sound.mp3文件放置在res/raw目录下。
运行该应用程序后,您可以通过选择TimePicker上的时间并点击ImageButton按钮来启动和关闭闹钟功能。当到达设置的时间时,将播放铃声,再次点击按钮则会关闭铃声。
### 回答3:
以下是使用Java代码实现闹钟功能的示例:
```java
import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Calendar;
public class AlarmActivity extends AppCompatActivity {
private ImageButton alarmButton;
private TimePicker alarmTimePicker;
private boolean isAlarmSet = false;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_alarm);
alarmButton = findViewById(R.id.alarm_button);
alarmTimePicker = findViewById(R.id.alarm_timepicker);
alarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!isAlarmSet) {
setAlarm();
} else {
cancelAlarm();
}
}
});
}
private void setAlarm() {
int hour = alarmTimePicker.getCurrentHour(); // 获取选定的小时
int minute = alarmTimePicker.getCurrentMinute(); // 获取选定的分钟
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
final long alarmTime = calendar.getTimeInMillis();
mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound);
mediaPlayer.setLooping(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("闹钟已设置");
builder.setMessage("闹钟将在所选时间响起");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startAlarm(alarmTime);
}
});
builder.setNegativeButton("取消", null);
AlertDialog dialog = builder.create();
dialog.show();
}
private void startAlarm(final long alarmTime) {
alarmButton.setImageResource(R.drawable.ic_alarm_on);
isAlarmSet = true;
Thread alarmThread = new Thread(new Runnable() {
@Override
public void run() {
while (System.currentTimeMillis() < alarmTime) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
mediaPlayer.start();
}
});
alarmThread.start();
}
private void cancelAlarm() {
alarmButton.setImageResource(R.drawable.ic_alarm_off);
isAlarmSet = false;
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
}
```
你需要在XML布局文件中加入以下代码:
```xml
<TimePicker
android:id="@+id/alarm_timepicker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:timePickerMode="spinner"/>
<ImageButton
android:id="@+id/alarm_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/alarm_timepicker"
android:layout_centerHorizontal="true"
android:src="@drawable/ic_alarm_off"/>
```
请确保将音频文件 "alarm_sound.mp3" 放置在 "res/raw/" 目录下。
这段代码创建了一个可调整时间的TimePicker控件和一个ImageButton按钮。当点击按钮时,将根据TimePicker选择的时间设置闹钟。在闹钟时间到达后,将播放名为 "alarm_sound.mp3" 的音乐。再次点击按钮将会取消闹钟并停止播放音乐。
阅读全文