-2

Don't downvote it.. If you think question needs clarification then comment the issue.

I want to update my sqlite table at midnight so calling broadcast receiver to hit at midnight automatically i.e. without launching the app. But it is updating every time when I launch the app.

Code:-

calling the function in the mainActivity.java in onCreate()

private void setTheTimeToUpdateTables(Context context) {

        Log.i("Update table function","Yes");

        AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);

        Intent alarmIntent=new Intent(context,UpdateTables.class);

        PendingIntent pendingIntent=PendingIntent.getBroadcast(context,0,alarmIntent,PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.cancel(pendingIntent);

        Calendar alarmStartTime = Calendar.getInstance();

        alarmStartTime.setTimeInMillis(System.currentTimeMillis());

        alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
        alarmStartTime.set(Calendar.MINUTE, 1);
        alarmStartTime.set(Calendar.SECOND, 0);


        System.out.println("Updating table time "+alarmStartTime);
        System.out.println("Time in millseconds "+alarmStartTime.getTimeInMillis());


        alarmManager.setInexactRepeating(AlarmManager.RTC,alarmStartTime.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent);

        Log.d("Alarm","Set for midnight");

    }

public class UpdateTables extends BroadcastReceiver {

DbHelper dbHelper;
ArrayList<ListMedicine> reminderInfo;

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

    dbHelper=new DbHelper(context);
    Log.i("Service Start", CalculateDaysService.TAG);

    context.startService(new Intent(context,CalculateDaysService.class));



    Log.i("Done","Yes");
}
}

Issue:- 1. This broadcast receiver is called everytime whenever I am launching the app. 2. It is not called at the midnight.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Ankur Khandelwal
  • 107
  • 1
  • 10

1 Answers1

1

First, you are making a Calendar whose time is in the past. This causes the alarm to trigger immediately. You need to add one day after setting the hour to zero.

Second, setInexactRepeating() will not make it trigger at midnight. I suggest you read the documentation for that method as well as the other methods of AlarmManager, because it sounds like you should be using one of the setExact() methods.

Karakuri
  • 38,365
  • 12
  • 84
  • 104