I created a service that will check some online data in specific time of the day and everyday (for example at 6 AM), and rather than using a background running service and broadcast receiver I decided to use AlarmMananger and the code below:
Intent myIntent = new Intent(MainActivity.this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
My questions are:
1- How to unregister from the AlarmManager when user decided to de-activate my service?
2- What is the use of this line
calendar.setTimeInMillis(System.currentTimeMillis());
3- What could happen if I called the same function above with the same params and data, will AlarmMananger overwrite my request or it will register a new one, and when the time comes (6 AM) it will call my service twice?
4- Is it possible to check AlarmMananger if it has successfully registered my Intent?
Edit 1:
The code below is not triggering my broadcast receiver, why?
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 6); // For 6 AM
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MILLISECOND, 0);
PendingIntent pi = PendingIntent.getService(this, 0, new Intent(this, mybroadcastreceiver.class), PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
am.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), AlarmManager.INTERVAL_DAY, pi);
AndroidManifest.xml
<receiver
android:name=".mybroadcastreceiver"
android:enabled="true"
android:exported="true"></receiver>