Search code examples
androidnotificationsalarmmanagerandroid-notificationsandroid-alarms

How to alert alarm message when outside of the app in android?


I am trying this code to popup the alarm message. Its working when launching or opening the app, but it doesn't say any popup message while outside of the app. I am so confused, i don't know what i am doing wrong.

String alarmtime = cur.getString(cur.getColumnIndex(DBDATA.LG_ALARMTIME));
//Reminder
String[] timesplit = alarmtime.split(":"); 
int hour = Integer.parseInt(timesplit[0]);
int minute = Integer.parseInt(timesplit[1]);
System.out.println(hour);
System.out.println(minute); 

AlarmManager alarmMgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, ShortTimeEntryReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0); 

Calendar alarm = new GregorianCalendar();
alarm.setTimeInMillis(System.currentTimeMillis());
alarm.set(Calendar.HOUR_OF_DAY, hour);
alarm.set(Calendar.MINUTE, minute); 
alarm.set(Calendar.SECOND, 0);  
System.out.println(System.currentTimeMillis());
System.out.println(alarm.getTimeInMillis());
if (System.currentTimeMillis() > alarm.getTimeInMillis()){
    alarm.setTimeInMillis(alarm.getTimeInMillis()+ 24*60*60*1000);// Okay, then tomorrow ...
    alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);
}
else
{
    alarmMgr.set(AlarmManager.RTC_WAKEUP, alarm.getTimeInMillis(),pendingIntent);                 
}

I need to pop up the alarm message outside of the app(i.e) exactly like the alarm does. Thanks for your help guys,


Solution

  • You probably need a BroadcastReceiver.

    As you can read in this question : BroadcastReceiver not receiving an alarm's broadcast

    You have to build the intent like this :

    Intent alarmIntent = new Intent(this, AlarmReceiver.class);
    PendingIntent sender = PendingIntent.getBroadcast(this, "CHECK_ALARM_CODE", alarmIntent, 0);
    

    And receive the alarm like this :

        public class AlarmReceiver extends BroadcastReceiver{
          @Override
          public void onReceive(Context context, Intent intent) {
             Toast.makeText(context, "Alarm worked.", Toast.LENGTH_LONG).show();
             Log.d("OK", "AlarmReceiver.onReceive");
          }
    }
    

    Don't forget to register your broadcast in your manifest file.