我写完整的可以运行的代码。使用一个Timepicker控件和一个imagebutton实现闹钟功能。点击按钮可切换闹钟的开和关。手机到timepicker上的时间时,闹钟触发并且循环播放MP3音乐,点击按钮可取消播放。
时间: 2023-03-27 15:01:00 浏览: 103
音乐闹钟 当到你设置的时间时就会播放音乐
4星 · 用户满意度95%
您好,我可以回答这个问题。以下是代码示例:
```
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 imageButton;
private MediaPlayer mediaPlayer;
private PendingIntent pendingIntent;
private AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timePicker = findViewById(R.id.timePicker);
imageButton = findViewById(R.id.imageButton);
mediaPlayer = MediaPlayer.create(this, R.raw.alarm);
Intent intent = new Intent(MainActivity.this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(MainActivity.this, , intent, );
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (alarmManager != null) {
if (imageButton.getTag() == null) {
int hour, minute;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M) {
hour = timePicker.getHour();
minute = timePicker.getMinute();
} else {
hour = timePicker.getCurrentHour();
minute = timePicker.getCurrentMinute();
}
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, );
calendar.set(Calendar.MILLISECOND, );
long timeInMillis = calendar.getTimeInMillis();
long currentTimeInMillis = System.currentTimeMillis();
if (timeInMillis > currentTimeInMillis) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
imageButton.setImageResource(R.drawable.ic_alarm_on);
imageButton.setTag("on");
Toast.makeText(MainActivity.this, "闹钟已开启", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(MainActivity.this, "请选择未来的时间", Toast.LENGTH_SHORT).show();
}
} else {
alarmManager.cancel(pendingIntent);
imageButton.setImageResource(R.drawable.ic_alarm_off);
imageButton.setTag(null);
mediaPlayer.stop();
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.setLooping(true);
mediaPlayer.start();
}
}
}
```
希望对您有所帮助!
阅读全文