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"/>
Related
Hi i am currently working on application of reminder in android and using Firebase as database. My reminder is getting set properly without any issue but when i retrieve data from Firebase, i'am getting data of particular date but don't know how to ring it on time that user had entered.
This is my code :
Miscelleneous.java
package com.example.dell.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Miscelleneous extends Activity {
private static Button setting,resetting;
private EditText text;
private TextView rem1,date1,time1;
private FirebaseDatabase fdb;
private DatabaseReference db5;
private Button btn1,btn2;
private DatePickerDialog.OnDateSetListener dateSetListener;
private TimePickerDialog.OnTimeSetListener timeSetListener;
String strDate;
String timeString = "";
public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.miscelleneous);
setting = (Button)findViewById(R.id.remset);
Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
text = (EditText)findViewById(R.id.editText);
btn1 = (Button)findViewById(R.id.selectdate);
btn2 = (Button)findViewById(R.id.selecttime);
rem1 = (TextView)findViewById(R.id.rem1);
date1 = (TextView)findViewById(R.id.date1);
time1 = (TextView)findViewById(R.id.time11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
month = month - 1;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
strDate = format.format(calendar.getTime());
// date = day + "/" + month + "/" + year;
btn1.setText(strDate);
}
};
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
//int second = cal.get(Calendar.SECOND);
TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
tdialog.show();
}
});
timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
//String timeString = "";
if (hours_x == 0) {
timeString = "12:"+minute_x+" "+"a.m.";
btn2.setText(timeString);
} else if (hours_x < 12) {
timeString = hours_x + ":" + minute_x +" "+ "a.m.";
btn2.setText(timeString);
} else if (hours_x == 12) {
timeString = hours_x+":"+minute_x+" "+"p.m.";
btn2.setText(timeString);
} else {
timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
btn2.setText(timeString);
}
}
};
db5 = FirebaseDatabase.getInstance().getReference().child("user1");
setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(text.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
}
else if(btn1.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
}
else if(btn2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
}
else{
final HashMap<String,String> adddata = new HashMap<String, String>();
adddata.put("Reminder",text.getText().toString());
adddata.put("Date",btn1.getText().toString());
adddata.put("Time",btn2.getText().toString());
db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),
"Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(),
"Problem in reminder setting !!",Toast.LENGTH_LONG).show();
}
}
});
retrive();
/*Intent intent = new Intent(Miscelleneous.this,History.class);
intent.putExtra(REM_KEY,validate1);
intent.putExtra(DATE_KEY,validate2);
intent.putExtra(TIME_KEY,validate3);
startActivity(intent);*/
//send();
}
}
});
}
/*private void send(){
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(validate1);
arrayList.add(validate2);
arrayList.add(validate3);
Intent i = new Intent(Miscelleneous.this,History.class);
i.putExtra(REM_KEY,arrayList);
startActivity(i);
}*/
private void retrive(){
long current_date = System.currentTimeMillis();
long current_time = System.currentTimeMillis();
// String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
String System_Date = sdf.format(current_date);
final String System_Time = sdf1.format(current_time);
String usrdate = btn1.getText().toString().trim();
final String usrtime = btn2.getText().toString().toLowerCase().trim();
// Log.d("Miscelleneous",usrtime);
// Log.d("Miscelleneous",usrdate);
if( System_Date.equals(usrdate)){
db5.child("Users Own").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tim="",date="",remind="";
for (DataSnapshot cdata:dataSnapshot.getChildren()) {
remind = cdata.getValue(String.class).toString();
date = cdata.getValue(String.class).toString();
tim = cdata.getValue(String.class).toString();
}
if(usrtime.equals(System_Time)){
Log.d("Miscelleneous","actual reminder");
Log.d("Miscelleneous","Date:"+remind);
Log.d("Miscelleneous","Reminder:"+date);
Log.d("Miscelleneous","Time:"+tim);
rem1.setText("Reminder : "+remind);
date1.setText("Date : "+date);
time1.setText("Time : "+tim);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
}
}
}
Can anyone give me a solution please,
Thanks
you can use AlarmManager to ringing or notify user at particular time.
private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;
public void setTimings(){
private Calender alarmCalender = Calendar.getInstance();
alarmCalender.setTimeInMillis(System.currentTimeMillis());
alarmCalender.set(Calendar.HOUR_OF_DAY, "hour"); // hour=07
alarmCalender.set(Calendar.MINUTE, "minute"); // minute=01
alarmCalender.set(Calendar.SECOND, "second"); // second=0
alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0
setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);
}
public void setAlarm(int type, Calendar calendar, long timeInMillis){
alarmIntent = new Intent(context, yourBroadcastReciever.class);
pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}
To handle the alarm at particular time you create the Reciever
yourBroadcastReciever.class
#Override
public void onReceive(Context context, Intent intent) {
// here you handle the task when alarm ringing
}
[Note: Intent and Pending Intent is compulsory for create an Alarm]
use a broadcast receiver and set the time which you are getting.
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);
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
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)