Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set android alarm clock programmatically

Tags:

java

android

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);
    }
}
like image 232
netwokz Avatar asked Dec 17 '12 05:12

netwokz


People also ask

How do I set repeating alarm on Android?

At the top of the main panel you should see an option to Add alarm. Tap this and you'll be presented with a time in the top half of the screen, with various settings in the lower half. Scroll the hours up or down until you reach the one you want, then repeat the process with the minutes.

How to set alarm programmatically in Android using Java?

By requesting this permission, you can set alarm programmatically using Java codes with the help of Intent. Add these permission in your AndroidManifest.xml like below: Now your application has the alarm setting permission. You may have already used intents before to start a new activity and passing data to another activity.

What is the Alarmclock intent?

The AlarmClock provider contains an Intent action and extras that can be used to start an Activity to set a new alarm or timer in an alarm clock application.

How does your app set exact alarms?

Your app can set exact alarms using one of the following methods. These methods are ordered such that the ones closer to the bottom of the list serve more time-critical tasks but demand more system resources. Invoke an alarm at a nearly precise time in the future, as long as other battery-saving measures aren't in effect.

How do I choose the right alarm clock type?

If you simply need your alarm to fire at a particular interval (for example, every half hour), use one of the elapsed real time types. In general, this is the better choice. If you need your alarm to fire at a particular time of day, then choose one of the clock-based real time clock types.


1 Answers

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>
like image 162
KeTaN Avatar answered Sep 20 '22 10:09

KeTaN