2

I am newbie in android. I want to do some work everyday at a specific time. My work is to fetch one data from database and to show to the user. I used onReceive method to do that work.

I put below code to the OnCreate method

SharedPreferences prefs = getSharedPreferences("FIRST_TIME_LOGIN", MODE_PRIVATE);
    String restoredText = prefs.getString("isFirstTime", null);
    if (restoredText == null) {
        SharedPreferences.Editor editor = getSharedPreferences("FIRST_TIME_LOGIN", MODE_PRIVATE).edit();
        editor.putString("isFirstTime", "yes");
        editor.commit();

        Calendar calendar = Calendar.getInstance();
        //calendar.setTimeInMillis(System.currentTimeMillis());
        calendar.set(Calendar.HOUR_OF_DAY, 9);
        calendar.set(Calendar.MINUTE, 35);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.AM_PM,Calendar.AM);

        Intent alarmIntent = new Intent(MainActivity.this, AlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, alarmIntent, 0);
        manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        int interval = 1000*60*5;//calendar.getTimeInMillis()//AlarmManager.INTERVAL_DAY
        manager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis() ,AlarmManager.INTERVAL_HOUR , pendingIntent);
        Toast.makeText(getApplicationContext(), "Alarm Set MainActivity", Toast.LENGTH_SHORT).show();
    }

To check i used one hour interval. Problem is whenever i install my app ,instantly it fires the alarm where it should fire the alarm at 9.30AM.

What is the wrong in my code??

  • I think the Calander is getting its time from calendar.setTimeInMillis(System.currentTimeMillis()); have you tried commenting that out? Also you can try running setTime on a custom DateObject https://developer.android.com/reference/java/util/Date.html#Date(int, int, int, int, int) – Menachem Hornbacher Feb 10 '17 at 03:57
  • Check the time of alarm, Log the time from Calander it may be before current time so alarm will fire instantly.Check if alarmTime is before now add 1 hour in alarm time and set alarm – d1vivek681065 Feb 10 '17 at 04:02
  • 1
    I am guessing your time now is later than 9.30am. If so your alarm will be set to an earlier time and the alarm will trigger. Try changing the date field as well. – Naveen Dissanayake Feb 10 '17 at 04:32

0 Answers0