package com.samples.alarm.alarmmanager;

import java.util.Calendar;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AlarmManagerActivity extends Activity 
	implements View.OnClickListener {

	private PendingIntent pendingIntent;
	private AlarmManager manager;
	private Intent intent;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		final Button bStart = (Button)findViewById(R.id.bStart);
		final Button bStop = (Button)findViewById(R.id.bStop);
		final Button bCancel = (Button)findViewById(R.id.bCancel);
		
		bStart.setOnClickListener(this);
		bStop.setOnClickListener(this);
		bCancel.setOnClickListener(this);
		
		manager = (AlarmManager)getSystemService(ALARM_SERVICE);
		
	    intent = new Intent(AlarmManagerActivity.this, 
				AlarmService.class);
 	}

	@Override
	public void onClick(View v) {
		

		
		switch (v.getId()) {
		case R.id.bStart:
			pendingIntent = PendingIntent.getService(
					getApplicationContext(), 0, intent, 0);

			Calendar calendar = Calendar.getInstance();
			calendar.setTimeInMillis(System.currentTimeMillis());
			calendar.add(Calendar.SECOND, 5);

			manager.setRepeating(
					AlarmManager.RTC_WAKEUP, 
					calendar.getTimeInMillis(), 
					5000, 
					pendingIntent);
			break;
			
		case R.id.bCancel:
			manager.cancel(pendingIntent);
			break;
			
		case R.id.bStop:
			this.stopService(intent);
			break;
		}		
	}
}