Skip to content

Instantly share code, notes, and snippets.

@BrandonSmith
Last active July 19, 2023 19:11
Show Gist options
  • Select an option

  • Save BrandonSmith/6679223 to your computer and use it in GitHub Desktop.

Select an option

Save BrandonSmith/6679223 to your computer and use it in GitHub Desktop.
Quick example of how to schedule a notification in the future using AlarmManager
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.cards.notification">
<uses-sdk
android:minSdkVersion="17"
android:targetSdkVersion="17" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.cards.notification.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>
<receiver android:name=".NotificationPublisher" />
</application>
</manifest>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/action_5"
android:title="5 seconds"
android:showAsAction="never" />
<item android:id="@+id/action_10"
android:title="10 seconds"
android:showAsAction="never" />
<item android:id="@+id/action_30"
android:title="30 seconds"
android:showAsAction="never" />
</menu>
package com.cards.notification;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.os.SystemClock;
import android.view.Menu;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_5:
scheduleNotification(getNotification("5 second delay"), 5000);
return true;
case R.id.action_10:
scheduleNotification(getNotification("10 second delay"), 10000);
return true;
case R.id.action_30:
scheduleNotification(getNotification("30 second delay"), 30000);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void scheduleNotification(Notification notification, int delay) {
Intent notificationIntent = new Intent(this, NotificationPublisher.class);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, 1);
notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay;
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
private Notification getNotification(String content) {
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle("Scheduled Notification");
builder.setContentText(content);
builder.setSmallIcon(R.drawable.ic_launcher);
return builder.build();
}
}
package com.cards.notification;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class NotificationPublisher extends BroadcastReceiver {
public static String NOTIFICATION_ID = "notification-id";
public static String NOTIFICATION = "notification";
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = intent.getParcelableExtra(NOTIFICATION);
int id = intent.getIntExtra(NOTIFICATION_ID, 0);
notificationManager.notify(id, notification);
}
}
@dn1vara

dn1vara commented Dec 26, 2017

Copy link
Copy Markdown

Easy to understand...Thanks

@amirdora

amirdora commented Jan 5, 2018

Copy link
Copy Markdown

thank you very much! Very well written easy to understand.

@GeneDalton

Copy link
Copy Markdown

Thanks. Very easy to read and still relevent today.

@meshileya

Copy link
Copy Markdown

What if i did like to repeat this alarm, how can i go about that pls???

@Mahmoood

Mahmoood commented Apr 26, 2018 •

Copy link
Copy Markdown

But if the device had shutdown, all scheduled alarms will be cancelled automatically.
So you should listen on an system event (When the device boot android.intent.action.BOOT_COMPLETED) to re-schedule your required alarms.
For more details:
https://developer.android.com/training/scheduling/alarms.html#boot

@lossurdo

lossurdo commented May 5, 2018

Copy link
Copy Markdown

Great!!

@talhakabakus

Copy link
Copy Markdown

In fact, not worked for me for a device whose API level is 27 (Oreo - 8.1). Just could not see anything.

@JackRichardBusiness

Copy link
Copy Markdown

Wonderful job! Worked perfectly!

@lazarodev

Copy link
Copy Markdown

Thank you! very helpful.

@annalenamueller

Copy link
Copy Markdown

For higher APIs you have to create a NotificationChannel first. Otherwise no notification will be viewed.

@tieorange

Copy link
Copy Markdown

Clean af. Cheers

@amritpal26

Copy link
Copy Markdown

Very Helpful! I have been looking for this for so long.

@AndrewKZY

Copy link
Copy Markdown

In fact, not worked for me for a device whose API level is 27 (Oreo - 8.1). Just could not see anything.

@talhakabakus did u manage to get it working?

@yilmazgokhan

Copy link
Copy Markdown

Thank you :) I want to ask how can I set multiple alarm, can you share your experience to us?

@SmailyCarrilho

Copy link
Copy Markdown

It was the only notification scheduler that worked for me so far. Thank you very much!

@raviteja74

Copy link
Copy Markdown

At last it worked for me also Thanks buddy

@danzada1

danzada1 commented Dec 9, 2019

Copy link
Copy Markdown

Thanks this is great!!!

@sh3rly13

Copy link
Copy Markdown

Cannot resolve the symbol "menu" - doesnt work it

@aishwaryaubhrani

Copy link
Copy Markdown

Thank You! Helped me a lot XD

@adnanhaider237

Copy link
Copy Markdown

Not working on After android 10 update.

@aman-junaid

aman-junaid commented Aug 11, 2020 •

Copy link
Copy Markdown

Even though I had to do a few changes related to notification channel. This was extremely helpful! Thanks a lot 👍 🥇

@anubhab-parallel-reality

anubhab-parallel-reality commented Sep 7, 2020 •

Copy link
Copy Markdown

Why does it look very similar to this tutorial posted on May 16, 2019. If this is your original code, you should tell the publisher as I see your's is from much older time

@priyacoder1794

Copy link
Copy Markdown

After killing application. Notifications not triggering.

@faiz786

faiz786 commented Oct 8, 2020

Copy link
Copy Markdown

Not working on After android 10 update.

Did you find any solution

@faiz786

faiz786 commented Oct 8, 2020

Copy link
Copy Markdown

After killing application. Notifications not triggering.

Did u find any solution

@BilalZurmati

BilalZurmati commented Nov 16, 2020 •

Copy link
Copy Markdown

Not working on After android 10 update.
make sure to add notification channel for api level greater than Android 7

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
String channelName = "My Background Service";
NotificationChannel chan = new NotificationChannel("com.offline.english.dictionary.speech.translator",
channelName, NotificationManager.IMPORTANCE_LOW);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
notificationManager.createNotificationChannel(chan);
}

    notificationManager.notify(2, notification);

also add this to get notification funtion

    Notification.Builder builder = null;
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
        builder = new Notification.Builder(this,
                "com.offline.english.dictionary.speech.translator");
    }
    else {
        builder = new Notification.Builder(this);
    }

@7afidi

7afidi commented Jan 8, 2021

Copy link
Copy Markdown

Thanks !

@UbaidKhan91

Copy link
Copy Markdown

notification not received after kill application Android 10 any one help..?

@PaulNCrotty

PaulNCrotty commented May 14, 2021 •

Copy link
Copy Markdown

@BilalZurmati - thank you! This was a big help.

@baponkar

Copy link
Copy Markdown

Thankyou for your shareing

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment