Question

I have one app which over some time get notification on status bar like alarm. The problem is when the time is met he run perfect, but after this time the alert is launch on some periods, like 5 minutes, 1 hour.

Then I put one (if) to solve the problem, but they never met.

   long current_time = System.currentTimeMillis();

  if (current_time == limit_time)

This is the full code.

Calendar calendar = Calendar.getInstance();


        calendar.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);

        calendar.set(Calendar.HOUR_OF_DAY,11);
        calendar.set(Calendar.MINUTE,27);
        calendar.set(Calendar.SECOND,0);


        long current_time = System.currentTimeMillis();


        long limit_time = calendar.getTimeInMillis();



       if (current_time == limit_time){
            Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);


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

enter image description here

Was it helpful?

Solution 2

Of course it's different every time, that's the point, when you count in milliseconds its not the same time now and now

Change your code and use < or > depending on your need instead of == as the computer might skip to check the value you're looking for because it's going to fast so it might go from 1388395620883 to 1388395620892 , it's actually not skipping but it doesn't have time to print or check (or whatever) them all. try to print this System.currentTimeMillis() in an infinite loop to see how it goes, you'll see it cannot "print that fast"

OTHER TIPS

I'm not sure I understood what you are asking, but

Calendar calendar = Calendar.getInstance();

will get a Calendar instance initialized to current date and time, with millisecond precision.

When you set some fields on the calendar, the others are left intact. So, if the last 3 digits in a millisecond stamp are problematic, set them to zero as well:

calendar.set(Calendar.MILLISECOND, 0);

And for comparisons of millisecond timestamps it often more useful to use >= or <= rather than ==.

It is better to use compare

if (time == limit_time) is causing the issue

set both values to calendar and compare them .check this for more details

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top