Android Studio AlarmManager is not running at the specific time - android

This is the code for the alarm manager:
protected void alarmInit(){
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 9);
calendar.set(Calendar.MINUTE, 25);
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent alarmIntent = new Intent(this, SampleBootReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, alarmIntent, 0);
manager.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_DAY, pendingIntent);
}
This is the Broadcast class:
public class SampleBootReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(getApplicationContext(),"Hello",Toast.LENGTH_LONG).show();
intent = new Intent(context, NotificationService.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context)
// Set Icon
.setSmallIcon(R.drawable.icono)
// Set Ticker Message
.setTicker("message")
// Set Title
.setContentTitle("asdf")
// Set Text
.setContentText("message")
// Add an Action Button below Notification
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
}
}
}
But at the set time I do not receive any message (I don't see the Toast message with the word Hello).
Also, in Manifest XML I set inside aplication tag:
<receiver android:name=".Home$SampleBootReceiver"
android:enabled="false"
tools:ignore="Instantiatable">
The class SampleBootReceiver is a public class in Home class
Could you please help me with this? Thanks in advance

You are using setInexactRepeating so the OS will decide when to fire your alarm. The OS tries to group together alarms to save battery.
Beginning with API 19 (Build.VERSION_CODES.KITKAT) alarm delivery is
inexact: the OS will shift alarms in order to minimize wakeups and
battery use. There are new APIs to support applications which need
strict delivery guarantees; see setWindow(int, long, long,
android.app.PendingIntent) and setExact(int, long,
android.app.PendingIntent). Applications whose targetSdkVersion is
earlier than API 19 will continue to see the previous behavior in
which all alarms are delivered exactly when requested.
https://developer.android.com/reference/android/app/AlarmManager

Related

Android AlarmManager only sending last scheduled notification

I am creating a research app that should prompt the user 4 times a day to enter their mood - by sending a notification, which when clicked launches the correct Activity. I am able to schedule these notifications using AlarmManager, however only the last scheduled notification ever shows. So although I schedule them for 9AM, 2PM, 5PM, and 8PM, it only ever sends a notification at 8PM.
How can I get all of the scheduled notifications to show?
Here is my code for setting (one of) the alarms (from a notification manager class). Note that al alarms are set using the same instance of AlarmManager:
cal.setTimeInMillis(System.currentTimeMillis());
cal.set(Calendar.HOUR_OF_DAY, 9);
cal.set(Calendar.MINUTE, 0);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), createPendingIntent(9, this));
Here is the createPendingIntent method (in the same notification manager class):
public static PendingIntent createPendingIntent(int hour, Context c){
Intent notificationIntent = new Intent(c, AlarmBroadcastReceiver.class);
notificationIntent.putExtra("time", hour);
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
return pendingIntent;
}
Here is the BroadcastReceiver for the alarm:
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
NotificationSender.createNotification(context);
}
}
And finally the createNotification method:
public static void createNotification(Context c){
Log.e("notif?", "creating");
Intent intent = new Intent(c, UpdateMoodActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
int notificationId = new Random().nextInt();
PendingIntent pendingIntent = PendingIntent.getActivity(c, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(c, "com.lizfltn.phdapp.notifChannelID")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentTitle("SoftMood")
.setContentText("Please record your mood")
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(c);
notificationManager.notify(notificationId, builder.build());
}
Yes I know this isn't the best-practice way of doing things, or even the neatest, but unfortunately I need to get code working ahead of writing good code :P
I've tried various configurations of setting the alarm, e.g. using elapsed realtime instead of RTC, only setting the alarm, setting the exact alarm, etc, but there might be something fundamental I'm not understanding about how those work.
Any help appreciated!
Can you try with same id in pending intent and notify.?
Notification id in createNotification() method is random id.
int notificationId = new Random().nextInt();
and id used in createPendingIntent method is 0.
PendingIntent pendingIntent = PendingIntent.getBroadcast(c, 0 , notificationIntent , PendingIntent.FLAG_UPDATE_CURRENT);
Can you try with using same value for second parameter of getBroadcast?

Android set alarm manager when another is finished

I tried to use the setRepeating of AlarmManager, and then I read that the method isn't working anymore in API 26+, so the another solution was to schedule each alarm when the previous is finish. How can I do that?
MainActivity.java
public class MainActivity extends AppCompatActivity {
calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hour.getText().toString()));
calendar.set(Calendar.MINUTE, Integer.parseInt(minute.getText().toString()));
calendar.set(Calendar.SECOND, 00);
Intent intent = new Intent(getApplicationContext(), Notification_receiver.class);
pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
}
Notification_reciever.java
public class Notification_receiver extends BroadcastReceiver {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, MainActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context, time, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentIntent(pendingIntent)
.setChannelId(CHANNEL_ID)
.setSmallIcon(R.drawable.ic_baseline_notifications_active_24)
.setContentTitle("Notification Title")
.setContentText("Notification Text")
.setAutoCancel(true);
notificationManager.notify(time, builder.build());
}
How can i create another alarm manager when the previous is finish?
You will need to schedule your next alarm, at the end of BroadcastReceiver
public class AlarmBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
...
alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmTimeInMillis(), pendingIntent);
Please note that, due to different battery saving mechanism implemented by different OEMs, AlarmManager is not guarantee to work all the time. Please refer to https://issuetracker.google.com/issues/122098785
In short, AlarmManager is the current best available mechanism, for timed notification to work, even without Internet connection. But, it is not gurantee to work all the time.
Here is example to make alarm every 2 minutes (tested on API 30)
move code to set alarm from MainActivity in own class
public class AlarmExecutor {
public static void makeAlarm(Context context, int minute) {
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.MINUTE, minute);
Intent intent = new Intent(context, Notification_receiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Log.d("Testing", "make alarm at " + calendar.getTime().toString());
}
}
now you can add in
Notification_receiver.java after notificationManager.notify(time, builder.build());
MainActivity
following line
// make alarm in 2 minutes
AlarmExecutor.makeAlarm(context, 2);
that will make an alarm every 2 minutes.
And don't forget to register the receiver in Manifest
<application >
<receiver android:name=".yourReceiver" />
</application>

Android local notification doesn't arrive every time

I want my user to set a time to receive a daily reminder from my app. In my ReminderActivity I create the PendingIntent and the Alarm Manager, and then in my Alarm Receiver class I create the notification inside onReceive(). I tried both the FLAG_CANCEL_CURRENT and FLAG_UPDATE_CURRENT flags when creating the pending intent but still when I am testing the app and changing the reminder time then sometimes the notification doesn't arrive at all, or it arrives only when the app is running in the background and the screen is on. I would greatly appreciate any thought or ideas.
ReminderActivity code:
private void setNotification() {
Calendar calendar = Calendar.getInstance();
Calendar now = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, chosenHour);
calendar.set(Calendar.MINUTE, chosenMinute);
calendar.set(Calendar.SECOND, 0);
//if user sets the alarm after their preferred time has already passed that day
if(now.after(calendar)) {
calendar.add(Calendar.DAY_OF_MONTH, 1);
}
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(ReminderActivity.this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
alarmManager = (AlarmManager) getSystemService(Activity.ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
}
Alarm Receiver code:
#Override
public void onReceive(Context context, Intent intent) {
Bitmap largeLogo = BitmapFactory.decodeResource(context.getResources(),
R.drawable.ptwired_logo);
//create local notification
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(context, MainActivity.class);
//notificationIntent.putExtra("FromPTWired", true); //to track if user opens the app from the daily digest notification
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
Notification notification = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ptwired_logo)
.setLargeIcon(largeLogo)
.setContentTitle(context.getResources().getString(R.string.app_name))
.setPriority(NotificationCompat.PRIORITY_HIGH)
.setContentIntent(pendingIntent)
.setContentText(REMINDER_TEXT)
.setAutoCancel(true)
.setOngoing(false)
.build();
notificationManager.notify(1, notification);
}
}
Probably an issue of Doze mode, take a look in Android restriction:
Doze restrictions
The following restrictions apply to your apps while in Doze:
Standard AlarmManager alarms (including setExact() and setWindow()) are deferred to the next maintenance window.
If you need to set alarms that fire while in Doze, use setAndAllowWhileIdle() or setExactAndAllowWhileIdle().
Alarms set with setAlarmClock() continue to fire normally — the system exits Doze shortly before those alarms fire.

Android manager not giving notification after 5 sec

I am trying to use alarm manager to show notification after 5 sec. I have tried many sites but was not able to understand please give a simple example for explaining how to use alarm manager and connect notification with it.
I am newbie.
this is function i used to set alarm and I am not getting notification after 5 secs not in emulator nor in android mobile.
public void setAlarm(View view)
{
Intent alertIntent = new Intent(this, AlertReciver.class);
Long alertTime = new GregorianCalendar().getTimeInMillis()+5*1000;
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, alertTime, PendingIntent.getBroadcast(this, 1, alertIntent, PendingIntent.FLAG_UPDATE_CURRENT));
tv.setText("completed");
}
and this class to make it work
public class AlertReciver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
createNotification(context,"times Up", "5 SEcond has passed", "Alert");
}
public void createNotification(Context context,String msg, String msgText, String msgAlert){
PendingIntent notificIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.drawable.ne)
.setContentTitle(msg)
.setTicker(msgAlert)
.setContentText(msgText);
mBuilder.setContentIntent(notificIntent);
mBuilder.setDefaults(NotificationCompat.DEFAULT_SOUND);
mBuilder.setAutoCancel(true);
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
mNotificationManager.notify(1, mBuilder.build());
}
}
See: https://developer.android.com/reference/android/app/AlarmManager.html
Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS
will shift alarms in order to minimize wakeups and battery use. There
are new APIs to support applications which need strict delivery
guarantees; see setWindow(int, long, long, PendingIntent) and
setExact(int, long, PendingIntent). Applications whose
targetSdkVersion is earlier than API 19 will continue to see the
previous behavior in which all alarms are delivered exactly when
requested.

how to schedule a notification using alarm manager

I have defined a receiver which should fire the notification when it is called. This works only if I call the receiver straight away.
I am unable to schedule it for a specific date.
Calendar c = Calendar.getInstance();
c.set(2014, 4, 18, 2, 20, 0);
AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(getBaseContext().ALARM_SERVICE);
int id = (int) System.currentTimeMillis();
Intent intent = new Intent(this, TimeAlarm.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), pendingIntent);
This is my Receiver class:
public class TimeAlarm extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent paramIntent) {
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent intent = new Intent("android.intent.action.VIEW");
intent.setData(Uri.parse("http://www.sdfasdf.ch"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification
Notification notification = new Notification(R.drawable.android_anydont_logo, "sdfs", System.currentTimeMillis());
notification.setLatestEventInfo(context, "something something", "darkside",pendingIntent);
// Fire the notification
notificationManager.notify(1, notification);
}
}
This is the definition in the manifest:
receiver
android:name="com.hack.doneit.utils.TimeAlarm"
android:process=":remote" />
My problem is that i am unable to set the alarm to trigger the receiver at a specific time in the future. A specific day would be enough.
Problem is with the Month value you have set. I believe you thought for month April the value is 4. The value of month starts from 0 , so April will be 3.
Change you code on month as Calendar.APRIL or set value as 3
c.set(2014, Calendar.APRIL, 17, 20, 43, 0);
This should work. Apart from this your codes are perfect.
Note: Your using the Notification deprecated API's . Use Notification Builder

Categories

Resources