Setting alarm notifications with toggle button - Android - java

I have a togglebutton in the main activity which enables alarm. aid is a unique key.
I need to have an alarm notification when the togglebutton is enabled so on that particular date the alarm will go. When the toggle button is offed the alarm should be canceled.
When the togglebutton is on the toast is not coming. which means the BroadcastReceiver is not called.
But when the toggle is offed the toast comes.
btnToggle.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (btnToggle.isChecked()) {
AddReminder reminder = new AddReminder(year,
month, day, hour,
min, body, context, aid);
reminder.setNotification();
} else {
AddReminder reminder = new AddReminder(context, mtchid);
reminder.offNotification();
}
}
});
This is the AddReminder Class I coded
public class AddReminder {
private String formattedYear;
private String formattedMonth;
private String formattedDay;
private String formattedHour;
private String formattedMin;
private String body;
private Context context;
private String aid;
private int mYear;
private int mMonth;
private int mDay;
private int mHour;
private int mMin;
private int alrmId = 0;
int aID;
public AddReminder(Context c, String aid){
this.context = c;
this.aid = aid;
aID = Integer.parseInt(aid);
}
public AddReminder(String year, String month, String day, String hour, String min, String body, Context c, String aid){
this.formattedYear = year;
this.formattedMonth = month;
this.formattedDay = day;
this.formattedHour = hour;
this.formattedMin = min;
this.body = body;
this.context = c;
this.aid = aid;
aID = Integer.parseInt(aid);
}
public void setNotification(){
Calendar c = Calendar.getInstance();
mYear = Integer.parseInt(formattedYear);
mMonth = Integer.parseInt(formattedMonth);
mDay = Integer.parseInt(formattedDay) - 1;
mHour = Integer.parseInt(formattedHour);
mMin = Integer.parseInt(formattedMin);
//set Reminder time and date into calendar object
c.set(Calendar.YEAR,mYear);
c.set(Calendar.MONTH, mMonth);
c.set(Calendar.DATE, mDay);// 1 days before
c.set(Calendar.HOUR_OF_DAY, mHour);
c.set(Calendar.MINUTE, mMin);
c.set(Calendar.SECOND, 0);
alrmId = Integer.parseInt(mMonth + "" + mDay + "" + mHour + ""
+ mMin);
Intent in = new Intent(context, ReminderReceiver.class);
in.putExtra("body", body);
in.putExtra("AlrmId", alrmId);
in.putExtra("aid",aid);
PendingIntent sender = PendingIntent.getBroadcast(context, aID, in, PendingIntent.FLAG_CANCEL_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), sender);
}
public void offNotification(){
Intent intent = new Intent(context, ReminderReceiver.class);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
PendingIntent pi = PendingIntent.getBroadcast(context, aID, intent,0);
am.cancel(pi);
}
}
This is the broadcast Receiver class
public class ReminderReceiver extends BroadcastReceiver {
String body;
String AlrmId;
String id;
String aid;
#Override
public void onReceive(Context context, Intent intent) {
body = intent.getStringExtra("body");
AlrmId = intent.getStringExtra("AlrmId");
aid = intent.getStringExtra("aid");
Toast.makeText(context, body+"/"+AlrmId+"/"+id+"/"+aid, Toast.LENGTH_SHORT).show();
}
}

The Toast is not shown because it´s not the time for it. The BroadcastReceiver is reached when the alarmManager fires the message at the given time. So to make the simple message when the alarm is turned on, do it inside the setNotification() event:
public void setNotification(){
//Your code
.
.
.
Toast.makeText(context,"ALARM IS ON", Toast.LENGTH_SHORT().show();
}

Related

why I don't get extra from intent in onReceive method of the brodcastReceiver?

I have weird problem woke me up full night, any extra data put in intent in Broadcast, I don't find it later in the Broadcast receiver
here is alarming class ( sender)
private class Alarming {
private AlarmManager alarmManager;
private Intent intent;
private PendingIntent pendingIntent;
Alarming() {
intent = new Intent(TimetableActivity.this, SessionAlarm.class);
alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
}
public void setSessionAlarm(FiredAlarm firedAlarm) {
/*
we will correct day of month if needed, so we roll elapsed date
to avoid instant alarming.
*/
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(firedAlarm.getDateInMillis());
Calendar now = Calendar.getInstance();
if (calendar.before(now)) {//if session date is before today
calendar.set(Calendar.YEAR, now.get(Calendar.YEAR));
calendar.set(Calendar.WEEK_OF_YEAR, now.get(Calendar.WEEK_OF_YEAR));
}
firedAlarm.setDateInMillis(calendar.getTimeInMillis());
Bundle args = new Bundle();
args.putParcelable(FIRED_ALARM_KEY, firedAlarm);
intent.putExtras(args);
intent.putExtra("INT", 54);
pendingIntent =
PendingIntent.getBroadcast(TimetableActivity.this, firedAlarm.getRequestedCode(), intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
firedAlarm.getDateInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES / 5, pendingIntent);
}
}
and here is the broadcast receiver, intent can't receive any kinds of data, primitive, bundle, parcelable...etc
public class SessionAlarm extends BroadcastReceiver {
private static final String TAG = "session_alarm_tag";
public static final String FIRED_ALARM_KEY = "fired_alarm_key";
FiredAlarm firedAlarm;
int requestCode;
#Override
public void onReceive(Context context, Intent intent) {
Log.i(TAG, " Received Integer : " + intent.getIntExtra("INT", -1));
Bundle bundle = intent.getExtras();
firedAlarm = bundle.getParcelable(FIRED_ALARM_KEY);
if (firedAlarm != null) {
//TODO Blabla...
} else Log.i("onReceive", "no parcelable fired alarm found!");
}
private void createNotification(Context context, FiredAlarm firedAlarm) {
//TODO
}
Here is FiredAlarm class :
public class FiredAlarm implements Parcelable {
private int requestedCode;
private long dateInMillis;
private String classroom;
private int duration;
public String getClassroom() {
return classroom;
}
public void setClassroom(String classroom) {
this.classroom = classroom;
}
public int getDuration() {
return duration;
}
public void setDuration(int duration) {
this.duration = duration;
}
public FiredAlarm(int requestedCode, long dateInMillis) {
this.requestedCode = requestedCode;
this.dateInMillis = dateInMillis;
}
public void setRequestedCode(int requestedCode) {
this.requestedCode = requestedCode;
}
public void setDateInMillis(long dateInMillis) {
this.dateInMillis = dateInMillis;
}
public int getRequestedCode() {
return requestedCode;
}
public long getDateInMillis() {
return dateInMillis;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.requestedCode);
dest.writeLong(this.dateInMillis);
dest.writeString(this.classroom);
dest.writeInt(this.duration);
}
public void readFromParcel(Parcel source) {
this.requestedCode = source.readInt();
this.dateInMillis = source.readLong();
this.classroom = source.readString();
this.duration = source.readInt();
}
protected FiredAlarm(Parcel in) {
this.requestedCode = in.readInt();
this.dateInMillis = in.readLong();
this.classroom = in.readString();
this.duration = in.readInt();
}
public static final Parcelable.Creator<FiredAlarm> CREATOR = new Parcelable.Creator<FiredAlarm>() {
#Override
public FiredAlarm createFromParcel(Parcel source) {
return new FiredAlarm(source);
}
#Override
public FiredAlarm[] newArray(int size) {
return new FiredAlarm[size];
}
};
}
I always get negative result, no data, is it really a bug on new SDK 30 level or what?
I disabled sending object, so primitive worked, obviously I'm gonna convert my object to bytes. that solution will work as it's confirmed all the time.

I want to make Background Service to add item to RecyclerView every 24 hours

I'm trying to start a service that adds an item to RecyclerView every 24 hours (every day). I used this code but it doesn't work:
BackgroundService.java
public class BackgroundService extends Service {
private boolean isRunning;
private Context context;
private Thread backgroundThread;
SharedPreferences pref;
String isMorningChecked;
String isEveningChecked;
String isNightChecked;
String isEchuraistChecked;
String isConfessChecked;
String isBibleChecked;
String Date;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
this.context = this;
this.isRunning = false;
this.backgroundThread = new Thread(addNewNote);
}
private Runnable addNewNote = new Runnable() {
#Override
public void run() {
Log.e("isRunning", "Yeeeeeeeeeees!");
pref = getApplicationContext().getSharedPreferences("checkStates", 0);
String checkMorningState = pref.getString("morning", "False");
String checkEveningState = pref.getString("evening", "False");
String checkNightState = pref.getString("night", "False");
String checkEchuraistState = pref.getString("echuraist", "False");
String checkConfessState = pref.getString("confess", "False");
String checkBibleState = pref.getString("bible", "False");
String writeYourNotes = pref.getString("writeNotes", "");
SimpleDateFormat sdf = new SimpleDateFormat("E", new Locale("ar"));
final SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy.MM.dd");
final Timestamp timestamp = new Timestamp(System.currentTimeMillis());
Date = sdf2.format(timestamp).toString();
if(checkMorningState.equals("True")){
isMorningChecked = "+";
}else{
isMorningChecked = "-";
}
if(checkEveningState.equals("True")){
isEveningChecked = "+";
}else{
isEveningChecked = "-";
}
if(checkNightState.equals("True")){
isNightChecked = "+";
}else{
isNightChecked = "-";
}
if(checkEchuraistState.equals("True")){
isEchuraistChecked = "+";
}else{
isEchuraistChecked = "-";
}
if(checkConfessState.equals("True")){
isConfessChecked = "+";
}else{
isConfessChecked = "-";
}
if(checkBibleState.equals("True")){
isBibleChecked = "+";
}else{
isBibleChecked = "-";
}
AppDatabase db = Room.databaseBuilder(getApplicationContext(), AppDatabase.class, "Note").allowMainThreadQueries().build();
db.userDao().insertAll(new Note(sdf.format(timestamp), sdf2.format(timestamp).toString(), isMorningChecked, isEveningChecked, isNightChecked, isEchuraistChecked, isConfessChecked, isBibleChecked, writeYourNotes));
stopSelf();
}
};
#Override
public void onDestroy() {
super.onDestroy();
this.isRunning = false;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!this.isRunning){
this.isRunning = true;
this.backgroundThread.start();
}
return START_STICKY;
}
}
BoardCastReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
context.startService(new Intent(context, BackgroundService.class));
}
}
Home.java
Intent alarm = new Intent(this, AlarmReceiver.class);
boolean alarmRunning = ((PendingIntent.getBroadcast(this,0,alarm,PendingIntent.FLAG_NO_CREATE)) != null);
if(alarmRunning == false){
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,0,alarm,0);
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), 1000, pendingIntent);
I have tried this but the Service works once or twice and then it stops and sometimes it gives me the following error:
java.lang.IllegalStateException: Not allowed to start service Intent
Background service can not be used for long running tasks on Android 8.0 onwards. Please use JobScheduler API or Workmanager to achieve the desired results. Consult the following link for details.
https://developer.android.com/topic/libraries/architecture/workmanager

Alarm manager not working for multiple Alarm in Android

I want to use alarm based on some database time value . Currently my alarm is working for one alarm Like : I have 3 alarm set at 8:30am , 10:20am and 12:20Pm
my alarm is working only for one value .This is reminder class there i am creating the alarm
public class OwnGoalReminder extends EventReminder {
GoalOwn goalOwn;
int interValTime;
int goalId;
int hour;
int minute;
int requestCode;
String type;
public void setInterValTime(int interValTime) {
this.interValTime = interValTime;
}
public int getHour() {
return hour;
}
public void setHour(int hour) {
this.hour = hour;
}
public void setRequestCode(int requestCode) {
this.requestCode = requestCode;
}
public void setType(String type) {
this.type = type;
}
public int getMinute() {
return minute;
}
#Override
protected int getGoalId(){return this.goalId;}
public void setMinute(int minute) {
this.minute = minute;
}
public OwnGoalReminder(Context context , int goalId, int interValTime){
super(context);
this.interValTime = interValTime;
this.goalId = goalId;
}
#Override
protected String getType() {
return this.type;
}
#Override
protected String getMessage() {
return "Reminder!!! You should check your goals!";
}
#Override
protected int getRequestCode() {
return requestCode;
}
#Override
protected EventTime getEventTime() {
int h = hour;
int m = minute;
return new EventTime(hour,minute,interValTime);
}
#Override
protected Class getBroadcastReceiver() {
return MyBroadcastReceiver.class;
}
}
This is base class of OwnGOalReminder
public abstract class EventReminder{
protected Context context;
protected Alarm alarm;
PushNotificationsManager notificationsManager;
public void remind() {
Bundle bundle = new Bundle();
bundle.putString("type", getType());
bundle.putString("msg", getMessage());
notificationsManager.sendNotification(bundle);
}
protected abstract String getType();
protected abstract String getMessage();
protected abstract int getRequestCode();
protected abstract int getGoalId();
protected abstract EventTime getEventTime();
protected abstract Class getBroadcastReceiver();
protected EventReminder(Context context){
this.context = context;
alarm = new Alarm(context, getBroadcastReceiver());
notificationsManager = new PushNotificationsManager(context);
}
public void startReminder(){
alarm.startAlert(getRequestCode(), getGoalId(), getEventTime().hour, getEventTime().minute, getEventTime().intervalInMinute);
//alarm.setAlarm(context, getEventTime().hour, getEventTime().minute);
}
protected class EventTime{
int hour, minute, intervalInMinute;
public EventTime(int hour, int minute, int intervalInMinute){
this.hour = hour;
this.minute = minute;
this.intervalInMinute = intervalInMinute;
}
}
}
this is alarm class there i am creating the alarmmanager
public class Alarm{
private final Context context;
private Class broadcastReceiver;
public Alarm(Context context, Class broadcastReceiver){
this.context = context;
this.broadcastReceiver = broadcastReceiver;
}
public void startAlert(int requestCode, int gid, int hour, int minute, int intervalMinute) {
Log.d(this.getClass().getName(), "starting alert");
int i = 10;
Long timeToMilliSeconds = timeToMilliSeconds(hour, minute);
Intent intent = new Intent(context, MyBroadcastReceiver.class);
intent.putExtra("reqcode", requestCode);
intent.putExtra("time", timeToMilliSeconds);
intent.putExtra("gid" , gid);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, timeToMilliSeconds+
+ (i * 1000), 1000*60*intervalMinute, pendingIntent);
//Toast.makeText(context, "Alarm set in " + i + " seconds",Toast.LENGTH_LONG).show();
}
#NonNull
public static long timeToMilliSeconds(int hour, int minute) {
Date dat = new Date();//initializes to now
Calendar cal_alarm = Calendar.getInstance();
Calendar cal_now = Calendar.getInstance();
cal_now.setTime(dat);
cal_alarm.setTime(dat);
cal_alarm.set(Calendar.HOUR_OF_DAY,hour);//set the alarm time
cal_alarm.set(Calendar.MINUTE, minute);
cal_alarm.set(Calendar.SECOND,0);
if(cal_alarm.getTimeInMillis() < System.currentTimeMillis()){
cal_alarm.add(Calendar.DAY_OF_YEAR,1);
}
return cal_alarm.getTimeInMillis();
}
}
This is the method here i am creating the multiple alarm object based on database value
public static void registerAlarm(Context context){
if(!UserPreferences.isAlarmRegistered(context)) {
GoalReminder goalReminder = new GoalReminder(context);
AppraisalReminder appraisalReminder = new AppraisalReminder(context);
goalReminder.startReminder();
appraisalReminder.startReminder();
// ownGoalReminder.startReminder();
//UserPreferences.setIsAlarmRegistered(context,true);
ArrayList<Goal> LIST_OF_OWN_GOALS = new ArrayList<>();
LIST_OF_OWN_GOALS = (ArrayList<Goal>) Goal.getGoalFromOwnGoals();
for (Goal g : LIST_OF_OWN_GOALS) {
OwnGoalReminder ownGoalReminder = new OwnGoalReminder(context , g.getgId(),3 );
int h = Integer.parseInt(g.getrTime())/60;
int min = Integer.parseInt(g.getrTime())%60;
ownGoalReminder.setHour(h);
ownGoalReminder.setMinute(min);
ownGoalReminder.setRequestCode(16);
ownGoalReminder.setType("16");
ownGoalReminder.startReminder();
LIST_OF_OWN_REMINDERS.add(ownGoalReminder);
}
}
}
This is my Broadcast receiver class :
public class MyBroadcastReceiver extends BroadcastReceiver {
private static final String[] goalMessagesArray = ApraiseApplication.getContext().getResources().getStringArray(R.array.goals_messages);
private static Queue<String> goalMessagesQueue = new ArrayDeque<>(Arrays.asList(goalMessagesArray));
private static final String[] appraisalsMessagesArray = ApraiseApplication.getContext().getResources().getStringArray(R.array.appraisals_messages);
private static Queue<String> appraisalsMessagesQueue = new ArrayDeque<>(Arrays.asList(appraisalsMessagesArray));
#Override
public void onReceive(Context context, Intent intent) {
Log.d(this.getClass().getName(), "notify");
PushNotificationsManager notificationsManager = new PushNotificationsManager(context);
PowerManager.WakeLock wl = acquireWakeLock(context);
int requestCode = intent.getIntExtra("reqcode",1);
int gId = intent.getIntExtra("gid",1);
long time = intent.getLongExtra("time",0);
String message = "";
// it will create the instance of Random class
Random randomGenerator = new Random();
// it will generate a random number based on goal message arrayList length
int indexForGoalMessage = randomGenerator.nextInt(goalMessagesArray.length);
// it will generate a random number based on appraisalsMessagesArray length
int indexForAppraisalsMessage = randomGenerator.nextInt(goalMessagesArray.length);
String gid = "";
if(isNotifyTimePassed(time)){
//return;
}
if(requestCode == 123){
// if(goalMessagesQueue.isEmpty()){
// goalMessagesQueue = new ArrayDeque<>(Arrays.asList(goalMessagesArray));
// }
// message = goalMessagesQueue.poll();
message = goalMessagesArray[indexForGoalMessage];
}else if(requestCode == 124){
// if(appraisalsMessagesQueue.isEmpty()){
// appraisalsMessagesQueue = new ArrayDeque<>(Arrays.asList(appraisalsMessagesArray));
// }
// message = appraisalsMessagesQueue.poll();
message = appraisalsMessagesArray[indexForAppraisalsMessage];
}
Bundle bundle = new Bundle();
bundle.putString("type", Integer.toString(requestCode));
bundle.putString("msg", message);
bundle.putString("gid" , String.valueOf(gId));
notificationsManager.sendNotification(bundle);
wl.release();
}
#NonNull
private PowerManager.WakeLock acquireWakeLock(Context context) {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
return wl;
}
private boolean isNotifyTimePassed(long time) {
return (System.currentTimeMillis()-time) > 1000L*60L*5L;
}
}
[I have found this solution from searching google ]
I have solved that problem by passing unique id which is depend on current time:-
final int intent_id= (int) System.currentTimeMillis();
PendingIntent pendingIntent = PendingIntent.getBroadcast(
context, intent_id , intent, PendingIntent.FLAG_UPDATE_CURRENT);
It is good to set your event id (unique id) as the request code of PendingIntent.getBroadcast() method. So the advantage here is when you update/edit the event then alarm wont duplicate.

store two time picker values in single fields

My app lets user enter two times to set device in silent mode in a specific time for an event. What I have done so far?
take start and end time input from user
activate silent mode and restore sound mode at the given time by the user.
What I need?
store start and end time values in sqlite database but in a single Time field.
For example:
ID Event Name Time
1 study time 2:00 PM-4:00 PM
Below is my MainActivity and databasehelper class
MainActivity.java
public class MainActivity extends AppCompatActivity {
EditText etMeal, etDesert;
EditText start, end;
Button btnAdd, btnView, btnsttime, btnend;
DatabaseHelper myDB;
SimpleDateFormat simpleDateFormat,simpleDateFormat1;
DatePicker dp;
CheckBox monday;
String[] Day;
TimePickerDialog timePickerDialog, secondtimepickerdialog;
static int RQS_1 = 1;
static int RQS_2 = 2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnAdd = (Button) findViewById(R.id.btnAdd);
btnView = (Button) findViewById(R.id.btnView);
btnsttime = (Button) findViewById(R.id.sttime);
btnend = (Button) findViewById(R.id.endtime);
monday=(CheckBox)findViewById(R.id.monchk);
etMeal = (EditText) findViewById(R.id.etMeal);
//etDesert = (EditText) findViewById(R.id.etDesert);
myDB = new DatabaseHelper(this);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String meal = etMeal.getText().toString();
//String desert = etDesert.getText().toString();
if (meal.length() != 0) {
AddData(meal);
etMeal.setText("");
//etDesert.setText("");
} else {
Toast.makeText(MainActivity.this, "You must fill in the text fields!", Toast.LENGTH_LONG).show();
}
}
});
btnView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, View_Foods.class);
startActivity(intent);
}
});
btnsttime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
start();
}
});
btnend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
end();
}
});
}
public void dat()
{
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Toast.makeText(MainActivity.this,dayOfTheWeek,Toast.LENGTH_LONG).show();
}
public void AddData(String meal) {
boolean insertData = myDB.addData(meal);
if (insertData == true) {
Toast.makeText(MainActivity.this, "Data Successfully Inserted!", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Something went wrong :(.", Toast.LENGTH_LONG).show();
}
}
public void start()
{
Calendar cal=Calendar.getInstance();
// simpleDateFormat=new SimpleDateFormat("hh:mm a");
Date date = new Date();
//String time=simpleDateFormat.format(date);
int hour=cal.get(Calendar.HOUR);
int minute=cal.get(Calendar.MINUTE);
timePickerDialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener()
{
#Override
public void onTimeSet(TimePicker view, final int hourOfDay1,final int minute1) {
Time time = new Time(hourOfDay1, minute1,0);
//GregorianCalendar j2=new GregorianCalendar(hourOfDay1,minute1,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat.format(time);
btnsttime.setText(s);
//dp.getDayOfMonth();
Calendar calNow = Calendar.getInstance();
Calendar calSet = (Calendar) calNow.clone();
calSet.set(Calendar.HOUR_OF_DAY, hourOfDay1);
calSet.set(Calendar.MINUTE, minute1);
Toast.makeText(MainActivity.this,"Pending intent started",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), SilenceBroadCastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
timePickerDialog.setTitle("Start time");
timePickerDialog.show();
}
public void end(){
Calendar cal1=Calendar.getInstance();
simpleDateFormat1=new SimpleDateFormat("hh:mm a");
Date date1 = new Date();
String time=simpleDateFormat1.format(date1);
int hour=cal1.get(Calendar.HOUR);
int minute=cal1.get(Calendar.MINUTE);
secondtimepickerdialog=new TimePickerDialog(MainActivity.this, new
TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, final int hourOfDay2,final int minute2) {
Time time = new Time(hourOfDay2, minute2,0);
//GregorianCalendar j2=new GregorianCalendar(hourOfDay1,minute1,0);
//little h uses 12 hour format and big H uses 24 hour format
SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("h:mm a");
//format takes in a Date, and Time is a sublcass of Date
String s = simpleDateFormat1.format(time);
btnend.setText(s);
Calendar calNow1 = Calendar.getInstance();
Calendar calSet1 = (Calendar) calNow1.clone();
calSet1.set(Calendar.HOUR_OF_DAY, hourOfDay2);
calSet1.set(Calendar.MINUTE, minute2);
Toast.makeText(MainActivity.this,"Pending intent started",Toast.LENGTH_LONG).show();
Intent intent = new Intent(getBaseContext(), UnsilenceBroadcastReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getBaseContext(), RQS_2, intent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calSet1.getTimeInMillis(), pendingIntent);
//final long sttimer=((shour)*60*60*1000)+((sminute)*60*1000);
}
},hour,minute,false);
timePickerDialog.setTitle("End time");
secondtimepickerdialog.show();
}
}
Databasehelper.java
public class DatabaseHelper extends SQLiteOpenHelper {
public static final String DATABASE_NAME = "food.db";
public static final String TABLE_NAME = "food_data";
public static final String COL1 = "ID";
public static final String COL2 = "MEAL";
//public static final String COL3 = "DESERT";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
#Override
public void onCreate(SQLiteDatabase db) {
String createTable = "CREATE TABLE " + TABLE_NAME + " (ID INTEGER PRIMARY KEY AUTOINCREMENT, " +
" MEAL TEXT)";
db.execSQL(createTable);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP IF TABLE EXISTS " + TABLE_NAME);
onCreate(db);
}
public boolean addData(String meal) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(COL2, meal);
//contentValues.put(COL3, desert);
long result = db.insert(TABLE_NAME, null, contentValues);
//if date as inserted incorrectly it will return -1
if (result == -1) {
return false;
} else {
return true;
}
}
public Cursor getListContents() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor data = db.rawQuery("SELECT * FROM " + TABLE_NAME, null);
return data;
}
}

How to get multiple notifications in Android

In one activity I have three DatePickerDialog where the user can put three date for a reminder purpose. The app must notify each date and if the user enters two or three equal date they must be notified in sequence . My problem is that only the last date entered is notified. I use a random number for the notification_id. How do I fix? Thanks
Here the code:
ScheduleClient.java
public class ScheduleClient {
private ScheduleService mBoundService;
private Context mContext;
private boolean mIsBound;
public ScheduleClient(Context context) {
mContext = context;
}
public void doBindService() {
// Establish a connection with our service
mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with our service has been established,
// giving us the service object we can use to interact with our service.
mBoundService = ((ScheduleService.ServiceBinder) service).getService();
}
public void onServiceDisconnected(ComponentName className) {
mBoundService = null;
}
};
public void setAlarmForNotification(Calendar c){
mBoundService.setAlarm(c);
}
public void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
mContext.unbindService(mConnection);
mIsBound = false;
}
}
}
ScheduleService.java
public class ScheduleService extends Service {
public class ServiceBinder extends Binder {
ScheduleService getService() {
return ScheduleService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("ScheduleService", "Received start id " + startId + ": " + intent);
stopped, so return sticky.
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new ServiceBinder();
public void setAlarm(Calendar c) {
// This starts a new thread to set the alarm
// You want to push off your tasks onto a new thread to free up the UI to carry on responding
new AlarmTask(this, c).run();
}
}
AlarmTask.java
public class AlarmTask implements Runnable {
private final Calendar date;
private final AlarmManager am;
private final Context context;
public AlarmTask(Context context, Calendar date) {
this.context = context;
this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
this.date = date;
}
#Override
public void run() {
// Request to start are service when the alarm date is upon us
// We don't start an activity as we just want to pop up a notification into the system bar not a full activity
Intent intent = new Intent(context, NotifyService.class);
intent.putExtra(NotifyService.INTENT_NOTIFY, true);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
// Sets an alarm - note this alarm will be lost if the phone is turned off and on again
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
}
}
NotifyService.java
public class NotifyService extends Service {
public class ServiceBinder extends Binder {
NotifyService getService() {
return NotifyService.this;
}
}
Random random = new Random();
int randomID = random.nextInt(9999 - 1000) + 1000;
public static final String INTENT_NOTIFY = "com.try.myapp.INTENT_NOTIFY";
private NotificationManager mNM;
#Override
public void onCreate() {
Log.i("NotifyService", "onCreate()");
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// If this service was started by out AlarmTask intent then we want to show our notification
if(intent.getBooleanExtra(INTENT_NOTIFY, false))
showNotification(randomID);
// We don't care if this service is stopped as we have already delivered our notification
return START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
private final IBinder mBinder = new ServiceBinder();
private void showNotification(int notificationID) {
// This is the 'title' of the notification
CharSequence title = "Notification!";
// This is the icon to use on the notification
int icon = R.drawable.ic_dialog_alert;
// This is the scrolling text of the notification
CharSequence text = "Sub text notification.";
// What time to show on the notification
long time = System.currentTimeMillis();
Notification notification = new Notification(icon, text, time);
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, notificationID, new Intent(this, SecondActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, title, text, contentIntent);
// Clear the notification when it is pressed
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notification.defaults |= Notification.DEFAULT_LIGHTS;
notification.defaults |= Notification.DEFAULT_VIBRATE;
// Send the notification to the system.
mNM.notify(notificationID, notification);
// Stop the service when we are finished
stopSelf();
}
}
InsertDateActivity.java
public class InsertCarActivity extends AppCompatActivity {
....
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId();
if (id == R.id.saveButton) {
firstDate = fDate.getText().toString().trim();
secondDate = sDate.getText().toString().trim();
thirdDate = tDate.getText().toString().trim();
String[] arrFirstDate = firstDate.split("-");
int day = Integer.parseInt(arrFirstDate[0]);
int month = Integer.parseInt(arrFirstDate[1]);
month -= 1;
int year = Integer.parseInt(arrFirstDate[2]);
Calendar c = Calendar.getInstance();
c.set(year, month, day);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c);
String[] arrSecondDate = secondDate.split("-");
int day1 = Integer.parseInt(arrSecondDate[0]);
int month1 = Integer.parseInt(arrSecondDate[1]);
month1 -= 1;
int year1 = Integer.parseInt(arrSecondDate[2]);
Calendar c1 = Calendar.getInstance();
c1.set(year1, month1, day1);
c1.set(Calendar.HOUR_OF_DAY, 0);
c1.set(Calendar.MINUTE, 0);
c1.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c1);
String[] arrThirdDate = thirdDate.split("-");
int day2 = Integer.parseInt(arrThirdDate[0]);
int month2 = Integer.parseInt(arrThirdDate[1]);
month2 -= 1;
int year2 = Integer.parseInt(arrThirdDate[2]);
Calendar c2 = Calendar.getInstance();
c2.set(year2, month2, day2);
c2.set(Calendar.HOUR_OF_DAY, 0);
c2.set(Calendar.MINUTE, 0);
c2.set(Calendar.SECOND, 0);
scheduleClient.setAlarmForNotification(c2);
return true;
}
return false;
}
....
}
When you create your PendingIntent here:
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);
you probably want to pass a different requestCode (the first 0 you're passing) every time or the PendingIntent will be the same as the last one you created and the following:
am.set(AlarmManager.RTC, date.getTimeInMillis(), pendingIntent);
will set a new alarm for the same PendingIntent as before, so only the last alarm you set will actually ever trigger.
From the official docs
If you truly need multiple distinct PendingIntent objects active at the same time (such as to use as two notifications that are both shown at the same time), then you will need to ensure there is something that is different about them to associate them with different PendingIntents. This may be any of the Intent attributes considered by Intent.filterEquals, or different request code integers supplied to getActivity(Context, int, Intent, int), getActivities(Context, int, Intent[], int), getBroadcast(Context, int, Intent, int), or getService(Context, int, Intent, int).

Categories