1

I write code in my MainActivity for repeating alarm and whenever i start my app alarm repeated everytime.But I want it to repeat after every 24 hours

MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);
    sessionManager = new SessionManager(this);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    toolbar.setBackgroundColor(getResources().getColor(R.color.black));
    setSupportActionBar(toolbar);
    repeatAlarm();
    }


    private void repeatAlarm() {
    Date when = new Date(System.currentTimeMillis());
    try {
        Intent someIntent = new Intent(getApplicationContext(), MyReciever.class); // intent to be launched
        // note this could be getActivity if you want to launch an activity
        PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, // id, optional
                someIntent, // intent to launch
                PendingIntent.FLAG_CANCEL_CURRENT); // PendintIntent flag
        AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        alarms.setRepeating(AlarmManager.RTC_WAKEUP, when.getTime(), AlarmManager.INTERVAL_DAY, pendingIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Manish
  • 55
  • 1
  • 7
  • That is working as you wrote your code. You should check if you set alarm then do not set alarm again. And I can see that interval time given into Hour, not into DAY. – Pankaj Kumar Dec 23 '16 at 08:39
  • Besides you also need to consider setting alarm after re-booting. ALso doze restrictions https://developer.android.com/training/monitoring-device-state/doze-standby.html – Raghunandan Dec 23 '16 at 08:40

1 Answers1

1

Use PendingIntent.getService

PendingIntent pendingIntent = PendingIntent.getService(getApplicationContext(), 0, // id, optional
            someIntent, // intent to launch
            PendingIntent.FLAG_CANCEL_CURRENT);

instead of PendingIntent.getBroadcast

PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, // id, optional
            someIntent, // intent to launch
            PendingIntent.FLAG_CANCEL_CURRENT);

more details refer Here

Community
  • 1
  • 1
sasikumar
  • 12,540
  • 3
  • 28
  • 48