package com.android.xiong.alarmtests;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class MainActivity extends Activity {
private Button bt1;
private AlarmManager aManger;
Calendar currentTime = Calendar.getInstance();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt1 = (Button) findViewById(R.id.bt1);
aManger = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
bt1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Calendar currentTime = Calendar.getInstance();
// 创建一个TimePickerDialog实例,并显示出来
new TimePickerDialog(MainActivity.this,0,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker view,
int hourOfDay, int minute) {
// 指定启动的组件
Intent intent = new Intent(MainActivity.this,
AlarmActivity.class);
// 创建PendingIntent对象
PendingIntent pi = PendingIntent.getActivity(
MainActivity.this, 0, intent, 0);
Calendar c = Calendar.getInstance();
// 根据用户选择的时间来设置Calender对象
c.set(Calendar.HOUR, hourOfDay);
c.set(Calendar.MINUTE, minute);
// 设置AlarManger将在Calendar对应的时间启动指定的组件
aManger.set(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pi);
// 显示闹钟设置成功的提示信息
Toast.makeText(MainActivity.this, "闹钟设置成功!",
Toast.LENGTH_SHORT).show();
}
}, currentTime.get(Calendar.HOUR_OF_DAY), currentTime
.get(Calendar.MINUTE), false).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
package com.android.xiong.alarmtests;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.media.MediaPlayer;
import android.os.Bundle;
public class AlarmActivity extends Activity {
MediaPlayer alarmMusic;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 加载指定的音乐,并为之创建MediaPlay对象
alarmMusic = MediaPlayer.create(this, R.raw.earth);
alarmMusic.setLooping(true);
// 播放音乐
alarmMusic.start();
// 创建一个对话框
new AlertDialog.Builder(this).setTitle("闹钟").setMessage("闹钟!go!go!go")
.setPositiveButton("确定", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//停止音乐
alarmMusic.stop();
AlarmActivity.this.finish();
}
}).show();
}
}