Tutorial #41: Using AlarmManager and BroadcastReceiver in Android

UPDATE:

Please refer the updated source code. It can be downloaded from the link at the end of this post.

Hello friends!

Sometimes we need to create an application that notifies a user at a particular time/date even though the user has not opened the application. The Android SDK provides developers an abstract class called BroadcastReceiver which is used to pass a notification to the user in case any specific event occurs.

In addition, developers can also schedule and add events using the AlarmManager class. As stated in the Android developer’s guide, when an alarm goes off, the Intent that had been registered using AlarmManager is broadcasted by the system, automatically starting the target application if it is not already running.

Using the above concepts, we will now create an Android application that sends a notification message to the user at a particular time (for example: 11:25:00 AM).

Pre-requisites: Eclipse IDE (preferably latest version) , Android SDK (tested below code on Android 2.3.3)

Create a new Android application project named AndroidAlarmManagerDemo with package name com.example. Select Target SDK as Android 2.3.3

Now, let’s create our startup Activity called MainActivity by adding the following code!

MainActivity.java

package com.example;

import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;

public class MainActivity extends Activity 
{

    private PendingIntent pendingIntent;
    
    @Override
    public void onCreate(Bundle savedInstanceState) 
     {
      
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
    
      Calendar calendar = Calendar.getInstance();
    
      calendar.set(Calendar.MONTH, 6);
      calendar.set(Calendar.YEAR, 2013);
      calendar.set(Calendar.DAY_OF_MONTH, 13);

      calendar.set(Calendar.HOUR_OF_DAY, 20);
      calendar.set(Calendar.MINUTE, 48);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.AM_PM,Calendar.PM);
    
      Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);
    
      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
   
    } //end onCreate
}

As stated earlier, we need to create a BroadcastReceiver that will that receive Intents. I have named my receiver class as MyReceiver.

MyReceiver.java

package com.example;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class MyReceiver extends BroadcastReceiver
{
	 
	@Override
	public void onReceive(Context context, Intent intent)
	{
	   Intent service1 = new Intent(context, MyAlarmService.class);
	   context.startService(service1);
	   
	}	
}

We also need to implement a Service that represents the application’s need to run a longer operation in the background without interacting with the user. For this purpose let’s create a Service called MyAlarmService.

package com.example;


import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
                           

public class MyAlarmService extends Service 
{
     
   private NotificationManager mManager;

    @Override
    public IBinder onBind(Intent arg0)
    {
       // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() 
    {
       // TODO Auto-generated method stub  
       super.onCreate();
    }

   @SuppressWarnings("static-access")
   @Override
   public void onStart(Intent intent, int startId)
   {
       super.onStart(intent, startId);
     
       mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
       Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
	
       Notification notification = new Notification(R.drawable.ic_launcher,"This is a test message!", System.currentTimeMillis());
       intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);

       PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
       notification.flags |= Notification.FLAG_AUTO_CANCEL;
       notification.setLatestEventInfo(this.getApplicationContext(), "AlarmManagerDemo", "This is a test message!", pendingNotificationIntent);

       mManager.notify(0, notification);
    }

    @Override
    public void onDestroy() 
    {
        // TODO Auto-generated method stub
        super.onDestroy();
    }

}

Finally, don’t forget to change the AndroidManifest.xml file to include the Service and the Receiver entries along with the necessary permissions. Save all changes and run the project on an Android device. You should see the following output!

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="10" />

    <uses-permission android:name="android.permission.WAKE_LOCK" />
     
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity
            android:name="com.example.NextActivity"
            android:label="Next Screen">
        </activity>
        
        <service android:name=".MyAlarmService"
            	 android:enabled="true" />
        
        <receiver android:name=".MyReceiver"/>
       
    </application>
</manifest>

Output

Updated source code for this tutorial can be found over here

Karan Balkar About Karan Balkar
self proclaimed extraterrestrial fandroid, computer engineer, amateur gamer and die hard punk rock fan!

117 thoughts on “Tutorial #41: Using AlarmManager and BroadcastReceiver in Android

  1. Pingback: Android notification message at a particular time repeated every time the app launched | questions android

  2. Hi , I have a small query. Will this alarm fire up a notification even if the app is closed by the user?? I mean we generally clear all those apps running in the background using the menu button in our mobile. I would like to know if this service will run even after the user closes the app(not minimized).If I had to run the service even after the user closes the app what should I do?

  3. i want to get notification at 7.20 pm.I have added
    calendar.set(Calendar.MONTH, 12);
    calendar.set(Calendar.YEAR, 2014);
    calendar.set(Calendar.DAY_OF_MONTH, 28);

    calendar.set(Calendar.HOUR_OF_DAY,19);
    calendar.set(Calendar.MINUTE, 20);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.AM_PM,Calendar.PM);
    but no notification
    why??

    • after this schedule your alarm to broadcast the notification for instance try this

      Intent intent = new Intent(MainActivity.this, MyReciever.class);
      intent.putExtra(“which”, 4);
      final int alarmId = (int) System.currentTimeMillis();

      pendingIntent = PendingIntent.getBroadcast(
      getApplicationContext(), alarmId, intent, 0);
      alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

      if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.LOLLIPOP_MR1) {
      alarmManager.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis()
      , pendingIntent);
      Log.i("MyTestService", "Service running");

      } else {
      alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, cal.getTimeInMillis()
      , pendingIntent);
      Log.i("MyTestService", "Service running");

      // alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, cal.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pendingIntent);
      alarmManager.cancel(pendingIntent);
      //

      and in your broadcast receiver class write your notification

  4. The application keeps giving the same alert repeatedly once the notification is triggered.
    So how do we stop the service from generating the same alert again and again?
    i.e. once we click on the notification or clear it from notifications,new alert must not be generated unless and until we specify new time.

    • Hi Prashant,

      I understood the problem. It is because the notification is present in the Service class due to which it is getting repeated again and again. I would suggest remove all the notification code from within the Service onStart() method and placing it in a different class all together. For example, create a class called Utils.java and add the notification code over there inside a method. Then, from the receiver instead of calling the Service, call the method from the Utils class. I think that should work.

      Sorry for the inconvenience. I will update this post soon.

      Regards,
      Admin

        • Hi Nabil,

          I understood the problem. It is because the notification is present in the Service class due to which it is getting repeated again and again. I would suggest remove all the notification code from within the Service onStart() method and placing it in a different class all together. For example, create a class called Utils.java and add the notification code over there inside a method. Then, from the receiver instead of calling the Service, call the method from the Utils class. I think that should work.

          Sorry for the inconvenience. I will update this post soon.

          • I’m trying to follow what you’ve said but I don’t understand. Do you call that method in the onReceive method of the receiver? And how?

      • if i call the utlis.java from the receiver, from where i should call the service. If i do not call the service the alarm will not trigger if the phone is rebooted.

  5. Hi, some functions in MyAlarmService class are deprecated because I use minimum SDK Android 4.2. How can I import successfully your code?

    The functions that are deprecated are:
    the method onStart
    the constructor Notification
    the method setLatestEventInfo

    Waiting for reply,
    Greetings

  6. Hi,

    I’ve tried to implement you’re code exactly lke you have written but I’m not receiving any notification when I try to use the values that a user can put in through date and timepicker dialogs.

    When i “hard-code” it, It works. What am I missing?

  7. hi thanks for the good tutorial.
    the thing is every time i open the app the receiver is triggered so the service is started and the notification is triggered.
    i want the user to use the app (the app have some functionality) but i need the notification to appear only at 8:00:00 am not everytime the application is opened and at 8 am
    any suggestions
    thanks in advice

    • Hi Yamen,

      I understood the problem. It is because the notification is present in the Service class due to which it is getting repeated again and again. I would suggest remove all the notification code from within the Service onStart() method and placing it in a different class all together. For example, create a class called Utils.java and add the notification code over there inside a method. Then, from the receiver instead of calling the Service, call the method from the Utils class. I think that should work.

      Sorry for the inconvenience. I will update this post soon.

  8. Hi,
    Thank you for this nice example you shared,
    I used it in my code and works perfectly fine.
    The issue i faced is, if i set a notification at specific time and my phone get rebooted before that time, then notification does not appear.

    I did some Google and added few lines of code for this issue as below,

    and now, notification get displayed, immediately after boot complete without respect of time i set. Any help will really appreciated.

  9. i want to show notification to the user at the same time means 11:45AM but it should be repeated alarm ….means this alarm should be fired on everyday at the same time can u pls tell how can i do that i m sure i need to use alarmmanager.setRepeating ….. but may i need to remove date from calendar ? reply

  10. Hey Karan,
    This is nice tute of wrote. I have a different scenario but this post seems close to my solution. My scenario is like this
    I am building an app that on its first run ask for a licensing key to verify with my server and then runs offline afterwards. This app sends some backup data on e-mail when user clicks the backup button. Now that people change the devices every next year i want that I could block the app from running in their old device and give them a new key for their new device.

    Now the problem is that my app runs offline. It only connects to internet when user want backup of his data. So how can I schedule a background task in my app that runs after every 30 days without users intervention and checks the key status on server. And if user dont have internet connection then app should wait for whenever the internet connection is available and then check the status. App need not to be running for this job. I only want that the app could check the status of the key whenever the net connection is available and then I could do the further things . Any suggestion is most welcome.

  11. Notification is only shwing when running application at particular time . and also not working while the activity is close. would u help me

  12. Hey nice tutorial but i have a problem. I selected the same target API as you but my Alarm Service has depricated methods? How do i fix? Thanks 🙂

    • You need to search for the new methods that have replaced the deprecated ones from the Android developer’s site. However, if your using Eclipse IDE then it should automatically take care of the same.

  13. how can i do the same thing when i want to get notification for particular wifi signal without actually connecting to that wifi signal.

  14. Hi Karan , For me I am not getting any notification.

    Calendar calendar = Calendar.getInstance();

    calendar.set(Calendar.MONTH, 3);
    calendar.set(Calendar.YEAR, 2015);
    calendar.set(Calendar.DAY_OF_MONTH, 2);

    calendar.set(Calendar.HOUR_OF_DAY, 1);
    calendar.set(Calendar.MINUTE, 41);
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.AM_PM,Calendar.PM);

  15. I have changed the calender time and all but it is not working when i’m starting this app that time only notification is coming.
    Can you give me the correct solution for that for which i can start notifiation at particular time only one time.

    • Modify MainActivity’s oncreate

      public void onCreate(Bundle savedInstanceState)
      {

      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      Calendar c = Calendar.getInstance();
      Date temp = c.getTime();
      Calendar calendar = Calendar.getInstance();

      calendar.set(Calendar.MONTH, 4);
      calendar.set(Calendar.YEAR, 2015);
      calendar.set(Calendar.DAY_OF_MONTH, 7);

      calendar.set(Calendar.HOUR_OF_DAY, 12);
      calendar.set(Calendar.MINUTE, 31);
      calendar.set(Calendar.SECOND, 0);
      calendar.set(Calendar.AM_PM,Calendar.PM);
      Date pm = calendar.getTime();

      if(pm.after(temp))
      {

      Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
      pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

      AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
      alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
      }

      } //end on

      Hope this helps

  16. I’m wondering if you could explain why it is necessary to start a new Service from the BroadcastReceiver, as opposed to just creating and issuing the notification from within BroadcastReceiver::onReceive(). Most examples I’ve seen don’t have this extra step of starting a service, unless it is starting a service at boot time to be able to put up notifications even if your application has not been run since rebooting.

    • Hi Adam,

      Yes you are right. In this example, my approach is wrong since at the time of writing this post I was unaware of the best practice. So please go with the recommended solution and not this one for now.

  17. Thanks for this code admin

    Now I made a calender notification app and this app notify me only selected dates and times, but I use your code, but my problem is I don’t set this code many days and time and another another notification message from notification manager.Please help me….

  18. Hi,
    Thanks a lot for the article!! This has been very helpful.
    I am new to android, and i have one doubt on this topic.
    Suppose if i have a scenario that alarm should buzz if i am in a particular place can that be done using alarm time to current time when the condition is true

  19. I tried to put a toast in a java class under util which i called from receiver but still i get the toast repeatly when i launch irrespective of the time i have mentioned.

  20. Sir,I tried to implement this code in android studio but it doesn’t show me any notification .no errors in the project.thanks

  21. Hello Karan, I am trying to implement the code mentioned in which the alarm is getting invoked at correct times but the problem is i have an array in which i have list of bithdays. i need to pass parameters with intent that is passed to alarm manager. But its Showing only the first element for all notifications. i have used Broadcast reciever. I had tried using service, but i cannot pass parameters from intent to service. Please help. I am an Android newbie

  22. Hi Dear Karan

    Thanks for your great tutorial

    I use 6 Edittext (for year & month & …) and one button to set my desire date instead of using static values for calendar.

    I want to set multiple reminder using my app; But when I click on button, just notification appears for last input date.

    Please give me suggestion to solve it

    Best Regards

    • Hi,

      Can you first try using only one EditText and button to set the date and see if the notification is appearing. You can download the updated source code from the link in the post and let me know.

      • Dear Karan

        I’ve used your updated source code.
        And this is my onClick method:

        year = Integer.parseInt(edtYear.getText().toString());
        .
        .
        .
        second = Integer.parseInt(edtSecond.getText().toString());

        Calendar c = Calndar.getInstance();
        c.set(Calendar.YEAR, year);
        .
        .
        .
        c.set(Calendar.SECOND, second);

        Intent myIntent = new Intent(MyActivity.this,MyReceiver.class);

        pendingIntent = PendingIntent.getBroadcast(MyActivity.this, 0, myIntent, 0);

        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

        alarmManager.set(AlarmManager.RTC, c.getTimeInMills(), pendingIntent);

        ———————-

        When I fill out Edittexts(for example 5 mins later) and press button, reminder will set for 5mins later.

        Again I fill out EditTexts( for example for 10mins later) and press button, reminder will set for new values (10mins later).

        Notification will show 10mins later instead of show on 5mins and 10mins later.

  23. hi karan….please can you help me i want daily reminder at a paticular time i.e like evry day at 11:30am i want reminder like popup dailog in that two buttons snooze and dismiss ..and also weekly reminder

  24. Hey Karan, thanks for sharing your codes. I have a qns, what if I have many events and each event needs a notification at different day and time?

  25. Hi Karan. Thank you very much for your tutorial. Notifications work, but I nedd they work also after reebot the device. Now it doesn’t. I tried to follow this training https://developer.android.com/training/scheduling/alarms.html#boot but notification shows immediately after reebot – not in the planned time.

    I have defined alarmCalendar (Calendar) and this is tho notification code:
    Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);

    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    alarmManager.set(AlarmManager.RTC, alarmCalendar.getTimeInMillis(), pendingIntent);

    MyReceiver.class and Utils.java is similar to yours.

    Than I added into manifest

    and into receiver:

    Do you know what could be the problem? Thank you very much for your response.

  26. Hi..
    I want to display notification on dates available in database(i.e) database will ‘ve date column and app should generate alarm notification on those dates..is it possible with above code..

  27. Hello Houdrtk I used the code Bs media does not appear to me at the bar Bs do not know why AT friendlier
    logcat
    android source close
    D/FFmpegExtractor? SniffFFMPEG failed to sniff this source

    MediaPlayer? Should have subtitle controller already set
    W/EGL_genymotion? eglSurfaceAttrib not implemented
    09-28 18:19:27.309 520-534/? I/ActivityManager? Displayed com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.Alarm_settings: +657ms
    D/Genyd? Received Set Clipboard
    D/Genymotion? Received Set Clipboard
    I/ProcessStatsService? Prepared write state in 2ms
    I/ProcessStatsService? Pruning old procstats: /data/system/procstats/state-2015-09-25-19-20-41.bin
    D/dalvikvm? GC_CONCURRENT freed 1092K, 24% free 7963K/10436K, paused 5ms+4ms, total 39ms
    09-28 18:24:00.001 520-520/? I/ActivityManager? Killing 1134:com.android.email/u0a29 (adj 15): empty for 1848s
    09-28 18:24:00.001 520-520/? I/ActivityManager? Killing 668:com.android.settings/1000 (adj 15): empty for 1853s
    09-28 18:24:00.005 520-520/? I/ActivityManager? Killing 1155:com.android.exchange/u0a30 (adj 15): empty for 1853s
    09-28 18:25:00.028 520-520/? I/ActivityManager? Killing 1110:com.android.calendar/u0a21 (adj 15): empty for 1832s
    09-28 18:25:00.028 520-520/? I/ActivityManager? Killing 955:com.android.mms/u0a9 (adj 15): empty for 1832s
    09-28 18:25:00.028 520-520/? I/ActivityManager? Killing 851:android.process.media/u0a5 (adj 15): empty for 1832s
    09-28 18:25:00.068 520-696/? D/CountryDetector? No listener is left
    09-28 18:26:01.592 75-75/? D/Genyd? Received Set Clipboard
    09-28 18:26:01.592 75-75/? D/Genymotion? Received Set Clipboard
    09-28 18:27:11.595 75-75/? D/Genyd? Received Set Clipboard
    09-28 18:27:11.595 75-75/? D/Genymotion? Received Set Clipboard
    09-28 18:27:33.458 75-75/? D/Genyd? Received Set Clipboard
    09-28 18:27:33.458 75-75/? D/Genymotion? Received Set Clipboard
    09-28 18:28:16.494 75-75/? D/Genyd? Received Set Clipboard
    09-28 18:28:16.494 75-75/? D/Genymotion? Received Set Clipboard
    09-28 18:28:17.882 682-685/? D/dalvikvm? GC_CONCURRENT freed 464K, 17% free 3560K/4252K, paused 1ms+1ms, total 10ms
    09-28 18:28:44.986 654-657/? D/dalvikvm? GC_CONCURRENT freed 317K, 12% free 3259K/3688K, paused 2ms+0ms, total 10ms
    09-28 18:30:01.021 520-565/? D/MobileDataStateTracker? default: setPolicyDataEnable(enabled=true)
    09-28 18:30:07.081 75-75/? D/Genyd? Received Set Clipboard
    09-28 18:30:07.081 75-75/? D/Genymotion? Received Set Clipboard
    09-28 18:30:26.580 520-565/? D/ConnectivityService? Sampling interval elapsed, updating statistics ..
    09-28 18:30:26.580 520-565/? D/ConnectivityService? Done.
    09-28 18:30:26.580 520-565/? D/ConnectivityService? Setting timer for 720seconds
    D/Genyd? Received Set Clipboard
    Genymotion?
    Received Set Clipboard
    Set Clipboard
    Received Set Clipboard

  28. Hello
    I wrote code in the project back problem in the non-appearance notification
    logcat
    Enabling debug mode 0
    09-29 00:38:54.785 2213-2231/? W/EGL_emulation? eglSurfaceAttrib not implemented
    09-29 00:38:54.785 2213-2231/? W/OpenGLRenderer? Failed to set EGL_SWAP_BEHAVIOR on surface 0xaf0356e0, error=EGL_SUCCESS
    09-29 00:38:55.256 2213-2213/? I/Choreographer? Skipped 51 frames! The application may be doing too much work on its main thread.
    09-29 00:38:55.745 950-979/? I/ActivityManager? Displayed com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.MainActivity: +1s770ms
    09-29 00:38:56.120 950-1329/? I/ActivityManager? Killing 1817:com.android.managedprovisioning/u0a7 (adj 15): empty #17
    09-29 00:38:56.988 950-1329/? I/ActivityManager? START u0 {cmp=com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.azkary} from uid 10064 on display 0
    09-29 00:38:56.991 950-1329/? V/WindowManager? addAppToken: AppWindowToken{3cbcee1f token=Token{7ff0dbe ActivityRecord{18037c79 u0 com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.azkary t54}}} to stack=1 task=54 at 1
    09-29 00:38:56.993 950-1117/? W/AudioTrack? AUDIO_OUTPUT_FLAG_FAST denied by client
    09-29 00:38:57.030 950-969/? V/WindowManager? Adding window Window{12366735 u0 com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.azkary} at 3 of 8 (after Window{27930127 u0 com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.MainActivity})
    09-29 00:38:57.117 2213-2231/? W/EGL_emulation? eglSurfaceAttrib not implemented
    09-29 00:38:57.117 2213-2231/? W/OpenGLRenderer? Failed to set EGL_SWAP_BEHAVIOR on surface 0xb43d9680, error=EGL_SUCCESS
    09-29 00:38:57.562 950-979/? I/ActivityManager? Displayed com.mohamed.elsayed.azkardifferent/elsayed.mohamed.com.azkardifferent.azkary: +561ms
    09-29 00:38:57.979 950-1136/? D/TaskPersister? removeObsoleteFile: deleting file=47_task.xml
    09-29 00:38:57.979 950-1136/? D/TaskPersister? removeObsoleteFile: deleting file=47_task_thumbnail.png
    09-29 00:44:02.898 83-83/? D/Genyd? Received Set Clipboard
    09-29 00:44:02.898 83-83/? D/Genymotion? Received Set Clipboard
    09-29 00:44:37.403 83-83/? D/Genyd? Received Set Clipboard
    09-29 00:44:37.403 83-83/? D/Genymotion? Received Set Clipboard
    09-29 00:44:40.663 83-83/? D/Genyd? Received Set Clipboard
    09-29 00:44:40.664 83-83/? D/Genymotion? Received Set Clipboard

  29. hello….
    i want to display a notification on every day at particular time ..lets say 2:30pm. i tried the above code but i am finding continousoly notification when i click the app ……..so please give me answer……..i have used utill class also…

  30. Hi karan,

    alarm is ringing at the fix time when i give hard coded time and alarm manager set them at correct time and alarm ring well……
    but when i launch/click on app after some time then notification open just because alarm set in on create method…..and then alarm manager do not take previous hardcoded time …..i seems that it take system current time………. pls give me solution

  31. In my application, there’s a alarm service, and I find that if user change it’s date or time to a passed time. My alarm will not be triggered at the time I expect.

    So, I may have to reset all the alarms again. Is there an date and time change listener in android?

    if i used…….

    if user change date or time in phone,
    then alarm is not ringing at fix time …alarm rings immediately…………

    please give solution………

  32. Hi I just tried your application (used the latest version in github) and the Receiver class doesn’t seem to get called. I got a notification the first time I ran the application, but afterwards, I don’t receive any more notifications. I tried adding logs and it seems that the OnReceive in the Receiver class is never called. Any clues to why?

  33. Hi Karan Balkar Sir,

    I create an interval alarm which is working good but alarm is ringing for 1st time only but in the service and data base it is updating the alarm for every one minute if I can get solution please help me.

  34. Hi! I have a doubt.. Suppose I set the time to be 8:20 am. Now, the notification is displayed at this time.
    Now everytime I open the app after 8:20 am, the notification is displayed.
    I guess this is because the activity is created again.
    How can I make sure that the notification is generated only once a day and not everytime I open the app.?

  35. Hello Karan!

    Is it possible to enter an alarm outside of the application. That is, is there a way for the user to set his own alarms and for the broadcastreciever to receive them as well? Is it a general/built-in function for alarms or is it just possible to decide your own time within the function?

  36. Hello Karan,
    Nice tutorial and great comments. I have looked at the updated code and it is very similar to most tutorials I have seen on the internet and GitHub. I particularly like the separation of duties you have outlined. It just makes since. Here is my hopes, I need a Alarm Manager similar to yours. What I am looking for is the ability to set unique multiple alarms, show a notification when the alarm has expired to the notification pull down, be able to swipe to dismiss and when clicked on, open an activity, use an extra passed at the time of the creation of the alarm and use that extra (rowid) to query a database and populate several text views. All the code I have seen so far and tried, will loose the extra if the application is not running. Meaning, back press to the launcher desktop. And the notification does not stay in the pull down unless it is set to ongoing(true). Is this code you provide capable of doing this? And or are you available to help with my existing code to achieve my goals.

  37. In my application i want that in case if my if condition get true then it should generate an alarm,then what should i do to implement this.where should i write the condition in above code to generate alarm? Plz help

  38. Hi,
    Can you help me to complete my task. I did this code and it works fine.can you lease tell to how to set alarm for every 3 months and should stop when click notification in android. and at the end of the period say 2 years alarm should stop completely.

  39. thank you for a good code.. thanks a lot..

    i ve been trying to

    thats i want…
    when i click the notification its going to another activity? how to implement?
    please suggest any code?

  40. Hi karan
    Thanku for ur code
    I’m getting notifications whenever I opened the app. But I want notifications at a specific time. I tried as u mentioned the modified way but still not yet getting.
    Can u provide modified code?
    Thanks in advance…:)

  41. sir pls sir can u give me a code for the same above mentioned example.. Actually one part of my project is reminder application, where the user should be able to set a reminder that is message on a specific day and time, and on that day and time that reminder should pop up as a notification.. Actually from a long time m trying this.. i got many code n i tried it but actually i m working on android studio and all the codes that i have tried as well ur code are in eclipse due to which i m getting errors in studio and the most common error is in the line-
    notification.setLatestEventInfo(context, “AlarmManagerDemo”, “This is a test message!”, pendingNotificationIntent);

    sir please can u provide me with a perfect souce code which will work in android studio.. sir plsss plss help…

  42. hi
    i have 1 problem …
    i set time for notification ex. 8 am then it will work proper but if i will open app minse MainActivity then it notificaton

    then plz give the sugetion for this problem ..
    i wont only one time notificaton but it will give multipal time give…

  43. hi..
    My problem is when i register all date+time(from my DB) for alarms to my AlarmManager,always the last one is fired.i dont know what wrong i did.pls give sugestion and if possible then pls give some code how data can be passed from DB to setAlarm();

  44. Is it necessary to set month and year? Because if we want the notification to appear everyday, why should we set month and year?

    • Hi Suyash,

      What problem are you facing? Is the notification not getting triggered at the time set by you. Please let me know if you are getting any exceptions in your logcat.

  45. hi i want set deffrent times like

    calendar.set(Calendar.HOUR_OF_DAY, 3);
    calendar.set(Calendar.MINUTE, 12);

    calendar.set(Calendar.HOUR_OF_DAY, 4);
    calendar.set(Calendar.MINUTE, 15);

    how can i do that ? set alaram to deffrent times like show up?

  46. I am getting an error as…
    notification.setLatestEventInfo(this.getApplicationContext(), “AlarmManagerDemo”, “This is a test message!”, pendingNotificationIntent);

    setLatestEventInfo is marked in red color

    plz hlp me with this immediately…

  47. First of all, thanks for sharing your knowledge. I am new in android programing so I am having some problems:
    1. Don’t know why but after the alarm being fired in time and date settled the alarm is not cancelled and it fires again everytime I open the application.
    2. How can I receive the notification ID from the MainActivity, considering that in my app the user will create many different alarms?
    3. How can I cancel the alarm using the ID when the user swipe the notification on the screen?

    I changed your code as following, in the deprecated part:

    NotificationManager mManager;
    mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
    Intent intent1 = new Intent(this.getApplicationContext(),Task.class);
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(),1, intent1,PendingIntent.FLAG_UPDATE_CURRENT);

    Notification notification = new NotificationCompat.Builder(this)
    .setContentIntent(pendingNotificationIntent)
    .setContentTitle(“Reminder”)
    .setContentText(“Teste de mensagem”)
    .setSmallIcon(R.mipmap.ic_launcher)
    .setWhen(System.currentTimeMillis())
    .build();
    mManager.notify(1,notification);

    notification.flags |= Notification.FLAG_AUTO_CANCEL;
    notification.flags |= Notification.DEFAULT_SOUND;

  48. I have vehicle tracking application in which I need to get location co ordintes and send them to server after every 5 sec for smooth track. It works fine for 45 mins but after that it gives ANR(Application not responding) error. I am using same method as above, but service is implemeting location listener.
    I tried Asyntask for network process, timer which sleeps after sometime, now using wakelock. Kindly suggest soltuion to this ANR problem.

  49. what if i reboot my system before alarm goes off?
    will it trigger the alarm??

    And you are using service which will consume battery life,

    • Hi,

      If you reboot your system, the alarm will not trigger since it is not handled as of now. In that case, you need to listen for the BOOT_COMPLETED receiver and implement a logic for the same. Currently, I have used an Alarm Service that runs in the background. However, it does not consume much battery,

      Regards,
      Karan

  50. Hi Karan,

    If i put MainActivity code in Some other Activity which is not launcher activity.
    In that case this should work or not ?
    I tried one sample and its not working.
    Can you clarify over the logic.

Leave a Reply

Your email address will not be published. Required fields are marked *