Gowtham Kumar
Gowtham Kumar

Reputation: 544

How to start an Alarm at specific Date and Time?

How to start an alarm at specific time and date, Where i got time and date using TimePicker and DatePicker . Even i can start an alarm at user specified time,but i can't do it for at user specified date. How can i reach my goal? The code which i have already done.

package com.example.modifiedalarm;
import java.util.Calendar;
import java.util.Locale;
import java.util.TimeZone;
import android.os.Bundle;
import android.provider.AlarmClock;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;

public class MainActivity extends Activity {
    Button b1, b2, b3;
    Calendar c;
    String abcd;
    TextView ed, tv;
    int hr, min, year, month, date;
    int time = 0;
    int daa = 0;

private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        b1 = (Button) findViewById(R.id.button1);
        b2 = (Button) findViewById(R.id.button2);
        b3 = (Button) findViewById(R.id.button3);
        ed = (TextView) findViewById(R.id.settime);
        tv = (TextView) findViewById(R.id.gettime);
        c = Calendar.getInstance();

        hr = c.get(Calendar.HOUR_OF_DAY);
        min = c.get(Calendar.MINUTE);
        year = c.get(Calendar.YEAR);
        month = c.get(Calendar.MONTH);
        date = c.get(Calendar.DAY_OF_MONTH);

        b2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
            i.putExtra(AlarmClock.EXTRA_MESSAGE, "New Alarm");
            i.putExtra(AlarmClock.EXTRA_HOUR, hr);
            i.putExtra(AlarmClock.EXTRA_MINUTES, min);
            startActivity(i);
}});                

        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                // showDialog(time);
                new TimePickerDialog(MainActivity.this, timeval, hr, min, true)
                        .show();

            }

        });

        b3.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                new DatePickerDialog(MainActivity.this, dateval, year, month,
                        date).show();
            }
        });
    }


    OnDateSetListener dateval = new OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int Year, int monthOfYear,
                int dayOfMonth) {
            // TODO Auto-generated method stub
            year = Year;
            month = monthOfYear;
            date = dayOfMonth;
            updatedate();
        }
    };


    OnTimeSetListener timeval = new OnTimeSetListener() {
        @Override
        public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
            // TODO Auto-generated method stub
            hr = hourOfDay;
            min = minute;
            updatetime();
        }
    };

    public void updatedate() {
        tv.setText(new StringBuilder().append(date).append("/").append(month).append("/").append(year));
        String og=tv.getText().toString();
        //int ogx=Integer.parseInt(og);
        Toast.makeText(MainActivity.this, "the date is "+og, Toast.LENGTH_LONG).show();
        datecompare();

}   private void datecompare() {

    }
private void updatetime() {
        // TODO Auto-generated method stub
        ed.setText(new StringBuilder().append(hr).append(":").append(min));
        String b=hr + ":" + min;
        }

}

For Example: i would like to set an alarm on 05-04-2013 12:00 pm .. How can i achieve that ??

Upvotes: 2

Views: 3925

Answers (2)

codeMagic
codeMagic

Reputation: 44571

Here is how I set a logout alarm for 5 minutes from now

Calendar cal1 = Calendar.getInstance(); 
cal1.add(Calendar.MINUTE, 5); 

you can do more with the date using the methods and fields available in Calendar. For example:

Calendar cal = Calendar.getInstanc();
cal.set(Calendar.MONTH, JANUARY);

to set the month. Check that link and you can see all the different ways that you can set it. Use set() to set the field (month, day, etc...) and use add() to add to the field. This should help you get started anyway

Edit

Wherever you set your pending intent just use these variables you have set as the values

    private void updatedate() {
    // TODO Auto-generated method stub
    c.set(Calendar.Month, month);            // `c` is the `Calendar` instance you defined earlier. Now we are setting the month on that instance
    c.set(Calendar.DAY_OF_MONTH, date);
    }

then when you click your Button

  b2.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         long alarmTime = cal.getTimeInMillis(); // convert your calendar instance with the dates set to millis
            Intent i = new Intent(AlarmClock.ACTION_SET_ALARM);
        i.putExtra(AlarmClock.EXTRA_MESSAGE, "New Alarm");
        i.putExtra("alarmTime", alarmTime);     //"alarmTime" will be used to get the time to set the alarm in your AlarmClock class
        startActivity(i);
}}); 

And the rest you know how to do if you are already setting a time. Hope this helps you

Upvotes: 1

Bhavesh Jethani
Bhavesh Jethani

Reputation: 3875

    AlarmManager:
    Calendar cal = Calendar.getInstance();

            long when =0; 
            intent = new Intent(this, AlarmReceiver.class);
            intent.putExtra("eventName", eventName);
            intent.putExtra("eventDescription",eventDescription);

            // Get the AlarmManager service
            AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);

            RadioGroup rg=(RadioGroup)findViewById(R.id.Setting_rgRepeatMode);
            selectedRadio=(RadioButton)findViewById(rg.getCheckedRadioButtonId());
            long repeatTime=0;

                cal.set(mYear,mMonth,mDay,mHour,mMinute,0);
                intent.putExtra("Flag",true);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
                when=cal.getTimeInMillis();
                am.set(AlarmManager.RTC_WAKEUP,when, pendingIntent);
                return;

    BroadCastReceiver:

        public class MyBroadcastReceiver extends BroadcastReceiver {
       try {
//Here you can write your logic
                    Toast.makeText(context,bundle.getString("eventName"), Toast.LENGTH_SHORT).show();

            NotificationManager notificationManager =(NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
            int icon = R.drawable.event;
            CharSequence notiText = "Event Notification";
            long time = System.currentTimeMillis();
            @SuppressWarnings("deprecation")
            Notification notification = new Notification(icon, notiText,time);
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            Intent notificationIntent = new Intent(context, Setting.class);
            PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
            notification.setLatestEventInfo(context,intent.getStringExtra("eventName"),intent.getStringExtra("eventDescription"), contentIntent);
            int SERVER_DATA_RECEIVED =  1;
            Calendar cal=Calendar.getInstance();
            Toast.makeText(context,"aavechhe "+intent.getBooleanExtra("Flag",false),Toast.LENGTH_SHORT).show();
            if(intent.getIntExtra("month",0)==cal.get(Calendar.DAY_OF_MONTH))
            {
                Toast.makeText(context,"aavechhe "+cal.get(Calendar.DAY_OF_MONTH),Toast.LENGTH_SHORT).show();
                notificationManager.notify(SERVER_DATA_RECEIVED, notification);
            }
            if(intent.getBooleanExtra("Flag",false))
                notificationManager.notify(SERVER_DATA_RECEIVED, notification);

        } catch (Exception e) {
            Toast.makeText(context, "There was an error somewhere, but we still received an alarm", Toast.LENGTH_SHORT).show();
            e.printStackTrace();

        }

Upvotes: 2

Related Questions