16

I'm trying to build a personal app that will set alarms in the DeskClock app. I can get it to set alarms for anytime in the current day, But how would I go about setting an alarm for the next day, or later in the week. Looking through the AlarmClock api in android I don't see a normal way to do this. Is this even possible?

Btw this is my code for setting the alarm it might not be pretty, but I am learning as I go.

 package com.netwokz.setit;

    import java.util.Calendar;
    import java.util.GregorianCalendar;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.provider.AlarmClock;
    import android.view.Menu;
    import android.view.View;
    import android.view.View.OnClickListener;
    import android.widget.Button;
    import android.widget.EditText;

    public class MainActivity extends Activity implements OnClickListener {
    Button btnSetAlarm;
    EditText etHour, etMinute;
    int minute, hour, day;
    Calendar cal;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);
        btnSetAlarm = (Button) findViewById(R.id.btn_set_alarm);
        etHour = (EditText) findViewById(R.id.etHour);
        etMinute = (EditText) findViewById(R.id.etMinute);
        btnSetAlarm.setOnClickListener(this);

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main_activity, menu);
        return true;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_set_alarm:
                setAlarm();
                break;
        }
    }

    private void setAlarm() {
        cal = new GregorianCalendar();
        cal.setTimeInMillis(System.currentTimeMillis());
        day = cal.get(Calendar.DAY_OF_WEEK);
        hour = cal.get(Calendar.HOUR_OF_DAY);
        minute = cal.get(Calendar.MINUTE);

        Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_HOUR, hour + Integer.parseInt(etHour.getText().toString()));
        i.putExtra(AlarmClock.EXTRA_MINUTES, minute + Integer.parseInt(etMinute.getText().toString()));
        i.putExtra(AlarmClock.EXTRA_SKIP_UI, true);
        startActivity(i);
    }
}
Pararth
  • 8,114
  • 4
  • 34
  • 51
netwokz
  • 333
  • 2
  • 3
  • 5

4 Answers4

26

MainActivity.java

public class MainActivity extends Activity {

    TimePicker myTimePicker;
    Button buttonstartSetDialog;
    TextView textAlarmPrompt;
    TimePickerDialog timePickerDialog;

    final static int RQS_1 = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textAlarmPrompt = (TextView) findViewById(R.id.alarmprompt);

        buttonstartSetDialog = (Button) findViewById(R.id.startAlaram);
        buttonstartSetDialog.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                textAlarmPrompt.setText("");
                openTimePickerDialog(false);

            }
        });

    }

    private void openTimePickerDialog(boolean is24r) {
        Calendar calendar = Calendar.getInstance();

        timePickerDialog = new TimePickerDialog(MainActivity.this,
                onTimeSetListener, calendar.get(Calendar.HOUR_OF_DAY),
                calendar.get(Calendar.MINUTE), is24r);
        timePickerDialog.setTitle("Set Alarm Time");

        timePickerDialog.show();

    }

    OnTimeSetListener onTimeSetListener = new OnTimeSetListener() {

        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

            Calendar calNow = Calendar.getInstance();
            Calendar calSet = (Calendar) calNow.clone();

            calSet.set(Calendar.HOUR_OF_DAY, hourOfDay);
            calSet.set(Calendar.MINUTE, minute);
            calSet.set(Calendar.SECOND, 0);
            calSet.set(Calendar.MILLISECOND, 0);

            if (calSet.compareTo(calNow) <= 0) {
                // Today Set time passed, count to tomorrow
                calSet.add(Calendar.DATE, 1);
            }

            setAlarm(calSet);
        }
    };

    private void setAlarm(Calendar targetCal) {

        textAlarmPrompt.setText("\n\n***\n" + "Alarm is set "
                + targetCal.getTime() + "\n" + "***\n");

        Intent intent = new Intent(getBaseContext(), AlarmReceiver.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getBaseContext(), RQS_1, intent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, targetCal.getTimeInMillis(),
                pendingIntent);

    }  
}

Reciver.java

public class AlarmReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context k1, Intent k2) {
        // TODO Auto-generated method stub
         Toast.makeText(k1, "Alarm received!", Toast.LENGTH_LONG).show();

    }

}

main_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp" >

    <Button
        android:id="@+id/startAlaram"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Set Alaram Time" />

    <TextView
        android:id="@+id/alarmprompt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:textColor="#000000" />

</LinearLayout>

Manifest.xml

<application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
         <receiver android:name=".AlarmReceiver" android:process=":remote" />
    </application>
APerson
  • 8,140
  • 8
  • 35
  • 49
KeTaN
  • 724
  • 8
  • 22
  • 1
    It would be nice if pushed it to github or something and provide link, so people wouldn't have to copypaste all these pieces in order to test it. – Prostakov Apr 16 '13 at 17:07
  • 14
    Both of these answers are about AlarmManager (triggering an action every X intervals), not AlarmClock (displaying an alarm to the user). – capitalf Jul 19 '13 at 20:57
  • @KeTaN i used the same code. The recieverclass toast wont apear – Ruch1234 Sep 22 '14 at 15:36
  • @Ruch1234 this code is working perfect i have check may be you do something wrong – KeTaN Sep 24 '14 at 06:42
  • @Shadow For that you can follow this link may be you can get solution for your senario http://clearosapps.blogspot.in/p/android.html – KeTaN Feb 05 '15 at 06:45
3

Like a real alarm clock, I don't see a way to set an alarm for a future date. I think this requires one of two options:

  1. A combination of AlarmManager (to trigger an app service on the desired future date to create the alarm in AlarmClock) and then AlarmClock (to actually handle the alarm). Don't forget to listen for BOOT_COMPLETED broadcast to reset the AlarmManager alarms since they don't persist after a reboot.

  2. Use AlarmManager to trigger an app service and UI that simulates an alarm. This will require you to consider phone state and etc things you don't have to worry about with AlarmClock.

I think you can make your app just bring up the AlarmClock dialog which allows the user to set recurring alarms and other options you cannot perform through the intent.

capitalf
  • 471
  • 1
  • 6
  • 14
0

This is an old thread, but I think what you were looking for was:

https://developer.android.com/reference/android/provider/AlarmClock#EXTRA_DAYS

Bundle extra: Weekdays for repeating alarm.

Used by ACTION_SET_ALARM.

The value is an ArrayList. Each item can be:

Calendar.SUNDAY, Calendar.MONDAY, Calendar.TUESDAY, Calendar.WEDNESDAY, Calendar.THURSDAY, Calendar.FRIDAY, Calendar.SATURDAY

Constant Value: "android.intent.extra.alarm.DAYS"

This would let you pick a day in the future, but I'm not sure if it would persist the alarm or not. You might have to go back and cancel it.

Drew Delano
  • 1,421
  • 16
  • 21
-1

How about trying a pending Intent?

Just change the Calendar value to a few days or so in advance?

AlarmManager am = (AlarmManager)getSystemService(alarm);

Intent i= new Intent("MY_INTENT");
PendingIntent pi = PendingIntent.getBroadcast(this, 0, i, 0);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, 2);
am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
Siddharth
  • 9,349
  • 16
  • 86
  • 148
Hiny
  • 195
  • 7
  • 21
  • 2
    I'm trying to set an alarm in the alarm clock app, is this the same thing? I was under the impression the AlarmManager class just sets an alarm for my app. – netwokz Dec 17 '12 at 06:06
  • Also,here is a nice thread about it. http://stackoverflow.com/questions/4459058/alarm-manager-example – Hiny Dec 17 '12 at 06:08
  • 3
    Both of these answers are about AlarmManager (triggering an action every X intervals), not AlarmClock (displaying an alarm to the user). – capitalf Jul 19 '13 at 20:57