Friday, August 13, 2010

Alarm Clock 1.0 Initial Code Release

So I cleaned out all the crap comments left over in the code and put in meaningful comments throughout. I still need to go back and review the structure and make any necessary improvements. I have created a database for logging my Bug/Feature/Wish list and will knock a few down, I imagine, before I lose interest in this app for a new one.

Either way, the java code is shown below. Feel free to comment on the code and make any suggestions for improvements. I am sure advice would allow me to get this cleaned up much quicker than having to figure it all out on my own.

It will probably be best to copy paste into another text editor for the best readability.


DonnsAlarm.java

package donnomalley.alarm;

import android.app.Activity;
import android.os.Bundle;
import android.widget.*;
import android.view.View;
import android.content.Intent;
import android.app.PendingIntent;
import android.app.AlarmManager;
import java.util.Calendar;
import android.content.SharedPreferences;

/** Main Class for setting the Alarm */
public class DonnsAlarm extends Activity {

public static final String PREFS_NAME = "MyPrefsFile";
public static final String ALARM_ENABLED = "ALARM_ENABLED";
public static final String ALARM_HOUR = "ALARM_HOUR";
public static final String ALARM_MINUTE = "ALARM_MIN";
public static final String SNOOZE_MINUTE = "SNOOZE_MIN";

int AlarmHour;
int AlarmMin;
boolean AlarmEnabled;
CheckBox EnableCheckBox;
TimePicker AlarmTimePicker;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//set Layout
setContentView(R.layout.alarmclock);

//Assign UI components to local variables
EnableCheckBox = (CheckBox)findViewById(R.id.EnabledCheckBox);
AlarmTimePicker = (TimePicker)findViewById(R.id.AlarmTimePicker);
EnableCheckBox.setOnClickListener(new AlarmEnableListener());

//Fetch Saved settings (Alarm Hour, Minute, Enable) and assign values accordingly
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
AlarmEnabled = settings.getBoolean("AlarmEnabled", false);
AlarmHour = settings.getInt(ALARM_HOUR, 12);
AlarmMin = settings.getInt(ALARM_MINUTE, 0);

//Set the Time Picker's Hour, Minute, AM/PM
AlarmTimePicker.setCurrentHour(AlarmHour);
AlarmTimePicker.setCurrentMinute(AlarmMin);

//Sets the property, doesn't cause OnClick Event to fire
EnableCheckBox.setChecked(AlarmEnabled);
}

/** Called to set/cancel an alarm. */
public void SetAlarm(boolean AlarmEnabled, int AlarmHour, int AlarmMin) {
if (AlarmEnabled) {
//Build Intent/Pending Intent for setting the alarm
Intent AlarmIntent = new Intent(DonnsAlarm.this, AlarmReceiver.class);
AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent Sender = PendingIntent.getBroadcast(DonnsAlarm.this, 0, AlarmIntent, 0);

//Build Calendar object with Alarm Time and use it to set the alarm
Calendar calendar = Calendar.getInstance();
int CurHour = calendar.get(Calendar.HOUR);
int CurMin = calendar.get(Calendar.MINUTE);

calendar.set(Calendar.HOUR, AlarmHour);
calendar.set(Calendar.MINUTE, AlarmMin);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
if (AlarmHour <= CurHour) { if (AlarmMin <= CurMin) { calendar.add(Calendar.HOUR, 24); } } AlmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), Sender); //Build the Strings for displaying the alarm time through Toast int CalendarHour = calendar.get(Calendar.HOUR); int CalendarMin = calendar.get(Calendar.MINUTE); String CalendarHourStr = Integer.toString(CalendarHour); String CalendarMinStr = Integer.toString(CalendarMin); if (CalendarMin < 10) { CalendarMinStr = "0" + CalendarMinStr; } String strAmPM; if (calendar.get(Calendar.AM_PM) == Calendar.AM) { strAmPM = "AM"; } else { strAmPM = "PM"; } Toast.makeText(this, "Alarm Set For " + CalendarHourStr + ":" + CalendarMinStr + " " + strAmPM, Toast.LENGTH_LONG).show(); //Save settings Enabled, Alarm Hour, Alarm Minute SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(ALARM_ENABLED, true); editor.putInt(ALARM_HOUR, AlarmHour); editor.putInt(ALARM_MINUTE, AlarmMin); //Commit the edits editor.commit(); } else { //Build Intent/Pending Intent for canceling the alarm Intent AlarmIntent = new Intent(DonnsAlarm.this, AlarmReceiver.class); AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE); PendingIntent Sender = PendingIntent.getBroadcast(DonnsAlarm.this, 0, AlarmIntent, 0); AlmMgr.cancel(Sender); //Display Alarm Disabled Message Toast.makeText(DonnsAlarm.this, "Alarm Disabled", Toast.LENGTH_LONG).show(); //Save setting Enabled SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0); SharedPreferences.Editor editor = settings.edit(); editor.putBoolean(ALARM_ENABLED, false); // Commit the edits editor.commit(); } } /** Class for implementing the Enable's Check Box Click Event Listener */ public class AlarmEnableListener implements CheckBox.OnClickListener { @Override public void onClick(View v) { //Read State of UI components and call SetAlarm routine AlarmEnabled = EnableCheckBox.isChecked(); AlarmHour = AlarmTimePicker.getCurrentHour(); AlarmMin = AlarmTimePicker.getCurrentMinute(); SetAlarm(AlarmEnabled, AlarmHour, AlarmMin); } } } 



AlarmReceiver.java

package donnomalley.alarm;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;

/** Class for receiving broadcast when the Alarm occurs */
public class AlarmReceiver extends BroadcastReceiver
{
public static final String ALARM_ALERT_ACTION = "com.android.alarmclock.ALARM_ALERT";
public static final String ALARM_INTENT_EXTRA = "intent.extra.alarm";

@Override
public void onReceive(Context context, Intent intent) {
//Create Intent to Start the AlarmActivity "Snooze" Activity
Intent myIntent = new Intent(context, AlarmActivity.class);
myIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(myIntent);

//Build pending intent from calling information to display Notification
PendingIntent Sender = PendingIntent.getBroadcast(context, 0, intent, 0);
NotificationManager manager = (NotificationManager)context.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "Wake up alarm", System.currentTimeMillis());
notification.setLatestEventInfo(context, "Donns Alarm", "WAKE UP BITCH", Sender);
notification.flags = Notification.FLAG_NO_CLEAR;
manager.notify(R.string.app_name, notification);
}
}



AlarmActivity.java

package donnomalley.alarm;

import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
//import android.widget.Toast;
import android.view.Window;
import android.view.WindowManager;

/** Class for managing the "Snooze"(AlarmActivity) Activity */
public class AlarmActivity extends Activity
{
public RadioButton SnoozeRadio1;
public RadioButton SnoozeRadio2;
public RadioButton SnoozeRadio5;
public RadioButton SnoozeRadio10;
public int SnoozeMin;
public MediaPlayer mMediaPlayer;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//Set window features to hide the notification bar and make the UI fullscreen before assigning the layout
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.alarm);

//Get Last used Snooze Value and use as default
SharedPreferences settings = getSharedPreferences(DonnsAlarm.PREFS_NAME, 0);
SnoozeMin = settings.getInt(DonnsAlarm.SNOOZE_MINUTE, 10);

//Assign UI components to local variables and define Click Event Listeners
SnoozeRadio1 = (RadioButton)findViewById(R.id.SnoozeMin1);
SnoozeRadio1.setOnClickListener(new MyRadioListener1());
SnoozeRadio2 = (RadioButton)findViewById(R.id.SnoozeMin2);
SnoozeRadio2.setOnClickListener(new MyRadioListener2());
SnoozeRadio5 = (RadioButton)findViewById(R.id.SnoozeMin5);
SnoozeRadio5.setOnClickListener(new MyRadioListener5());
SnoozeRadio10 = (RadioButton)findViewById(R.id.SnoozeMin10);
SnoozeRadio10.setOnClickListener(new MyRadioListener10());
Button SnoozeButton = (Button)this.findViewById(R.id.snooze_button);
SnoozeButton.setOnClickListener(new MySnoozeListener());

//Initialize UI Components
SnoozeRadio1.setChecked(false);
SnoozeRadio2.setChecked(false);
SnoozeRadio5.setChecked(false);
SnoozeRadio10.setChecked(false);

//Set Default Value based on saved preference
if (SnoozeMin == 1) {
SnoozeRadio1.setChecked(true);
}
else if(SnoozeMin == 2) {
SnoozeRadio2.setChecked(true);
}
else if(SnoozeMin == 5 ) {
SnoozeRadio5.setChecked(true);
}
else if(SnoozeMin == 10) {
SnoozeRadio10.setChecked(true);
}

//Create Media Player for sounding the system alarm
Uri alert = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(this, alert);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
mMediaPlayer.setLooping(true);
mMediaPlayer.prepare();
mMediaPlayer.start();
}
catch(Exception e) {
//TODO : Implement Error Checking
}
}

//Class for implementing the Click Event listener for the Radio Button snooze 1
public class MyRadioListener1 implements RadioButton.OnClickListener {
@Override
public void onClick(View v) {
SnoozeRadio1.setChecked(true);
SnoozeRadio2.setChecked(false);
SnoozeRadio5.setChecked(false);
SnoozeRadio10.setChecked(false);
}
}

//Class for implementing the Click Event listener for the Radio Button snooze 2
public class MyRadioListener2 implements RadioButton.OnClickListener {
@Override
public void onClick(View v) {
SnoozeRadio1.setChecked(false);
SnoozeRadio2.setChecked(true);
SnoozeRadio5.setChecked(false);
SnoozeRadio10.setChecked(false);
}
}

//Class for implementing the Click Event listener for the Radio Button snooze 5
public class MyRadioListener5 implements RadioButton.OnClickListener {
@Override
public void onClick(View v) {
SnoozeRadio1.setChecked(false);
SnoozeRadio2.setChecked(false);
SnoozeRadio5.setChecked(true);
SnoozeRadio10.setChecked(false);
}
}

//Class for implementing the Click Event listener for the Radio Button snooze 10
public class MyRadioListener10 implements RadioButton.OnClickListener {
@Override
public void onClick(View v) {
SnoozeRadio1.setChecked(false);
SnoozeRadio2.setChecked(false);
SnoozeRadio5.setChecked(false);
SnoozeRadio10.setChecked(true);
}
}

//Class for implementing the Click Event listener for the Snooze Button
public class MySnoozeListener implements Button.OnClickListener {
@Override
public void onClick(View v) {
boolean UpdatePreferences = false;

//Get AlarmEnabled Value to determine if Snooze Disable's alarm or snoozes
SharedPreferences settings = getSharedPreferences(DonnsAlarm.PREFS_NAME, 0);
boolean AlarmEnabled = settings.getBoolean(DonnsAlarm.ALARM_ENABLED, false);

//Stop Alarm Sound
try {
mMediaPlayer.stop();
}
catch(Exception e) {
//TODO : Implement Error Checking
}

//Check Alarm Enabled Preference: Enabled = Snooze Alarm, Disabled = Disarm Alarm
if (AlarmEnabled) {
//Check Snooze value and set flag to update preferences as needed
if (SnoozeRadio1.isChecked() && SnoozeMin != 1) {
SnoozeMin = 1;
UpdatePreferences = true;
} else if (SnoozeRadio2.isChecked() && SnoozeMin != 2) {
SnoozeMin = 2;
UpdatePreferences = true;
} else if (SnoozeRadio5.isChecked() && SnoozeMin != 5) {
SnoozeMin = 5;
UpdatePreferences = true;
} else if (SnoozeRadio10.isChecked() && SnoozeMin != 10) {
SnoozeMin = 10;
UpdatePreferences = true;
}

//Set Calendar Value for Snooze Alarm
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, SnoozeMin);

//Build Intent and Pending Intent to Set Snooze Alarm
Intent AlarmIntent = new Intent(AlarmActivity.this, AlarmReceiver.class);
AlarmManager AlmMgr = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent Sender = PendingIntent.getBroadcast(AlarmActivity.this, 0, AlarmIntent, 0);
AlmMgr.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), Sender);

//Update the Snooze Time Preference if flag is set
if (UpdatePreferences) {
//TODO : Save settings Enabled, Alarm Hour, Alarm Minute
SharedPreferences.Editor editor = settings.edit();
editor.putInt(DonnsAlarm.SNOOZE_MINUTE, SnoozeMin);

// Commit the edits!
editor.commit();
}
}

//Cancel the Notification. Will re-occur on next alarm occurance
NotificationManager manager = (NotificationManager)getSystemService(android.content.Context.NOTIFICATION_SERVICE);
manager.cancel(R.string.app_name);

//Close Activity
finish();
}
}

/** Destructor routine to ensure media player is cleaned up after */
@Override
protected void onDestroy() {
super.onDestroy();
//If the media player is playing stop it, and release the memory when the activity is closed.
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.stop();
}
mMediaPlayer.release();
mMediaPlayer = null;
}

}
}

18 comments:

  1. can you share the xml files, resouces or best would be to share the source code sompletely to have a better understanding..thanks in advance..please send me email at anki.cruise@gmail.com

    ReplyDelete
  2. Sorry for the extremely delayed response. I must have disabled my email notification of comments.
    Anyways, All the files are posted on box.net. Poke around my blog and you will find the links. It will include all the source files and XML layouts/resources/manifest.

    ReplyDelete
  3. you can share the ***.xml file for this code because i can't understood for the code.
    Please help me.

    ReplyDelete
  4. thank you.
    You can share Source Code Alarm clock with me.
    Please help me. my Email smart_sud@hotmail.com

    ReplyDelete
  5. Could you please post the rest of the file. I can't understand the code because the rest of the file are missing. Please help or you can email it to me at (kaybeeomm@gmail.com)

    Thanks

    ReplyDelete
  6. Check the other posts in this blog. There is a later post with the links to the full source on Box.net

    ReplyDelete
  7. please mail me this project on kpltilwani91@gmail.com because i could not find it on box.net
    thank you

    ReplyDelete
  8. Try this link - Should go directly to the folder for the current release of the code on Box
    https://www.box.com/shared/zh23rkdkzm

    ReplyDelete
  9. I downloaded the file but the R file is missing, help me pleaaaaaaaaaaase :(


    sara.alhrbi@gmail.com

    ReplyDelete
  10. R file is missing pls update the code

    ReplyDelete
  11. hi. can you please send me the source. jenyakirmiza@gmail.com

    ReplyDelete
  12. Hi ! The box link you gave is not accessible, can you put here the git hub link, or send me the source ... birooszkar@gmail.com .
    Thank you !

    ReplyDelete
    Replies
    1. Here's the github link - It's been a while since I messed with this code.
      https://github.com/DonnOMalley/MySimpleAlarmClock

      Delete
    2. Also, this Box.Net link still appears active:
      https://www.box.com/shared/zh23rkdkzm

      Delete
  13. Nice info regarding Alarm Clock 1.0 Initial Code Release my sincere thanks for sharing this post please continue to share this kind of post
    Android Training in Chennai

    ReplyDelete
  14. nice blog has been shared by you. before i read this blog i didn't have any knowledge about this but now i got some knowledge. so keep on sharing such kind of an interesting blogs.
    android training in chennai

    ReplyDelete
  15. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…

    Android Online Training

    ReplyDelete