Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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

This comment has been minimized.

Show comment Hide comment
@xswapnull

xswapnull Jul 23, 2014

Thanks man ! This gist has helped me a lot.

Thanks man ! This gist has helped me a lot.

@luckcfm

This comment has been minimized.

Show comment Hide comment
@luckcfm

luckcfm Aug 25, 2014

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

luckcfm commented Aug 25, 2014

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

@marcusficner

This comment has been minimized.

Show comment Hide comment
@marcusficner

marcusficner Sep 4, 2014

+1

+1

@joomi

This comment has been minimized.

Show comment Hide comment
@joomi

joomi Dec 5, 2014

Thanks a lot!
Very helpful {:

joomi commented Dec 5, 2014

Thanks a lot!
Very helpful {:

@sfxmaker

This comment has been minimized.

Show comment Hide comment
@sfxmaker

sfxmaker 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 ?

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

This comment has been minimized.

Show comment Hide comment
@xiprox

xiprox Dec 16, 2014

@BrandonSmith, thanks for the clean and useful code!

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

xiprox commented Dec 16, 2014

@BrandonSmith, thanks for the clean and useful code!

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

@chihebnabil

This comment has been minimized.

Show comment Hide comment
@chihebnabil

chihebnabil Dec 26, 2014

Thanks

Thanks

@dyaskur

This comment has been minimized.

Show comment Hide comment
@dyaskur

dyaskur May 9, 2015

thx, i hope i can use this.

dyaskur commented May 9, 2015

thx, i hope i can use this.

@dexcell

This comment has been minimized.

Show comment Hide comment
@dexcell

dexcell Sep 6, 2015

Thanks man

dexcell commented Sep 6, 2015

Thanks man

@reastland

This comment has been minimized.

Show comment Hide comment
@reastland

reastland Oct 19, 2015

Very helpful. Thanks a million!

Very helpful. Thanks a million!

@reynaldo14

This comment has been minimized.

Show comment Hide comment
@reynaldo14

reynaldo14 Oct 26, 2015

It works even if I turn off the smarphone ?

It works even if I turn off the smarphone ?

@Bardo-Konrad

This comment has been minimized.

Show comment Hide comment
@Bardo-Konrad

Bardo-Konrad Nov 13, 2015

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

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

@bayanJ

This comment has been minimized.

Show comment Hide comment
@bayanJ

bayanJ Dec 28, 2015

Thanks, it helped me a lot

bayanJ commented Dec 28, 2015

Thanks, it helped me a lot

@nazmul-nasir

This comment has been minimized.

Show comment Hide comment
@nazmul-nasir

nazmul-nasir Jan 16, 2016

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

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

@prayansh

This comment has been minimized.

Show comment Hide comment
@prayansh

prayansh Jan 27, 2016

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

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

@JaydipRadadiya

This comment has been minimized.

Show comment Hide comment
@JaydipRadadiya

JaydipRadadiya Feb 20, 2016

perfect! Thanks a lot..

perfect! Thanks a lot..

@TufferyJordan

This comment has been minimized.

Show comment Hide comment
@TufferyJordan

TufferyJordan Mar 2, 2016

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

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

@tonyshkurenko

This comment has been minimized.

Show comment Hide comment
@tonyshkurenko

tonyshkurenko Apr 5, 2016

Love you, bro

Love you, bro

@Arshadse

This comment has been minimized.

Show comment Hide comment
@Arshadse

Arshadse Apr 19, 2016

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,

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

This comment has been minimized.

Show comment Hide comment
@sree91

sree91 Jun 2, 2016

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 commented Jun 2, 2016

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

This comment has been minimized.

Show comment Hide comment
@sree91

sree91 Jun 2, 2016

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

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

This comment has been minimized.

Show comment Hide comment
@nguyenquangsang

nguyenquangsang Jun 17, 2016

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

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

@Jawnnypoo

This comment has been minimized.

Show comment Hide comment
@Jawnnypoo

Jawnnypoo Jul 26, 2016

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

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

@exc414

This comment has been minimized.

Show comment Hide comment
@exc414

exc414 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.

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

This comment has been minimized.

Show comment Hide comment
@BalaramTupili

BalaramTupili Nov 1, 2016

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

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

@PagesByZ

This comment has been minimized.

Show comment Hide comment
@heetel

This comment has been minimized.

Show comment Hide comment
@heetel

heetel Jan 9, 2017

Thanks a lot. Very helpful

heetel commented Jan 9, 2017

Thanks a lot. Very helpful

@jeffyzxc

This comment has been minimized.

Show comment Hide comment
@jeffyzxc

jeffyzxc Mar 17, 2017

Thaaankksss bruhh!

Thaaankksss bruhh!

@a3y3

This comment has been minimized.

Show comment Hide comment
@a3y3

a3y3 Mar 28, 2017

This helped loads. Exactly what I was looking for.

a3y3 commented Mar 28, 2017

This helped loads. Exactly what I was looking for.

@ngriffiths

This comment has been minimized.

Show comment Hide comment
@ngriffiths

ngriffiths Apr 7, 2017

Useful and succinct, thank you.

Useful and succinct, thank you.

@zsperske

This comment has been minimized.

Show comment Hide comment
@zsperske

zsperske Apr 25, 2017

I have not for the life of me been able to get this to work...

I have not for the life of me been able to get this to work...

@zsperske

This comment has been minimized.

Show comment Hide comment
@zsperske

zsperske May 11, 2017

Hey Brandon have you tried this on 7.0? After my previous comment I got it to work, but now when running this code on a 7.0 device, the Notification is missing from the intent delivered to the broadcast receiver.

Hey Brandon have you tried this on 7.0? After my previous comment I got it to work, but now when running this code on a 7.0 device, the Notification is missing from the intent delivered to the broadcast receiver.

@RomarioTeles

This comment has been minimized.

Show comment Hide comment
@RomarioTeles

RomarioTeles Jun 3, 2017

Thanks. Notifications not working after close app. How can I fix it?

Thanks. Notifications not working after close app. How can I fix it?

@MiguelAngelHdz

This comment has been minimized.

Show comment Hide comment
@MiguelAngelHdz

MiguelAngelHdz Jun 22, 2017

good bro

good bro

@DeathTaxer

This comment has been minimized.

Show comment Hide comment
@DeathTaxer

DeathTaxer Dec 26, 2017

Easy to understand...Thanks

Easy to understand...Thanks

@amirdora

This comment has been minimized.

Show comment Hide comment
@amirdora

amirdora Jan 5, 2018

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

amirdora commented Jan 5, 2018

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

@GeneDalton

This comment has been minimized.

Show comment Hide comment
@GeneDalton

GeneDalton Mar 21, 2018

Thanks. Very easy to read and still relevent today.

Thanks. Very easy to read and still relevent today.

@meshileya

This comment has been minimized.

Show comment Hide comment
@meshileya

meshileya Apr 11, 2018

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

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

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