0

I am trying to make an application that shows a notification on the selected time and date entered by the user from date picker and time picker, but after selecting the time and date it is not showing on that exact time. Instead it fires after a few seconds when I press ok button. Code is given below for main activity:

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

    Reminder_Title=(EditText)findViewById(R.id.Reminder_Title);

    tDate=(TextView) findViewById(R.id.Date_text);

    tTime=(TextView)findViewById(R.id.Time_text);

    tRepeat=(TextView)findViewById(R.id.Repeat_text);

    doneFab=(FloatingActionButton)findViewById(R.id.donefab);

    calendar=Calendar.getInstance();
    int Hour = calendar.get(Calendar.HOUR_OF_DAY);
    int Mint = calendar.get(Calendar.MINUTE);
    final int Year = calendar.get(Calendar.YEAR);
    final int Month = calendar.get(Calendar.MONTH) + 1;
    final int Day = calendar.get(Calendar.DAY_OF_MONTH);

    mDate = Day + "/" + Month + "/" + Year;


    tDate.setText(mDate);

    if(Mint<10) {
        mTime=Hour + ":"+0+ Mint;
    }
    else
    {
        mTime=Hour + ":" + Mint;
    }
    tTime.setText(mTime);

    doneFab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            if (Reminder_Title.getText().toString().length() != 0) {


                AlertDialog.Builder Message = new AlertDialog.Builder(Add_Reminder.this);
                Message.setTitle("Message");
                Message.setMessage("Reminder Added!!");
                Message.setNegativeButton("Ok", new DialogInterface.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.M)
                    @Override
                    public void onClick(DialogInterface dialog, int which) {



                     // Set calender for notifcation

                        calendar.set(Calendar.MONTH, --nMonth);
                        calendar.set(Calendar.YEAR, nYear);
                        calendar.set(Calendar.DAY_OF_MONTH, nDay);
                        calendar.set(Calendar.HOUR_OF_DAY, nHour);
                        calendar.set(Calendar.MINUTE, nMinute);
                        calendar.set(Calendar.SECOND, 0);
                        calendar.set(Calendar.MILLISECOND, 0);

                        long selectedTimestamp = calendar.getTimeInMillis();

                        Intent intent=new Intent(Add_Reminder.this,AlarmSetter.class);
                        PendingIntent p1=PendingIntent.getBroadcast(getApplicationContext(),0, intent,0);
                        AlarmManager a=(AlarmManager)getSystemService(ALARM_SERVICE);
                        a.setExactAndAllowWhileIdle(AlarmManager.RTC,selectedTimestamp,p1);

                    }
                });
                AlertDialog alert = Message.create();
                alert.show();

            }
        }
    });




}


public void setDate(View view) {

    Calendar c=Calendar.getInstance();
    int mYear = c.get(Calendar.YEAR);
   int mMonth = c.get(Calendar.MONTH);
    int mDay = c.get(Calendar.DAY_OF_MONTH);

    DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener()
    {
        @Override
                public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
        {
            //getting reminder set dates and day
            nYear=year;
            nMonth=monthOfYear;
            nDay=dayOfMonth;


            mDate=dayOfMonth + "-" + (monthOfYear + 1) + "-" + year;
            tDate.setText(mDate);


                }
                }, mYear, mMonth, mDay);
    datePickerDialog.show();
}

public void setTime(View view) {
     Calendar c = Calendar.getInstance();
     int mHour = c.get(Calendar.HOUR);
     int mMinute = c.get(Calendar.MINUTE);


    // Launch Time Picker Dialog
    TimePickerDialog timePickerDialog = new TimePickerDialog(this,
            new TimePickerDialog.OnTimeSetListener() {

                @Override
                public void onTimeSet(TimePicker view, int HOUR_OF_DAY,
                                      int minute) {
                    nHour=HOUR_OF_DAY;
                    nMinute=minute;

                      if(minute<10) {
                          mTime=HOUR_OF_DAY + ":"+0+ minute;
                      }
                      else
                      {
                          mTime=HOUR_OF_DAY + ":" + minute;
                      }
                      tTime.setText(mTime);
                }
            }, mHour, mMinute, false);
    timePickerDialog.show();



}

public void setRepeating(View view)
{
    final String[] items = new String[6];

    items[0] = "No Repeating";
    items[1] = "Every Hour";
    items[2] = "Every Day";
    items[3] = "Every Week";
    items[4] = "Every Month";
    items[5] = "Every Year";

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("Select Type");

    builder.setItems(items, new DialogInterface.OnClickListener() {

        public void onClick(DialogInterface dialog, int item) {

           String mRepeatType = items[item];
           tRepeat.setText(mRepeatType);

        }
    });
    AlertDialog alert = builder.create();
    alert.show();
}

Code for Alarm.java

public class AlarmSetter extends BroadcastReceiver{

    @Override public void onReceive(Context context, Intent intent) {

        String id="main_channel";
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
            Toast.makeText(context, "Wake up", Toast.LENGTH_LONG).show();

            NotificationManager notificationManager=(NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
            CharSequence name="Channel Name";
            String description="Channel Description";
            int importance=NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel=new NotificationChannel(id,name,importance);
            notificationChannel.setDescription(description);
            notificationChannel.enableLights(true);
            notificationChannel.setLightColor(Color.WHITE);
            notificationChannel.enableVibration(false);
            if(notificationManager!=null)
            {
                notificationManager.createNotificationChannel(notificationChannel);
            }
            NotificationCompat.Builder notificationBuilder =new NotificationCompat.Builder(context,id);
            notificationBuilder.setSmallIcon(R.drawable.timesmall);
            notificationBuilder.setContentTitle("Notification Title");
            notificationBuilder.setLights(Color.WHITE,500,5000);
            notificationBuilder.setColor(Color.RED);
            notificationBuilder.setDefaults(Notification.DEFAULT_SOUND);
            NotificationManagerCompat notificationManagerCompat=NotificationManagerCompat.from(context);
            notificationManagerCompat.notify(1000,notificationBuilder.build());

        }
    }
}
hatef
  • 5,491
  • 30
  • 43
  • 46

1 Answers1

0

This is a bit of a long shot, but I assume your error is calendar.set(Calendar.MONTH, --nMonth);

Remove the pre-decrement statement -- and it should work.

--nMonth means execute nMonth = nMonth - 1 and then use the new nMonth in the statement calendar.set(Calendar.MONTH, nMonth); <-- here nMonth is one less than before. This means every time you set an Alarm it will be set a month earlier.

Also please have a look at the google-java style-guide http://google.github.io/styleguide/javaguide.html#s5.2.7-local-variable-names it tells you how to write more readable code. Especially Month,Hour, Mint... should be all lowercase.

leonardkraemer
  • 6,573
  • 1
  • 31
  • 54
  • Thanks man ..its working .. now how do i set multiple alarms? – Kainth Sourav Oct 02 '18 at 10:30
  • and the other problem is its showing notification even if i set alarm for 4am it is showing on 4pm and vise versa.. – Kainth Sourav Oct 02 '18 at 10:35
  • You can find answers for both questions on SO. see https://stackoverflow.com/questions/12785702/android-set-multiple-alarms and https://stackoverflow.com/a/36639155/4265739 <- this is a bit of a read, but well written and explains how to use a better class for handling time – leonardkraemer Oct 02 '18 at 13:33