帮我写完整的代码实现闹铃功能。在Timepicker选择好闹铃时间后,在闹铃的时间时响起MP3音乐。
时间: 2023-03-27 18:02:06 浏览: 102
好的,以下是实现闹铃功能的代码:
```
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.Button;
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 Button setAlarmButton;
private MediaPlayer mediaPlayer;
private boolean isPlaying = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
setAlarmButton = findViewById(R.id.setAlarmButton);
setAlarmButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
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, );
setAlarm(calendar.getTimeInMillis());
}
});
}
private void setAlarm(long timeInMillis) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, , intent, );
alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
Toast.makeText(this, "闹铃设置成功", Toast.LENGTH_SHORT).show();
}
public void startAlarm() {
if (!isPlaying) {
mediaPlayer = MediaPlayer.create(this, R.raw.alarm_sound);
mediaPlayer.start();
isPlaying = true;
}
}
public void stopAlarm() {
if (isPlaying) {
mediaPlayer.stop();
mediaPlayer.release();
isPlaying = false;
}
}
}
```
在这个代码中,我们使用了 Android 的 AlarmManager 来设置闹铃,当闹铃时间到达时,会触发一个广播,我们在广播接收器中播放 MP3 音乐。以下是广播接收器的代码:
```
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity activity = (MainActivity) context;
activity.startAlarm();
}
}
```
在这个广播接收器中,我们通过 context 获取到 MainActivity 的实例,然后调用 MainActivity 中的 startAlarm() 方法来播放音乐。当用户点击停止闹铃按钮时,我们会调用 MainActivity 中的 stopAlarm() 方法来停止播放音乐。
阅读全文