Android 闹钟源码

package xuyan.alarmmanager.test;

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.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

public class AlarmManagerActivity extends Activity {
    /** Called when the activity is first created. */
	Button settime;
	AlarmManager alarmmanager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        alarmmanager=(AlarmManager)getSystemService(Service.ALARM_SERVICE);
        settime=(Button)this.findViewById(R.id.button1);
        settime.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Calendar currenttime=Calendar.getInstance();
				//创建一个Timepicketdialog的实例,并把它显示出来
				new TimePickerDialog(AlarmManagerActivity.this, 0, new TimePickerDialog.OnTimeSetListener() {
					
					public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
						// TODO Auto-generated method stub
						
						
						//指定启动Alarmmanager组建
						Intent intent=new Intent();
						intent.setClass(AlarmManagerActivity.this, AlarmActivity.class);
						
						//创建PindingIntent对象
						PendingIntent pi=PendingIntent.getActivity(AlarmManagerActivity.this, 0, intent, 0);
						Calendar c=Calendar.getInstance();//实例化
						c.setTimeInMillis(System.currentTimeMillis());
						
						//根据用户选择时间来设置Calendar对象
						c.set(Calendar.HOUR, hourOfDay);
						c.set(Calendar.MINUTE, minute);
						
						//设置AlarmManager将在Calendar对应的时间启动指定组件
						alarmmanager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pi);
						
						//显示闹铃提示设置成功的信息
						Toast.makeText(AlarmManagerActivity.this, "设置成功", 5000).show();
					}
				}, currenttime.get(Calendar.HOUR_OF_DAY), currenttime.get(Calendar.MINUTE), false).show();
			}
		});
    }
}


 

第二个Activity

 

 

package xuyan.alarmmanager.test;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Button;

public class AlarmActivity extends  Activity{

	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		
		//创建一个对话框
		new  AlertDialog.Builder(AlarmActivity.this)
		.setTitle("闹铃")
		.setMessage("闹铃响了,GO!GO!GO!")
		.setPositiveButton("确定", new OnClickListener(){

			public void onClick(DialogInterface dialog, int which) {
				// TODO Auto-generated method stub
				AlarmActivity.this.finish();
			}
			
		}).show();
	}
	

}


 

你可能感兴趣的:(Android)