Task: to start a service that collects statistics and writes it to the database every day at the end of the day. Implement using AlarmManager. Activation code:

public class MainActivity extends AppCompatActivity { public DBHelper dbHelper; private Context context; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); Intent alarm = new Intent(getApplicationContext(), AlarmBroadcastReceiver.class); boolean alarmRunning = (PendingIntent.getBroadcast(getApplicationContext(), 0, alarm, PendingIntent.FLAG_NO_CREATE) != null); Calendar calendar = new GregorianCalendar(); Calendar cal = Calendar.getInstance(); calendar.set(Calendar.YEAR, cal.get(Calendar.YEAR)); calendar.set(Calendar.MONTH, cal.get(Calendar.MONTH)); calendar.set(Calendar.DAY_OF_MONTH, cal.get(Calendar.DAY_OF_MONTH)); calendar.set(Calendar.HOUR_OF_DAY, 23); calendar.set(Calendar.MINUTE, 59); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); if(!alarmRunning) { PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, alarm, 0); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); alarmManager.setRepeating(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY, pendingIntent); } } 

Receiver code:

 public class AlarmBroadcastReceiver extends BroadcastReceiver { final String LOG_TAG = "myLogs"; @Override public void onReceive(Context context, Intent intent) { Log.d(LOG_TAG, "TIME!"); context.startService(new Intent(context, MyService.class)); } 

Service Code:

 public class MyService extends Service { @Override public int onStartCommand(Intent intent, int flags, int startId) { DBHelper dbHelper = new DBHelper(getApplicationContext()); DBHelper.update_db(getApplicationContext(),dbHelper); return super.onStartCommand(intent, flags, startId); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } 

The problem in general is that the service does not start. Logs in AlarmBroadcastReceiver also do not work.

update: the receiver registered in the manifest

    1 answer 1

    Understood. Need to use the RTC flag.

    UPDATE: Flags whose names begin with RTC are oriented on system time. And the start time of such alarms should be specified relative to System.currentTimeMillis. Those. This is RTC and RTC_WAKEUP.

    Flags that begin with ELAPSED_REALTIME are based on the time from the start of the device being turned on. The start time of such alarms should be specified relative to SystemClock.elapsedRealtime (). Those. these are ELAPSED_REALTIME and ELAPSED_REALTIME_WAKEUP.

    The indication of the relative flag ELAPSED_REALTIME was erroneous, since the time I specified was absolute.

    • Please try to leave a little more detailed answers. - aleksandr barakin