I have a receiver inside a service and the receiver isnt working. I did not declare it inside the manifest as it is made it in the service. Here is the code
package com.todaysfuture.dynpin;
public class MyBroadcastReceiver extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
AlarmManager alarmMgr;
PendingIntent alarmIntent;
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
Context context=getApplicationContext();
alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent intent1 = new Intent(context, MyBroadcastReceiver.class);
alarmIntent = PendingIntent.getBroadcast(context, 0, intent1, 0);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
1000 * 60, alarmIntent);
IntentFilter filter = new IntentFilter();
final BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
{
MainActivity ii=new MainActivity();
ii.displayer();
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
}
}
};
registerReceiver(receiver, filter);
return null;
}
}
The Service has been declared in the manifest. Yet it isnt working. What could possibly be the issue?
EDIT---------------------------------------------------------------------
Here is the updated Service
public class MyBroadcastReceiver extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
Calendar c = Calendar.getInstance();
int hour=c.get(Calendar.HOUR_OF_DAY);
int minute=c.get(Calendar.MINUTE);
Calendar calendar = new GregorianCalendar(1990, 1, 1, hour, minute);
MainActivity ii=new MainActivity();
ii.displayer();
String LOG_TAG="DevicePolicyAdmin";
Log.v(LOG_TAG, "Service Started");
SimpleDateFormat sdf = new SimpleDateFormat("hh:mm");
String date = sdf.format(calendar.getTime());
String str=date.charAt(0)+""+date.charAt(1)+""+date.charAt(3)+""+date.charAt(4);
MainActivity.minochaDevicePolicyManager.resetPassword(str, 0);
return null;
}
}
It still isnt working
Related
The user can press three buttons: One will bring up a clock to select the time, another will bring up a calendar to select the date. The third button is to be pressed last, and is meant to send out a notification.
When I press on the last button, I get the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.util.Calendar.before(java.lang.Object)' on a null object reference
at com.example.meeldetuletuserakendus.MeeldetuletusActivity.startAlarm(MeeldetuletusActivity.java:105)
Something goes wrong when trying to do the method startAlarm(c).
I know for certain that everything worked perfectly when the code only had a choice to choose a time, but something broke when I coded the date picking part of the code. So the problem probably has something to do with the date.
MeeldetuletusActivity.java:
public class MeeldetuletusActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
String timeText;
TextView textTime;
Button nupp_vali, nupp_katkesta, nupp_kuupaev, nupp_alarm;
Calendar c;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meeldetuletus);
nupp_vali = findViewById(R.id.button2);
nupp_katkesta = findViewById(R.id.nupp_katkesta);
nupp_kuupaev = findViewById(R.id.button);
nupp_alarm = findViewById(R.id.button3);
nupp_alarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startAlarm(c);
}
});
nupp_vali.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment timePicker = new TimePickerFragment();
timePicker.show(getSupportFragmentManager(), "time picker");
}
});
nupp_kuupaev.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
DialogFragment kuupaevaValija = new KuupaevaFragment();
kuupaevaValija.show(getSupportFragmentManager(), "date picker");
}
});
nupp_katkesta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
katkestaAlarm();
Toast.makeText(MeeldetuletusActivity.this, "Meeldetuletus unustatud", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
Calendar c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
private void startAlarm(Calendar c) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP,
c.getTimeInMillis(), pendingIntent);
}
private void katkestaAlarm() {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent myIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(
getApplicationContext(), 1, myIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.cancel(pendingIntent);
}
}
Row 105 is:
if (c.before(Calendar.getInstance())) {
KuupaevaFragment.java:
public class KuupaevaFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int aasta = c.get(Calendar.YEAR);
int kuu = c.get(Calendar.MONTH);
int paev = c.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(),
aasta, kuu, paev);
}
}
TimePickerFragment.java: (This worked perfectly before, I'm only putting this here so you can see what KuupaevaFragment.java is meant to do aswell)
public class TimePickerFragment extends DialogFragment {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(),
hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
NotificationPublisher.java:
public class NotificationPublisher extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
notificationHelper.getManager().notify(1, nb.build());
Notification notification = nb.build();
notification.defaults |= Notification.DEFAULT_VIBRATE;
notification.defaults |= Notification.DEFAULT_SOUND;
}
}
NotificationHelper.Java:
class NotificationHelper extends ContextWrapper {
public static final String channelID = "channelID";
public static final String channelName = "Channel Name";
private NotificationManager notificationManager;
public NotificationHelper(Context base) {
super(base);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
createChannel();
}
}
#TargetApi(Build.VERSION_CODES.O)
private void createChannel() {
NotificationChannel channel = new NotificationChannel(channelID, channelName,
NotificationManager.IMPORTANCE_HIGH);
getManager().createNotificationChannel(channel);
}
public NotificationManager getManager() {
if (notificationManager == null) {
notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
}
return notificationManager;
}
public NotificationCompat.Builder getChannelNotification() {
return new NotificationCompat.Builder(getApplicationContext(), channelID)
.setContentTitle("Meeldetuletus")
.setContentText("Teie valitud aeg on käes")
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24);
}
}
Try to reference to the Activity's field c in onTimeSet and onDateSet:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c = Calendar.getInstance();
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
public void onDateSet(DatePicker view, int aasta, int kuu, int paev) {
c = Calendar.getInstance();
c.set(Calendar.YEAR, aasta);
c.set(Calendar.MONTH, kuu);
c.set(Calendar.DAY_OF_MONTH, paev);
}
So instead of Calendar c = Calendar.getInstance(); write c = Calendar.getInstance(); like in the code above.
Or you can try to initialize c property in Activity:
Calendar c = Calendar.getInstance();
and use it to change Calendar's properties, for example in onTimeSet method:
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
}
I am a bit new to android studio, and i am making an app where the user can select the date and time, and it will schedule and alarm to go off at that time. However, when i set the alarm it does not go off. Does anyone know where i went wrong? Or what it is i can change within my code.
CustomDialogClass
public Activity c;
public Dialog d;
public CircleButton CalendarBtn, TimeBtn;
public Button CancelBtn, ProceedBtn;
public TextView CalendarTxt, TimeTxt;
public EditText ReminderTxt;
//FOR CALENDAR
final Calendar myCalendar = Calendar.getInstance();
//FOR CALENDAR
private void updateLabel(TextView edittext) {
String myFormat = "dd/MM/yy"; //In which you need put here
SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.UK);
edittext.setText(sdf.format(myCalendar.getTime()));
}
//FOR CALENDAR
DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
myCalendar.set(Calendar.YEAR, year);
myCalendar.set(Calendar.MONTH, monthOfYear);
myCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
updateLabel(CalendarTxt);
}
};
public CustomDialogClass(Activity a) {
super(a);
// TODO Auto-generated constructor stub
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
CalendarTxt = (TextView) findViewById(R.id.CurrentDateSelect);
TimeTxt = (TextView) findViewById(R.id.CurrentTimeSelect);
CancelBtn = (Button) findViewById(R.id.CancelBtn);
ProceedBtn = (Button) findViewById(R.id.ProceedBtn);
CancelBtn.setOnClickListener(this);
ProceedBtn.setOnClickListener(this);
CalendarBtn = (CircleButton) findViewById(R.id.calendarBtn);
TimeBtn = (CircleButton) findViewById(R.id.timeBtn);
CalendarBtn.setOnClickListener(this);
TimeBtn.setOnClickListener(this);
ReminderTxt = (EditText) findViewById(R.id.ReminderTxt);
}
#Override
public void onClick(View v) {
//On click method for buttons
switch (v.getId()) {
case R.id.calendarBtn:
new DatePickerDialog(getContext(), date, myCalendar
.get(Calendar.YEAR), myCalendar.get(Calendar.MONTH),
myCalendar.get(Calendar.DAY_OF_MONTH)).show();
break;
case R.id.CancelBtn:
dismiss();
break;
case R.id.timeBtn:
Calendar mcurrentTime = Calendar.getInstance();
int hour = mcurrentTime.get(Calendar.HOUR_OF_DAY);
int minute = mcurrentTime.get(Calendar.MINUTE);
TimePickerDialog mTimePicker;
mTimePicker = new TimePickerDialog(getContext(), new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int selectedHour, int selectedMinute) {
String curTime = String.format("%02d:%02d", selectedHour, selectedMinute);
TimeTxt.setText(curTime);
}
}, hour, minute, true);//Yes 24 hour time
mTimePicker.setTitle("Select Time");
mTimePicker.show();
break;
case R.id.ProceedBtn:
String TimeVal = TimeTxt.getText().toString();
String DateVal = CalendarTxt.getText().toString();
String RemindVal = ReminderTxt.getText().toString();
if ((TimeVal + DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + DateVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((TimeVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else if ((DateVal + RemindVal).isEmpty()) {
Toast.makeText(getContext(), "No View can be Empty!", Toast.LENGTH_SHORT).show();
} else {
String FinalAlarmVal = DateVal + " " + " " + TimeVal;
String AlarmHour = TimeVal.substring(0, 2);
String AlarmMins = TimeVal.substring(3, 5);
String AlarmMonth = DateVal.substring(3, 5);
String AlarmDay = DateVal.substring(0, 2);
System.out.println("SEWISINGHVV- "+ Integer.parseInt(AlarmMonth));
AlarmScheduler.setReminder(getContext(), Integer.parseInt(AlarmHour), Integer.parseInt(AlarmMins), Integer.parseInt(AlarmDay), Integer.parseInt(AlarmMonth)); // Here mContext is Context of Activity. If you use this code in Activity then you can pass ActivityName.this and in Fragment you can do getActivity()
Intent AlarmName = new Intent(getContext(), AlarmReceiver.class);
AlarmName.putExtra("NameOfAlarm", RemindVal);
getContext().startService(AlarmName);
}
break;
default:
break;
}
//dismiss();
//Ends dialog when button is pressed
}
AlarmScheduler
public static final int DAILY_REMINDER_REQUEST_CODE = 100;
public static final String TAG = "AlarmScheduler";
public static void setReminder(Context context, int hour, int min, int day, int month) {
Calendar calendar = Calendar.getInstance();
Calendar setcalendar = Calendar.getInstance();
setcalendar.set(Calendar.MONTH, month);
setcalendar.set(Calendar.DAY_OF_MONTH, day);
setcalendar.set(Calendar.HOUR_OF_DAY, hour);
setcalendar.set(Calendar.MINUTE, min);
setcalendar.set(Calendar.SECOND, 0);
setcalendar.set(Calendar.MILLISECOND, 0);
// cancel already scheduled reminders
cancelReminder(context, AlarmReceiver.class);
if (setcalendar.before(calendar))
setcalendar.add(Calendar.DATE, 1);
// Enable a receiver
ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.setInexactRepeating(AlarmManager.RTC_WAKEUP, setcalendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
public static void cancelReminder(Context context, Class<?> cls) {
// Disable a receiver
ComponentName receiver = new ComponentName(context, cls);
PackageManager pm = context.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Intent intent1 = new Intent(context, cls);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, DAILY_REMINDER_REQUEST_CODE, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) context.getSystemService(ALARM_SERVICE);
am.cancel(pendingIntent);
pendingIntent.cancel();
}
AlarmReceiver
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
}
So, I wanna build a scheduled message. But when I try to send more than one message, the other messages can't be delivered. I wonder how to do that.
onTimeSet method
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.MINUTE, calendar.get(Calendar.MINUTE)+1);
Log.d("Current time: ", formatter.format(calendar.getTime()));
c.set(Calendar.HOUR_OF_DAY, hourOfDay);
c.set(Calendar.MINUTE, minute);
c.set(Calendar.SECOND, 0);
if (c.getTimeInMillis() <= calendar.getTimeInMillis()){
Log.d("Tag: ", "Denied");
Toast.makeText(this, "You can't send it if it's too early!", Toast.LENGTH_SHORT).show();
} else {
Log.d("Tag: ", "Approved");
Toast.makeText(this, "Success!", Toast.LENGTH_SHORT).show();
startSchedule(c);
Intent intent = new Intent(MessageActivity.this, MessageActivity.class);
startActivity(intent);
finish();
}
}
startSchedule method
private void startSchedule(Calendar calendar) {
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlertReceiver.class);
intent.putExtra("number", number);
intent.putExtra("body", body);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
DateFormat formatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm");
Log.d("Test: ", ""+calendar.getTimeInMillis());
Log.d("Date: ", ""+formatter.format(calendar.getTimeInMillis()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
}
AlertReceiver class
public class AlertReceiver extends BroadcastReceiver {
String number, body;
#Override
public void onReceive(Context context, Intent intent) {
Log.d("Test: ", "Worked");;
Bundle bd = intent.getExtras();
if(bd == null){
number = "";
body = "";
}else {
number = bd.getString("number");
body = bd.getString("body");
}
Log.d("Number: ", number +"\nBody: "+body);
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(number, null, body, null, null);
}
}
Please let me know if you guys know what I should do to make things right, thanks a lot!
I want to send a notification with the alarm manager in my application. I am using the setRepeating method because it should be in intervals. but notifications always come delayed.
For example, I would like to receive a notification at 12:14. but notification is coming sometimes 12:17, sometimes 12:20
Thanks in advance
Note: doze mode off
For Example:
thatDay Sat Apr 25 16:30:00 GMT+03:00 2020
today Sat Apr 25 16:07:44 GMT+03:00 2020
thatDay.getTimeInMillis() = 1587821400000
#Override
protected void onStop() {
if (notification) {
Calendar thatDay = Calendar.getInstance();
Calendar today = Calendar.getInstance();
int today_month_day = today.get(Calendar.DAY_OF_MONTH);
int today_month = today.get(Calendar.MONTH);
int today_year = today.get(Calendar.YEAR);
thatDay.setTime(new Date(0));
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
thatDay.set(Calendar.MONTH, today_month);
thatDay.set(Calendar.YEAR, today_year);
thatDay.set(Calendar.HOUR_OF_DAY, 8);
thatDay.set(Calendar.MINUTE, 0);
thatDay.set(Calendar.SECOND, 0);
thatDay.set(Calendar.MILLISECOND, 0);
Calendar calendar = Calendar.getInstance();
if (calendar.get(Calendar.HOUR_OF_DAY) < 23 && calendar.get(Calendar.HOUR_OF_DAY) > 7) {
if (calendar.get(Calendar.MINUTE) < 30) {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY));
thatDay.set(Calendar.MINUTE, 30);
} else {
thatDay.set(Calendar.HOUR_OF_DAY, calendar.get(Calendar.HOUR_OF_DAY) + 1);
}
} else if (thatDay.getTimeInMillis() - today.getTimeInMillis() < 0) {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day + 1);
} else {
thatDay.set(Calendar.DAY_OF_MONTH, today_month_day);
}
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, AlarmReceiver.class);
intent.putExtra("NotificationID", 6);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 7, intent, PendingIntent.FLAG_UPDATE_CURRENT);
Objects.requireNonNull(alarmManager).setRepeating(AlarmManager.RTC_WAKEUP, thatDay.getTimeInMillis(), waterList[waterCheck], pendingIntent);
super.onStop();
}
#SuppressLint("BatteryLife")
#RequiresApi(api = Build.VERSION_CODES.M)
private void requestBattery() {
Intent intent = new Intent();
String packageName = context.getPackageName();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
if (!(Objects.requireNonNull(pm).isIgnoringBatteryOptimizations(packageName))) {
intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
intent.setData(Uri.parse("package:" + packageName));
startActivityForResult(intent, BATTERY_PERMISSION);
}
}
This is because setRepeating is only fired, when something else is happening in the background. Mainly this is due to battery saving. The best way to set a repeating alarm is to use setExact and set another alarm once the first one was fired.
Alarmmanager:
public class AlarmManagerSetup {
public static Boolean alarmActivated;
public static Long milliSeconds;
public void startAlarm(Calendar c, Context context, Database database) {
android.app.AlarmManager alarmManager = (android.app.AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, AlertReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, 0);
c.setTimeInMillis(milliSeconds);
//compares to the current time and only adds when it is later than now
if (c.before(Calendar.getInstance())) {
c.add(Calendar.DATE, 1);
}
if (Build.VERSION.SDK_INT >= 23) {
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else if (Build.VERSION.SDK_INT >= 19) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
} else {
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
}
}
And inside the Alert Receiver you do this:
public class AlertReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Context appContext = context.getApplicationContext();
CalendarSearch calendar = new CalendarSearch(context);
calendar.calendar();
NotificationHelper notificationHelper = new NotificationHelper(context);
NotificationCompat.Builder nb = notificationHelper.getChannelNotification(appContext);
notificationHelper.getManager().notify(1, nb.build());
AlarmManagerSetup alarmManager = new AlarmManagerSetup();
Calendar c = Calendar.getInstance();
c.setTimeInMillis(milliSeconds);
c.add(Calendar.DATE, 1);
milliSeconds = c.getTimeInMillis();
alarmManager.startAlarm(c, appContext, database);
}
I am using the AlarmManager for repeating alarms. I've set repeating alarms for Mondays, Thursdays and Saturdays. The alarm shows correctly on Monday but when Thursday comes, it displays both notifications for Monday and Thursday together, and shows all three notifications on the Saturdays. How do I code it such that when the first alarm is done, it doesn't show on subsequent alarms in that same week, instead it goes to the next weeks?
EDIT1 - Code
MainActivity
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.action_settings:
EnableNoti();
return true;
}
return super.onOptionsItemSelected(item);
}
private void EnableNoti() {
Calendar calendar = Calendar.getInstance();
Calendar calendar1 = Calendar.getInstance();
Calendar calendar2 = Calendar.getInstance();
Calendar calendar3 = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_WEEK, 1); // Sunday
calendar1.set(Calendar.DAY_OF_WEEK, 4); // Wednesday
calendar2.set(Calendar.DAY_OF_WEEK, 6); // Friday
calendar3.set(Calendar.DAY_OF_WEEK, 5); // Thursday
calendar3.set(Calendar.DAY_OF_WEEK_IN_MONTH, 1); // First Thursday of
// Each Month
Date now = new Date(System.currentTimeMillis());
if (calendar3.getTime().before(now)) {
calendar3.add(Calendar.MONTH, 1);
} else if (calendar.getTime().before(now)) {
calendar.add(Calendar.HOUR, 168);
} else if (calendar1.getTime().before(now)) {
calendar1.add(Calendar.HOUR, 168);
} else if (calendar2.getTime().before(now)) {
calendar2.add(Calendar.HOUR, 168);
}
// Sunday
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
// Wednesday
calendar1.set(Calendar.HOUR_OF_DAY, 17);
calendar1.set(Calendar.MINUTE, 30);
calendar1.set(Calendar.SECOND, 0);
calendar1.set(Calendar.AM_PM, Calendar.PM);
// Friday
calendar2.set(Calendar.HOUR_OF_DAY, 17);
calendar2.set(Calendar.MINUTE, 30);
calendar2.set(Calendar.SECOND, 0);
calendar2.set(Calendar.AM_PM, Calendar.PM);
// Thursday
calendar3.set(Calendar.HOUR_OF_DAY, 22);
calendar3.set(Calendar.MINUTE, 0);
calendar3.set(Calendar.SECOND, 0);
calendar3.set(Calendar.AM_PM, Calendar.PM);
Intent myIntent = new Intent(TheBeginningEnglish.this,
MyReceiverEnglish.class);
pendingIntent = PendingIntent.getBroadcast(TheBeginningEnglish.this, 0,
myIntent, 0);
Intent myIntent1 = new Intent(TheBeginningEnglish.this,
MyReceiver1English.class);
pendingIntent1 = PendingIntent.getBroadcast(TheBeginningEnglish.this,
0, myIntent1, 0);
Intent myIntent2 = new Intent(TheBeginningEnglish.this,
MyReceiver2English.class);
pendingIntent2 = PendingIntent.getBroadcast(TheBeginningEnglish.this,
0, myIntent2, 0);
Intent myIntent3 = new Intent(TheBeginningEnglish.this,
MyReceiver3English.class);
pendingIntent3 = PendingIntent.getBroadcast(TheBeginningEnglish.this,
0, myIntent3, 0);
AlarmManager alarmMgr = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7,
pendingIntent); // every Sunday
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar1.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7,
pendingIntent1); // every Wednesday
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar2.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 7,
pendingIntent2); // every Friday
alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
calendar3.getTimeInMillis(), AlarmManager.INTERVAL_DAY * 31,
pendingIntent3); // every first Thursday
}
Receiver.java
public class MyReceiverEnglish extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
Intent service = new Intent(context, MyAlarmServiceEnglish.class);
context.startService(service);
}
}
AlarmService.java
public class MyAlarmServiceEnglish extends Service {
int currentapiVersion = android.os.Build.VERSION.SDK_INT;
private NotificationManager mManager;
Notification notification;
// Notification notification;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
onStartCommand(intent, 0, startId);
}
#SuppressWarnings({ "static-access", "deprecation" })
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mManager = (NotificationManager) this.getApplicationContext()
.getSystemService(
this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),
TheBeginning1English.class);
if (currentapiVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
Notification notification = new Notification(
R.drawable.ic_launcher,
"Its Sunday!.",
System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP
| Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent1 = PendingIntent
.getActivity(this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(this.getApplicationContext(),
"Testing", "Its Sunday.",
pendingNotificationIntent1);
mManager.notify(0, notification);
} else {
PendingIntent pendingNotificationIntent1 = PendingIntent
.getActivity(this.getApplicationContext(), 0, intent1,
PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("Test Test App")
.setContentText("Its Sunday!.")
.setWhen(System.currentTimeMillis())
.setContentIntent(pendingNotificationIntent1)
.setSmallIcon(R.drawable.ic_launcher).build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
mManager.notify(0, notification);
}
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
Thats it,in the main activity, you will see four separate calendar variables, I had to create a Receiver,Receiver1,Receiver2,Receiver3, and AlarmService1,2,3. for each calendar, not the best way, but only thing I could figure. I added the:
Date now = new Date(System.currentTimeMillis());
if (calendar3.getTime().before(now)) {
calendar3.add(Calendar.MONTH, 1);
} else if (calendar.getTime().before(now)) {
calendar.add(Calendar.HOUR, 168);
} else if (calendar1.getTime().before(now)) {
calendar1.add(Calendar.HOUR, 168);
} else if (calendar2.getTime().before(now)) {
calendar2.add(Calendar.HOUR, 168);
}
I added the date part today, havent checked it out to know if it will work. Thanks for helping me with this!
How Alaram Service work?
it start as per your condition like you have set for day,week or any week day. so at every specified time set it receive command. like Notification,tone.
so in onStartServiceCommand() method. you have to apply logic for that.
so notification just comes once for that specific day.