Search code examples
androidandroid-studionotificationsandroid-pendingintent

Notifications not showing on specific time and date


I am working on an app that will remind the user of a particular event at a specific time and date. I have set the notifications correctly but they sometimes work and sometimes not.

I am using put extra and get extra to send clicked position to my receiver class(sending position from BuddhaEvent class to Myreceiver class). So if user clicks on position 1 then notification 1 should be triggered from the message class. I am put log statements in each position call please check it.

The output of the log statement is like this:

POSITION0 : 0 POSITION0 : 0 POSITION1: 1 POSITION0 : 0 POSITION2 : 2

And this is the log statement when 4 notifications are shown

POSITION0 : 0

POSITION0 : 0 POSITION1: 1 POSITION0 : 0 POSITION2 : 2 POSITION0 : 0 POSITION3 : 3

There is a pattern here, 0 is always being called before a notification!!!

I don’t know what’s going on. The first notification works fine but after that the notifications are just random. Most of the times notifications 2 and 3 come at the same time and sometimes 2 waits for the 3 to come. Another problem I noticed is that when I slide down for notifications, all of the notifications have the same time of delivery. I have set different id for each notification.

What I am thinking is that, the put extra and get extra are done incorrectly. I would really appreciate if someone can help me figure out the problem.

UPDATE: SO WHEN I CLICK FIRST ITEM IN THE LIST, NOTIFICATION 1 SHOWS UP. IF I CLICK ON ITEM 2, THEN NOTIFICATION 1 AND 2 SHOW UP AT THE SAME TIME. WHEN I CLICK ON ITEM 3 NOTIFICATION 3 AND 1 SHOW UP. Thanks in advance

UPDATE2: THE PROGRAM WAS CALLING 0 EVERY TIME, I DECIDED TO CHANGE THE PUT POSITION0 TO SOMETHING DIFFERENT AND NOW ONLY ONE NOTIFICATION SHOWS AT TIME(THIS ONLY WORKS WHEN TIME HAS PASSED) BUT WHEN I TRY TO SCHEDULE NOTIFICATIONS EVENTS SAME PROBLEM EXITS(LIKE SHOWING TWO NOTIFICATIONS AT THE SAME TIME).

This is my Main class `public class BuddhaEvent extends AppCompatActivity implements View.OnClickListener { public List myList = new ArrayList(); android.support.v4.app.NotificationCompat.Builder notification;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_buddhism_event);


    fill_eventsList();
    fill_ListView();
    clickResponse();

    Button buddah_button_event = (Button) findViewById(R.id.button_event_back_buddhism);
    buddah_button_event.setOnClickListener(this);


}

private void fill_eventsList() {
    myList.add(new list("Jan-24", R.drawable.chris, "Mahayana countries the new year starts on the first full moon day in January.", "Mahayana New Year"));
    myList.add(new list("Feb-2", R.drawable.chris, "Chinese festival celebrated at the turn of the traditional lunisolar Chinese calendar.", "Chinese New Year"));
    myList.add(new list("Feb-15", R.drawable.chris, "Celebrates the day when the Buddha is said to have achieved Parinirvana, or complete Nirvana", "Nirvana Day"));
    myList.add(new list("Mar-23", R.drawable.chris, "Celebration in honour of the Sangha, or the Buddhist community", "Magha Puja Day"));
    myList.add(new list("Apr-22", R.drawable.chris, "Buddhist New Year", "Theravada New Year"));
    myList.add(new list("May-15", R.drawable.chris, "Celebrates the Buddha's birthday", "Wesak - Buddha Day"));
    myList.add(new list("Jul-11", R.drawable.chris, "Honor the spirits of one's ancestors.", "Obon"));
    myList.add(new list("Jul-19", R.drawable.chris, "Celebrates Buddha's teachings of peace and enlightenment", "Asala - Dharma Day"));
    myList.add(new list("Dec-8", R.drawable.chris, "The day that the historical Buddha, Siddhartha Gautama (Shakyamuni), experienced enlightenment", "Bodhi Day"));

}

private void fill_ListView() {
    ArrayAdapter<list> listArrayAdapter = new myListAdapter();
    ListView list = (ListView) findViewById(R.id.list_eventsView);
    list.setAdapter(listArrayAdapter);

}

public void clickResponse() {
    ListView l = (ListView) findViewById(R.id.list_eventsView);
    if (l != null) {
        l.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, final View viewClicked,
                                    final int position, long id) {


                AlertDialog.Builder alert = new AlertDialog.Builder(
                        BuddhaEvent.this);
                alert.setTitle("Reminder!!");
                alert.setMessage("Do you want to be reminded of this event in future?");
                alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Log.d("OUTSIDE", "CHECKING WHICH IS CLICKED    : " + which);

                        if (position == 0) {
                            Calendar calendar = Calendar.getInstance();
                            calendar.set(Calendar.MONTH, 6);
                            calendar.set(Calendar.DAY_OF_MONTH, 20);
                            calendar.set(Calendar.HOUR_OF_DAY, 21);
                            calendar.set(Calendar.MINUTE, 2);
                            calendar.set(Calendar.SECOND, 0);

                            Intent intent = new Intent(getApplicationContext(), MyReceiver.class);
                            intent.putExtra("position0", position);


                            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 100, intent, PendingIntent.FLAG_UPDATE_CURRENT);

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

                        }

                        if (position == 1) {
                            Calendar calendar2 = Calendar.getInstance();

                            calendar2.set(Calendar.MONTH, 6);
                            calendar2.set(Calendar.DAY_OF_MONTH, 20);

                            calendar2.set(Calendar.HOUR_OF_DAY, 21);
                            calendar2.set(Calendar.MINUTE, 3);
                            calendar2.set(Calendar.SECOND, 0);


                            Intent intent2 = new Intent(getApplicationContext(), MyReceiver.class);
                            intent2.putExtra("position1",position );



                            PendingIntent pendingIntent2 = PendingIntent.getBroadcast(getApplicationContext(), 101, intent2, PendingIntent.FLAG_UPDATE_CURRENT);

                            AlarmManager alarmManager2 = (AlarmManager) getSystemService(ALARM_SERVICE);
                            alarmManager2.set(AlarmManager.RTC_WAKEUP, calendar2.getTimeInMillis(), pendingIntent2);
                        }

                        if (position == 2) {

                            Calendar calendar3 = Calendar.getInstance();

                            calendar3.set(Calendar.MONTH, 6);
                            calendar3.set(Calendar.DAY_OF_MONTH, 20);

                            calendar3.set(Calendar.HOUR_OF_DAY, 21);
                            calendar3.set(Calendar.MINUTE, 4);
                            calendar3.set(Calendar.SECOND, 0);


                            Intent intent3 = new Intent(getApplicationContext(), MyReceiver.class);
                            intent3.putExtra("position2", position);


                            PendingIntent  pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(), 105, intent3, PendingIntent.FLAG_UPDATE_CURRENT);

                            AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                            alarmManager.set(AlarmManager.RTC, calendar3.getTimeInMillis(), pendingIntent3);
                        }


                        if (position == 3) {

                            Calendar calendar4 = Calendar.getInstance();

                            calendar4.set(Calendar.MONTH, 6);
                            calendar4.set(Calendar.DAY_OF_MONTH, 20);

                            calendar4.set(Calendar.HOUR_OF_DAY, 21);
                            calendar4.set(Calendar.MINUTE, 5);
                            calendar4.set(Calendar.SECOND, 0);


                            Intent intent4 = new Intent(getApplicationContext(), MyReceiver.class);
                            intent4.putExtra("position3", position);


                            PendingIntent  pendingIntent4 = PendingIntent.getBroadcast(getApplicationContext(), 102, intent4, PendingIntent.FLAG_UPDATE_CURRENT);

                            AlarmManager alarmManager4 = (AlarmManager) getSystemService(ALARM_SERVICE);
                            alarmManager4.set(AlarmManager.RTC, calendar4.getTimeInMillis(), pendingIntent4);
                        }
                        dialog.dismiss();
                    }
                });

                alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        dialog.dismiss();
                    }
                });
                alert.show();
            }
        });
    }
}


private class myListAdapter extends ArrayAdapter<list> {
    public myListAdapter() {
        super(BuddhaEvent.this, R.layout.custom_events_layout, myList);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View itemView = convertView;
        if (itemView == null) {
            itemView = getLayoutInflater().inflate(R.layout.custom_events_layout, parent, false);
        }
        list current_list = myList.get(position);


        ImageView imageView = (ImageView) itemView.findViewById(R.id.id_image);
        imageView.setImageResource(current_list.getIconId());


        TextView titleTxt = (TextView) itemView.findViewById(R.id.id_event);
        titleTxt.setText(current_list.getName());

        EditText text = (EditText) itemView.findViewById(R.id.id_desp);
        text.setText(current_list.getDetails());


        TextView date = (TextView) itemView.findViewById(R.id.id_date);
        date.setText(current_list.getDate());

        return itemView;
    }


}


public void onClick(View v) {
    startActivity(new Intent(BuddhaEvent.this, BuddhaScreen.class));
}

} ` This is MyReceiver class that extends Broadcast receiver

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
    Bundle bundle = intent.getExtras();


    if(bundle==null){
        return;
    }else{
        if(bundle.getInt("position0")==0){
            Log.d("INSIDE", "POSITION0 : " + bundle.getInt("position0"));

            Utils utils = new Utils();
            utils.generateNotification(context);
        }

        if(bundle.getInt("position1")==1){
            Log.d("INSIDE", "POSITION1: " + bundle.getInt("position1"));

            Utils utils = new Utils();
            utils.generateNotification2(context);
        }

        if(bundle.getInt("position2")==2){
            Log.d("INSIDE", "POSITION2 : " + bundle.getInt("position2"));

            Utils utils = new Utils();
            utils.generateNotification3(context);
        }

        if(bundle.getInt("position3")==3){
            Log.d("INSIDE", "POSITION3 : " + bundle.getInt("position3"));

            Utils utils = new Utils();
            utils.generateNotification4(context);
        }
    }


}

}

This is my utils class that keeps track of the notifications

public class Utils {


public void generateNotification(Context context) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent repeating_intent = new Intent(context, BuddhaNow.class);
    // replace the old activity if there is a case that it is already opened
    repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 100, repeating_intent, PendingIntent.FLAG_UPDATE_CURRENT);


    NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.drawable.ic_launcher)
            .setWhen(System.currentTimeMillis())
            .setContentTitle("Notification Title1")
            .setContentText("Notification Text1")
            .setAutoCancel(true);

    notificationManager.notify(100, builder.build());


}


public void generateNotification2(Context context) {

    NotificationManager notificationManager2 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent repeating_intent2 = new Intent(context, BuddhaNow.class);
    // replace the old activity if there is a case that it is already opened
    repeating_intent2.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent2 = PendingIntent.getActivity(context, 101, repeating_intent2, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder2 = new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent2)
            .setSmallIcon(R.drawable.ic_launcher)
            .setWhen(System.currentTimeMillis())

            .setContentTitle("Notification Title2")
            .setContentText("Notification Text2")
            .setAutoCancel(true);

    notificationManager2.notify(101, builder2.build());


}

public void generateNotification3(Context context) {

    NotificationManager notificationManager3 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent repeating_intent3 = new Intent(context, BuddhaNow.class);
    // replace the old activity if there is a case that it is already opened
    repeating_intent3.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent3 = PendingIntent.getActivity(context, 102, repeating_intent3, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder3 = new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent3)
            .setSmallIcon(R.drawable.ic_launcher)
            .setWhen(System.currentTimeMillis())

            .setContentTitle("Notification Title3")
            .setContentText("Notification Text3")
            .setAutoCancel(true);

    notificationManager3.notify(102, builder3.build());


}

public void generateNotification4(Context context) {

    NotificationManager notificationManager4 = (NotificationManager) context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent repeating_intent4 = new Intent(context, BuddhaNow.class);
    // replace the old activity if there is a case that it is already opened
    repeating_intent4.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent4 = PendingIntent.getActivity(context, 105, repeating_intent4, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder4 = new NotificationCompat.Builder(context)
            .setContentIntent(pendingIntent4)
            .setSmallIcon(R.drawable.ic_launcher)
            .setWhen(System.currentTimeMillis())

            .setContentTitle("Notification Title4")
            .setContentText("Notification Text4")
            .setAutoCancel(true);

    notificationManager4.notify(105, builder4.build());


}

}

Solution

  • You should use setExact method in order to archive exact time of alarm firing.

    But main your problem is that bundle.getInt("position0")==0 will be always true when there is no position0 in bundle, because of:

    Returns the value associated with the given key, or 0 if no mapping of the desired type exists for the given key.

    So, in order to fix that, pass position:

    intent.putExtra("position", position);
    

    and then check it like that inside broadcast receiver:

    int position = bundle.getInt("position");
    
    switch (position):
        case 0: 
            utils.generateNotification(context);
            break;
        case 1:
            utils.generateNotification1(context);
            break;
        ...