请帮我写完整的可以运行的代码。使用一个Timepicker控件和一个imagebutton实现闹钟功能。点击按钮可切换闹钟的开和关。手机到timepicker上的时间时,闹钟触发并且循环播放MP3音乐,点击按钮可取消播放。
时间: 2023-03-27 16:01:06 浏览: 81
Android实例代码
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;
private boolean isAlarmSet = false;
@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 (isAlarmSet) {
alarmManager.cancel(pendingIntent);
mediaPlayer.stop();
mediaPlayer.reset();
isAlarmSet = false;
Toast.makeText(MainActivity.this, "闹钟已关闭", Toast.LENGTH_SHORT).show();
} else {
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 timeInMillis = calendar.getTimeInMillis();
if (timeInMillis < System.currentTimeMillis()) {
timeInMillis += 24 * 60 * 60 * 100;
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, timeInMillis, 24 * 60 * 60 * 100, pendingIntent);
mediaPlayer.start();
isAlarmSet = true;
Toast.makeText(MainActivity.this, "闹钟已开启", Toast.LENGTH_SHORT).show();
}
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
```
请注意,这段代码只是一个示例,可能需要根据您的具体需求进行修改。
阅读全文