package com.example.alarmtest;

import java.util.Calendar;

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.os.Bundle;
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 {
	Button button;
	AlarmManager alarmManager;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		button = (Button) findViewById(R.id.button1);
		
		//获取AlarmManager对象
		alarmManager = (AlarmManager) getSystemService(Service.ALARM_SERVICE);
		
		button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				Calendar currentTime = Calendar.getInstance();
				//创建一个TimePickerDialog实例，并显示
				new TimePickerDialog(MainActivity.this, 0, 
						new TimePickerDialog.OnTimeSetListener() {
							
							@Override
							public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
								//指定启动AlarmActivity组件
								Intent intent = new Intent(MainActivity.this, AlarmActivity.class);
								//创建PendingIntent对象
								/*
								 * PendingIntent与Intent的区别是PendingIntent处理即将发生的事情
								 * 比如：在通知栏Notification中跳转页面，不是立即跳转
								 * 通常通过  getActivity、getBroadcast、getService得到PendingIntent的实例
								 * 
								 */
								PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
								Calendar c = Calendar.getInstance();
								c.setTimeInMillis(System.currentTimeMillis());
								c.set(Calendar.HOUR, hourOfDay);
								c.set(Calendar.MINUTE, minute);
								
								alarmManager.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();
			}
		});
	}
}
