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 ??
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();
}
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
Related
I am trying to create a to-do application where user can set date and time for their tasks. Once user has define his task and has exit the application, user should get the notification from the app about the task that he has defined in the application. Below is the snippet that I've tried.
todocreate.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_todo_create);
getSupportActionBar().setTitle("ToDoList Create");
myToDoHelper = new myDBHelper(todo_create.this);
titleText = (EditText)findViewById(R.id.getTitle);
dateText = (EditText)findViewById(R.id.getDate);
timeText = (EditText)findViewById(R.id.getTime);
pickDate = (Button)findViewById(R.id.pickDate);
pickTime = (Button)findViewById(R.id.pickTime);
c = Calendar.getInstance();
pickDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mDay = c.get(Calendar.DAY_OF_MONTH);
mMonth = c.get(Calendar.MONTH);
mYear = c.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(todo_create.this, new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
dateText.setText(dayOfMonth +"-"+(month+1)+"-"+year);
c.set(Calendar.DAY_OF_MONTH,dayOfMonth);
c.set(Calendar.MONTH,month+1);
c.set(Calendar.YEAR,year);
}
}, mYear, mMonth, mDay);
datePickerDialog.show();
}
});
pickTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mHour = c.get(Calendar.HOUR_OF_DAY);
mMinute = c.get(Calendar.MINUTE);
TimePickerDialog timePickerDialog = new TimePickerDialog(todo_create.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timeText.setText(hourOfDay +":"+minute);
c.set(Calendar.HOUR_OF_DAY,hourOfDay);
c.set(Calendar.MINUTE,minute);
c.set(Calendar.SECOND,0);
c.set(Calendar.MILLISECOND,0);
}
}, mHour, mMinute, false);
timePickerDialog.show();
}
});
}
//function to save todo task with alarm manager
public void saveToDo(String todoTaskInput, String todoDateInput, String todoTimeInput){
//createNotification(todoTaskInput);
boolean isInserted = myToDoHelper.createToDo(todoTaskInput, todoDateInput,todoTimeInput);
if(isInserted == true){
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent alarmShowIntent = new Intent(this, BroadcastReceiver.class);
alarmShowIntent.putExtra("TodoTitle",todoTaskInput);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,alarmShowIntent,0);
Calendar c1 = Calendar.getInstance();
long currentTime = c1.getTimeInMillis();
alarmManager.set(AlarmManager.RTC_WAKEUP,c.getTimeInMillis()-currentTime,pendingIntent);
Toast.makeText(getApplicationContext(),"ToDo Item created successfully",Toast.LENGTH_LONG).show();
}else {
Toast.makeText(getApplicationContext(),"Error occured ! Please try again after sometime",Toast.LENGTH_LONG).show();
}
this.finish();
}
BroadcastManager.java
package com.example.mytodoapp;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
import java.io.Console;
public class BroadcastManager extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context,intent,"myToDo App",intent.getStringExtra("TodoTitle"));
}
public void createNotification(Context context,Intent intent,CharSequence ticker, CharSequence title){
//Intent intent = new Intent(this,todo_home.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
PendingIntent pendingIntent = PendingIntent.getActivity(context,0,intent,0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,"todoAppChannel");
builder.setSmallIcon(R.drawable.ic_note_add_black_24dp);
builder.setContentTitle("todo App");
builder.setContentText(title);
builder.setPriority(NotificationCompat.PRIORITY_DEFAULT);
builder.setContentIntent(pendingIntent);
builder.setAutoCancel(true);
NotificationManagerCompat notificationManagerCompat = NotificationManagerCompat.from(context);
notificationManagerCompat.notify(200,builder.build());
}
}
home.java
Created following method to create notification channel on application load.
public void createNotificationChannel(){
if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
CharSequence name = "todoAppChannel";
String description = "temp";
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel channel = new NotificationChannel("todoAppChannel",name,importance);
channel.setDescription(description);
NotificationManager manager = getSystemService(NotificationManager.class);
manager.createNotificationChannel(channel);
}
}
AndroidManifest.xml
Following line updated in the file.
<receiver android:name=".BroadcastManager"/>
I was able to generate the notification on button click but not on specific date on a specific time. However I am not able to generate notification for a specific date at specific time. What could be the problem.
You forgot to add intent filters to your receiver (correct me if I'm wrong).
<receiver
android:name="BroadcastManager">
<intent-filter>
<action android:name="ALARM" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
Also add this permission
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
I am trying to schedule a task " a toast message" to appear in the time chosen by the user, but nothing is showing after that time and i can't see what is wrong in the code.
That's my code
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//set The Calendar to to the wanted time!
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
Intent setMsg = new Intent(MainActivity.this, TaskReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setMsg, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setExact(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(), pendingIntent);
}
}
public class TaskReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "it is working!", Toast.LENGTH_SHORT).show();
}
}
If there is a better way to schedule such a task please go ahead and introduce it.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.yourcomp.yourapp.R;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TestAct extends Activity {
private static class MyHandler extends Handler{
private WeakReference<Activity> activityWr;
public MyHandler(Activity activityMain){
activityWr = new WeakReference<>(activityMain);
}
#Override
public void handleMessage(Message inputMessage) {
if (activityWr.get() != null){
Toast.makeText(activityWr.get(),"Your text",Toast.LENGTH_LONG).show();
}
}
}
private MyHandler mHandler;
private Future<?> mToastTaskRef;
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
/**
* initialize UI & take input from user && call method
*/
}
private void showToastAfterUserSpecifiedDelay(int seconds){
mToastTaskRef = Executors.newScheduledThreadPool(NUMBER_OF_CORES).scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
mHandler.sendMessage(new Message());
}
}, /**initial delay*/60
,/**time*/seconds
,/**time unit*/ TimeUnit.MILLISECONDS);
}
private void stopToastTask(){
if (mToastTaskRef != null && !mToastTaskRef.isCancelled() && !mToastTaskRef.isDone()){
mToastTaskRef.cancel(true); //tru -- >interrupt even if it's running
}
}
}
Use this in your code Instead of manager.setExact method as follows:
manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);
I have to show calender using DatePickerDialog.
The below code is used:
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.TextView;
import android.widget.Toast;
public class DatePickerExample extends Activity {
private TextView Output;
private Button changeDate;
private Boolean mEnableNativeCalGridView = null;
String timeZone;
public static TimeZone tz;
private int year;
private int month;
DatePickerDialog d;
public Calendar c;
SimpleDateFormat sdf;
private int day;
public static IntentFilter s_intentFilter;
static final int DATE_PICKER_ID = 1111;
static{
s_intentFilter = new IntentFilter();
s_intentFilter.addAction(Intent.ACTION_TIME_TICK);
s_intentFilter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
s_intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
registerReceiver(m_timeChangedReceiver, s_intentFilter);
Output = (TextView) findViewById(R.id.Output);
changeDate = (Button) findViewById(R.id.changeDate);
// sdf = new SimpleDateFormat("EEE, MMM d, ''yy");//Wed, Jul 4, '01
// Show current date
Output.setText(new StringBuilder()
// Month is 0 based, just add 1
.append(month + 1).append("-").append(day).append("-")
.append(year).append(" "));
// Button listener to show date picker dialog
changeDate.setOnClickListener(new OnClickListener() {
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
// On button click show datepicker dialog
showDialog(DATE_PICKER_ID);
}
});
}
#Override
protected void onPrepareDialog(int id, Dialog dialog) {
switch (id) {
case DATE_PICKER_ID:
((DatePickerDialog) dialog).updateDate(
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH));
}
}
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DATE_PICKER_ID:
// open datepicker dialog.
// set date picker for current date
// add pickerListener listner to date picker
sdf = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
c= Calendar.getInstance();
c.setTimeZone(tz);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
d = new DatePickerDialog(DatePickerExample.this, pickerListener, year, month,day);
setMinMaxdate();
return d;
}
return null;
}
////////////////////Fix for issue on OS 5.1 //////////////////////
public long getDateFormatted(String date){
String givenDateString = date;
long timeInMilliseconds = 0;
try {
Date mDate = sdf.parse(givenDateString);
timeInMilliseconds = mDate.getTime();
System.out.println("Date in milli :: " + timeInMilliseconds);
} catch (ParseException e) {
e.printStackTrace();
}
return timeInMilliseconds;
}
//////////////////////////////////////////
private DatePicker.OnDateChangedListener newchange= new OnDateChangedListener(){
#Override
public void onDateChanged(DatePicker view,
int year, int monthOfYear,int dayOfMonth) {
Toast.makeText(getApplicationContext(),
"onDateChanged", Toast.LENGTH_SHORT).show();
}};
DatePicker datePicker;
public void setMinMaxdate() {
//Time zone calculation
//TimeZone.setDefault(tz);
///////////////////////
long calEvtEndDate= getDateFormatted("Sun May 31 23:59:59 "+timeZone+" 2015");//System.currentTimeMillis();
long calEvtStartDate= getDateFormatted("Wed May 13 00:00:00 "+timeZone+" 2015");//System.currentTimeMillis()/2;
// long calEvtEndDate = getDateFormatted("Sun, may 31, '15");
//long calEvtStartDate = getDateFormatted("Wed, may 13, '15");
if(d != null){
datePicker = d.getDatePicker();
if(mEnableNativeCalGridView != null){
datePicker.setCalendarViewShown(mEnableNativeCalGridView.booleanValue());
}
// If Start Date is Greater than End Date then we are showing from valid StartDate
// value and we are not setting the maxdate.
if (calEvtStartDate > calEvtEndDate) {
datePicker.setMinDate(calEvtStartDate);
} else {
if (calEvtStartDate > 0) { // If Only ValidStart date is provided, then setting the minDate.
datePicker.setMinDate(calEvtStartDate);
}
if (calEvtEndDate > 0) { // If Only ValidEnd date is provided, then setting the maxDate.
datePicker.setMaxDate(calEvtEndDate);
}
}
}
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
System.out.println("-------resumed");
}
public DatePickerDialog.OnDateSetListener pickerListener = new DatePickerDialog.OnDateSetListener() {
// when dialog box is closed, below method will be called.
#Override
public void onDateSet(DatePicker view, int selectedYear,
int selectedMonth, int selectedDay) {
//view.updateDate(year, month, day);
System.out.println("---------------datesetchange");
year = selectedYear;
month = selectedMonth;
day = selectedDay;
// Show selected date
Output.setText(new StringBuilder().append(month + 1)
.append("-").append(day).append("-").append(year)
.append(" "));
}
};
public void onDestroy() {
super.onDestroy();
unregisterReceiver(m_timeChangedReceiver);
}
private final BroadcastReceiver m_timeChangedReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(Intent.ACTION_TIME_CHANGED) ||
action.equals(Intent.ACTION_TIMEZONE_CHANGED))
{
System.out.println("timezone changed---"+action.toString());
tz = TimeZone.getDefault();
System.out.println("TimeZone "+tz.getDisplayName(false, TimeZone.SHORT)+" Timezon id :: " +tz.getID());
timeZone = tz.getDisplayName(false, TimeZone.SHORT);
// Intent intent1 = getIntent();
// finish();
// startActivity(intent1);
showDialog(DATE_PICKER_ID);
}
}
};
}
When the app is running, I go to the settings and change the Timezone to such a value so that the current date will change. Now when we select any date in the dialog, it behaves abnormally and goes to other date. I have used setMinDate() and setMaxDate() methods. This happens only in Android OS 5.1.
Any idea or help? Thanks in advance.
I am creating alarm alert for appointment reminder for that I am using following code.Code is working very well it showing me alarm alert but only problem is that, it is not differentiate alarm between am and pm, suppose if I set alarm for 7am and currently 7pm in device then also my alert dialog shows. How can I manage that am and pm? I used this link for ref
http://wptrafficanalyzer.in/blog/setting-up-alarm-using-alarmmanager-and-waking-up-screen-and-unlocking-keypad-on-alarm-goes-off-in-android/
AlertDemo.class
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.WindowManager.LayoutParams;
public class AlertDemo extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
}
});
/** Creating the alert dialog window */
return builder.create();
}
/** The application should be exit, if the user presses the back button */
#Override
public void onDestroy() {
super.onDestroy();
getActivity().finish();
}
}
Appointment.class
import java.text.DateFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TimePicker;
import android.widget.Toast;
public class Appointment extends Activity {
Button date, time, save;
private static final int DIALOG_DATE = 1;
private static final int DIALOG_TIME = 2;
private int year;
private int month;
private int day;
int i;
String strmonth, strday, stryear;
String months[] = { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December" };
int intmonth, intday, intyear, inthour, intminutes;
Calendar c = Calendar.getInstance();
private SimpleDateFormat timeFormatter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.doctor_appointment);
year = c.get(Calendar.YEAR);
month = c.get(Calendar.MONTH);
day = c.get(Calendar.DAY_OF_MONTH);
date = (Button) findViewById(R.id.btnsetdate);
time = (Button) findViewById(R.id.btnsettime);
save = (Button) findViewById(R.id.btnsave);
timeFormatter = new SimpleDateFormat("hh:mm a");
// c.set(Calendar.MONTH, 4);
date.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_DATE);
}
});
time.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
showDialog(DIALOG_TIME);
}
});
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent("com.example.healthmanager.DemoActivity");
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(
getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext()
.getSystemService(ALARM_SERVICE);
String strtime = time.getText().toString();
Log.v("str btntime", strtime);
String[] splitstrtime = strtime.split(":");
Log.v("timestr1", splitstrtime[0]);
Log.v("timestr2", splitstrtime[1]);
int splithour = Integer.parseInt(splitstrtime[0]);
String[] splitsecond = splitstrtime[1].split(" ");
Log.v("split str second", splitsecond[0]);
int splitmin = Integer.parseInt(splitsecond[0]);
/**
* Creating a calendar object corresponding to the date and time
* set by the user
*/
// GregorianCalendar calendar = new
// GregorianCalendar(year,month,day, hour, minute);
GregorianCalendar calendar = new GregorianCalendar(intyear,
intmonth, intday, splithour, splitmin);
/**
* Converting the date and time in to milliseconds elapsed since
* epoch
*/
long alarm_time = calendar.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager
.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",
Toast.LENGTH_SHORT).show();
}
});
}
// For date dialog
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_DATE:
return new DatePickerDialog(this, datePickerListener, year, month,
day);
case DIALOG_TIME:
return new TimePickerDialog(this, new OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
time.setText(timeFormatter.format(c.getTime()));
}
}, c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE), false);
}
return null;
}
// For date
private DatePickerDialog.OnDateSetListener datePickerListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year1, int monthOfYear,
int dayOfMonth) {
year = year1;
month = monthOfYear;
day = dayOfMonth;
// date.setText(dateFormatter.format(dateTime.getTime()));
updateDisplay();
}
};
public String getMonthForInt(int m) {
String month = "invalid";
DateFormatSymbols dfs = new DateFormatSymbols();
String[] months = dfs.getMonths();
if (m >= 0 && m <= 11) {
month = months[m];
}
return month;
}
private void updateDisplay() {
// String strDOB = month + 1 + "/" + day + "/" + year;
// Log.v("strDOB : ", strDOB);
intmonth = month;
intday = day;
intyear = year;
strmonth = Integer.toString(intmonth);
strday = Integer.toString(intday);
stryear = Integer.toString(intyear);
Log.v("month value", strmonth);
Log.v("day value", strday);
Log.v("year value", stryear);
// int one=7;
// Log.v("string limit",one.length());
for (i = 0; i < intmonth; i++) {
String strone = Integer.toString(intmonth);
strone = months[i];
// String intmonth=Integer.toString(months);
}
Log.v("month value", months[i].toString());
date.setText(months[i] + " " + day + "," + year);
}
}
DemoActivity.class
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
You are not handling the AM/PM. Just put these lines of code...
int timeDifference=0;
String ampm=splitampmtime[1];
if(ampm.matches("PM")){
timeDifference=12;
}
int splithour = timeDifference+Integer.parseInt(splitstrtime[0]);
String[] splitsecond = splitstrtime[1].split(" ");
Well you can add the check for AM and PM in your save.setOnClickListener() and change the value of hour accordingly:
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
.....
int splithour = Integer.parseInt(splitstrtime[0]); //10
String[] splitsecond = splitstrtime[1].split(" "); //40, am
Log.v("split str second", splitsecond[0]);
int splitmin = Integer.parseInt(splitsecond[0]); //40
if(splitsecond[1].equalsIgnoreCase("pm")) {
splithour += 12;
} else if(splitsecond[1].equalsIgnoreCase("am") && splithour == 12) {
splithour = 0;
}
....
}
}
Please use:-
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + alarm_time,
operation);
in place of
alarmManager.set(AlarmManager.RTC_WAKEUP, alarm_time, operation);
Read:-
SystemClock.elapsedRealtime() is the current time in millis add the total time to skip from now to alarm in millis.
I used to set the alarm using this method:
/**
* Set the Alarm
*
* #param context the activity context
* #param id the alarm ID for this app
* #param hour the alarm hour
* #param minute the alarm minute
* #param timeZone the timezone am = Calendar.AM or pm = Calendar.PM
*/
public static void setAlarm(Context context, int id, int hour, int minute, int timeZone) {
AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR, hour);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, timeZone);
Intent intent = new Intent(context, PopupActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(context, id, intent, 0);
alarm.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 10, pIntent);
}
Not able to get the notification for particular date set using calendar class .
I have set the year, date time, month , second using calendar class, Not able to get Notification.
any help would be appreciated , Below is the code snippet.
public class CalActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Intent chartNotifier = new Intent(CalActivity.this,
CRT.class);
PendingIntent pendingIntent = PendingIntent
.getBroadcast(
CalActivity.this,
234324243,
chartNotifier,
PendingIntent.FLAG_UPDATE_CURRENT);
Calendar calendar = Calendar.getInstance();
//calendar.set(year, month, day, hour, min, 0);
//calendar.set(2012, 8, 15, 12, 18,0);
calendar.set(Calendar.YEAR,2012);
calendar.set(Calendar.MONTH, 8-1);
calendar.set(Calendar.DAY_OF_MONTH,15);
calendar.set(Calendar.HOUR, 12);
calendar.set(Calendar.MINUTE,32);
calendar.set(Calendar.SECOND, 15);
long when =calendar.getTimeInMillis();
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP,when,
pendingIntent);
}
}
Receiver Class
public class CRT extends BroadcastReceiver {
String trainNo, journeyDate;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
System.out.println("Has arrived inside Receiver");
// Call Service
Intent service = new Intent(context, ChartNotifierService.class);
context.startService(service);
}
}
Service class is
package com.cal;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
public class ChartNotifierService extends Service {
String trainNo;
String journeyDate;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) ChartNotifierService.this
.getSystemService(ns);
long when = System.currentTimeMillis();
Notification notification = new Notification(R.drawable.ic_launcher, "Time",
when);
notification.flags |= Notification.FLAG_INSISTENT
| Notification.FLAG_AUTO_CANCEL;
Intent enterPnr = new Intent(ChartNotifierService.this, CalActivity.class);
enterPnr.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent enterIntent = PendingIntent.getActivity(
ChartNotifierService.this, 0, enterPnr, 0);
notification.setLatestEventInfo(ChartNotifierService.this, "Date",
"time", enterIntent);
notificationManager.notify(0, notification);
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
}
Change
Calendar.setField(Calendar.HOUR, xx)
to
Calendar.setField(Calendar.HOUR_OF_DAY, xx)