Create a gist now

Instantly share code, notes, and snippets.

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);
}
}
@xswapnull

Thanks man ! This gist has helped me a lot.

@luckcfm
luckcfm commented Aug 25, 2014

Thank you, it helped me a lot!!!!

@marcusficner

+1

@joomi
joomi commented Dec 5, 2014

Thanks a lot!
Very helpful {:

@sfxmaker
sfxmaker commented Dec 8, 2014

Click on notification in the Notification Manager does not work, even though i tried for 8 hours to fix this. Anyone having a solution ?

@xiprox
xiprox commented Dec 16, 2014

@BrandonSmith, thanks for the clean and useful code!

@sfxmaker, did you try Builder.setContentIntent(PendingIntent) ?

@chihebnabil

Thanks

@dyaskur
dyaskur commented May 9, 2015

thx, i hope i can use this.

@dexcell
dexcell commented Sep 6, 2015

Thanks man

@reastland

Very helpful. Thanks a million!

@reynaldo14

It works even if I turn off the smarphone ?

@Bardo-Konrad

I used your code with subsequently for several notifications with different text and different delay but none showed up. Why?

@bayanJ
bayanJ commented Dec 28, 2015

Thanks, it helped me a lot

@nazmul-nasir

app crashed at first launching. receiver has already registered in manifest file ... what would be the cause ? (I am using android studio)

@prayansh

What if for some reason I want to cancel the already scheduled notification, how would I go about it?

@JaydipRadadiya

perfect! Thanks a lot..

@TufferyJordan

Au top !
Thanks a lot for your help ;-)

@tonyshkurenko

Love you, bro

@Arshadse

Sir how to do Auto silent mobile on the user given time,such as Start time and End time. the mobile is silent from start time and goes to un silent if the time reached to EndTime...plz help,im new in android,,Send me a code
Arshadkha48@gmail.com,

@sree91
sree91 commented Jun 2, 2016 edited

public class AlarmMonitoring extends Activity implements FetchDataListener {

public static boolean errored = false;
Context ctx=AlarmMonitoring.this; 
public ArrayList<view360.aws.alarmmonitor.TrackingBean> detailTrackData=null;

Spinner spUserSelector;
Spinner spAlarmType;
private ListView listview;
ArrayList<?> DashboradUsers;
private Timer autoUpdate;
private ApplicationAdapter LSTadapter;
private ApplicationAdapter adapter;

// private ProgressDialog dialog;
private String username=LoginActivity.Username;
static String Type ="Default Data";
Button Logout;
ConnectivityManager connectivityManager;

static NotificationManager NM;
 int lastViewedPosition=0;
 int topOffset=0;
private String message="";
    String U,P;

@Override
public void onCreate(Bundle savedInstanceState) {

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






    Logout = (Button) findViewById(R.id.logout);

    Logout.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {


             Intent newIntent = new Intent(AlarmMonitoring.this,
                     LoginActivity.class);
             onPause();
             startActivity(newIntent);
             android.os.Process.killProcess(android.os.Process.myPid());
             Toast.makeText(AlarmMonitoring.this, "You are loged out!!", Toast.LENGTH_SHORT).show();

         }
        }); 





            if(LoginActivity.Username!=null && LoginActivity.Previlege!=null)
            {U=LoginActivity.Username;P= LoginActivity.Previlege;}
            else{
                U="NUll";P="NUll";
                Intent newIntent = new Intent(AlarmMonitoring.this,
                        LoginActivity.class);
             onPause();

             startActivity(newIntent);
             android.os.Process.killProcess(android.os.Process.myPid());
             Toast.makeText(AlarmMonitoring.this, "Your session has been expired!! please login again to continue..", Toast.LENGTH_SHORT).show();
            }



    DashboradUsers = WebService.invokeDashboardUsers(U,P);
     ArrayList<String> return_likes = new ArrayList<String>();
     return_likes.add("Select");
    for(int i=0;i<DashboradUsers.size();i++)
    {
        return_likes.add(DashboradUsers.get(i).toString().trim());
    }



  spUserSelector = (Spinner)findViewById(R.id.UserSelector);




  ArrayAdapter<String> adptSpnCategory = new ArrayAdapter<String>(this,R.layout.list_row,  return_likes);
  adptSpnCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
  spUserSelector.setAdapter(adptSpnCategory);
  spUserSelector.setOnItemSelectedListener(new OnItemSelectedListener() 
  {
      public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
      {
      }
      public void onNothingSelected(AdapterView<?> arg0) 
      {
      }
  });


  spUserSelector.setAdapter(adptSpnCategory);
  spUserSelector.setOnItemSelectedListener(
  new AdapterView.OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) 
        {
            String position = (String) spUserSelector.getSelectedItem();;

            if(position=="Select")
            {

                username=LoginActivity.Username;

            }
            else 

            username=position;
            //customGridAdapter.clear();
            if(detailTrackData.size()!=0 &&  LSTadapter.getCount()!=0){
                 detailTrackData.clear();
             LSTadapter.clear();}
            initView();
        }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {



        }

    }
);


      String Alarms[] = { "Alarm Panel","NoEb", "SOB", "LowBattery", "SiteDown","HighTemperature", "Inactive","LowFuel","Door","FireStatus", };




     spAlarmType= (Spinner) findViewById(R.id.AlarmType);


      ArrayAdapter<String>  adapterAlarms = new ArrayAdapter<String>(this,R.layout.list_row, Alarms);
      adapterAlarms.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
      spAlarmType.setAdapter( adapterAlarms);
      spAlarmType.setOnItemSelectedListener(new OnItemSelectedListener() 
      {
       public void onItemSelected(AdapterView<?> arg0, View arg1,int arg2, long arg3) 
       {
       }
       public void onNothingSelected(AdapterView<?> arg0) 
       {
       }
      });

      spAlarmType.setOnItemSelectedListener(new OnItemSelectedListener() {

            @Override
            public void onItemSelected(AdapterView<?> adapter, View v,
            int position, long id) {
                String item = adapter.getItemAtPosition(position).toString();
                Type=item.toString().trim();



                if(Type=="Alarm Panel")
                {

                    Type="DefaultData";

                }


                 if(detailTrackData.size()!=0 &&  LSTadapter.getCount()!=0){
                     detailTrackData.clear();
                 LSTadapter.clear();}
                 initView();        

            }

            @Override
            public void onNothingSelected(AdapterView<?> arg0) {
                            }
        });



     initView();


        Bundle bundle = getIntent().getExtras();
        message = bundle.getString("message");

        if(!message.equalsIgnoreCase(""))
        {
            Hello();
        }


}


static int notificationNO=1;


@Override
protected void onResume() {

    super.onResume();
    autoUpdate = new Timer();
      autoUpdate.schedule(new TimerTask() {
       @Override
       public void run() {
        runOnUiThread(new Runnable() {

        public void run() {
             int x=0;
             if(!detailTrackData.equals(null))
             {
              x=detailTrackData.size();

             }


            ArrayList<String> towerList1 = new ArrayList<String>();
             for(int i=0;i<detailTrackData.size();i++)
             {
             towerList1.add(detailTrackData.get(
                        i).getAssetNo());}



             if(detailTrackData.size()!=0 &&  LSTadapter.getCount()!=0){
                 detailTrackData.clear();
             LSTadapter.clear();}


         initView();


         int y=detailTrackData.size();
         ArrayList<String> towerList2 = new ArrayList<String>();
         for(int i=0;i<detailTrackData.size();i++)
         {
         towerList2.add(detailTrackData.get(
                    i).getAssetNo());

         }



         if((x==y)){


             for (String item : towerList2)
             {
                 if (!(towerList1.contains(item))){


                     Toast.makeText(getApplicationContext(), "Dataset changed" +" "+y, Toast.LENGTH_SHORT).show();
                    NoTiFiCaTiON();

                 }

             }



         }

         else if(x>y)

         { Toast.makeText(getApplicationContext(), "Alarms reduced " +" "+y, Toast.LENGTH_SHORT).show();

         NoTiFiCaTiON();
         }




         else if(x<y)

         { Toast.makeText(getApplicationContext(), "Alarms Increased" +" "+y, Toast.LENGTH_SHORT).show();


         NoTiFiCaTiON();
         }



         }
        });
       }
      }, 0, 60000); 
}


private void initView() {




    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo wifiNetwork = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_WIFI);
    NetworkInfo mobileNetwork = connectivityManager
            .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);

    if ((wifiNetwork != null && wifiNetwork.isConnected())
            || (mobileNetwork != null && mobileNetwork.isConnected())) {

    } else {

        internetConnectionAlert();

    }


    detailTrackData = WebService.invokeAlarmMonitor(username,"", Type);


    if (detailTrackData.size()!=0) {

    }

    if(!errored){

        if(detailTrackData.size()!=0){
            listview = (ListView) findViewById(R.id.detailList);
            lastViewedPosition = listview.getFirstVisiblePosition();


            View v = listview.getChildAt(0);
            topOffset = (v == null) ? 0 : v.getTop();
            LSTadapter = new ApplicationAdapter(AlarmMonitoring.this,detailTrackData);

            listview.setAdapter(LSTadapter);
            listview.setSelectionFromTop(lastViewedPosition, topOffset);

            LSTadapter.notifyDataSetChanged();



        }else{


        }

    }else{

        Toast.makeText(getApplicationContext(), "Error occured in invoking webservice, please check the internet connection", Toast.LENGTH_SHORT).show();

    }

    errored = false;      

}





@Override
public void onFetchComplete(ArrayList<TrackingBean> data) {



    adapter = new ApplicationAdapter(this, data);

    listview = (ListView) findViewById(R.id.detailList);
    listview.setAdapter(adapter);
    adapter.notifyDataSetChanged();

}


@Override
public void onFetchFailure(String msg) {


    //  dialog.dismiss();

    Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
}   



@Override
public void onBackPressed() {

    super.onBackPressed();
    super.stopService(getIntent());
}


@SuppressWarnings("deprecation")
private void internetConnectionAlert() {

    AlertDialog alertDialog = new AlertDialog.Builder(AlarmMonitoring.this)
            .create();
    alertDialog.setTitle("Network Error");
    alertDialog.setMessage("check your Internet connection");

    alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
        public void onClick( DialogInterface dialog, final int which) {

        }
    });
    alertDialog.setIcon(R.drawable.delete);

}   



public void Hello() {



        Intent newIntent = new  Intent(AlarmMonitoring.this,
            AndroidBottomTabActivity.class);
        startActivity( newIntent);
        onResume();
        AlarmMonitoring.this.finish();


    }
public void NoTiFiCaTiON() {

     try {
         Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
         Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
         r.play();r.play();r.play();


         NM=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);

         @SuppressWarnings("deprecation")
        Notification notify=new Notification(R.drawable.notification,"TSIM Alarm",System.currentTimeMillis());
         @SuppressWarnings("unused")
        Context context = ctx.getApplicationContext();
         Intent notificationIntent = new Intent(ctx, AlarmNotify.class);

         PendingIntent contentIntent = PendingIntent.getActivity(ctx, 0, notificationIntent, 0);

         notify.setLatestEventInfo(getApplicationContext(),"Total Alarms:"+notificationNO,"Alarms dataset has been changed!",contentIntent);
         NM.notify(0, notify);

         notificationNO++;

      } catch (Exception e) {
          e.printStackTrace();

      }




    }

}

@sree91
sree91 commented Jun 2, 2016

this is my code can any one help to get notifications even app is closed and cleared from recent apps

@nguyenquangsang

i write the same as his code but nothing show up. Anyone help me :(

@Jawnnypoo

It is worth noting that you need to re-register all notifications with AlarmManager if the users resets their device

@exc414
exc414 commented Oct 2, 2016

This code was not working for until I put the whole package name in the androidmanifest.xml file.

I had to put this : <receiver android:name="com.somename.packagename.NotificationPublisher" />
Instead of just : <receiver android:name=".NotificationPublisher" />

Thank you for the code.

@BalaramTupili

No Errors are coming but How to create link between Activity_main.xml and main.xml

@heetel
heetel commented Jan 9, 2017

Thanks a lot. Very helpful

@jeffyzxc

Thaaankksss bruhh!

@a3y3
a3y3 commented Mar 28, 2017

This helped loads. Exactly what I was looking for.

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