I have an alarm manager, that should run in the end of every year. It's work fine, but when I rebooted my device, this event start after my device robot, which, in my case, clearing my database. But I want my alarmmanager to go into the background after rebooting the device and worked at the end of the year, and not immediately:
device reboot -> alarm manager starting -> not do everything till the end of the year -> end of the year-> trigger
MainActivity.class
public class MainActivity extends AppCompatActivity implements MainView {
@Override
protected void onCreate(Bundle savedInstanceState) {
AndroidInjection.inject(this);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
runFullYearTimer();
}
private void runFullYearTimer() {
AlarmManager manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(this, FullYearCleaning.class);
PendingIntent pi = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, 23);
calendar.set(Calendar.MINUTE, 59);
calendar.set(Calendar.SECOND, 59);
calendar.set(Calendar.DATE, 31);
calendar.set(Calendar.MONTH, 11);
presenter.putIntInStorage(YEAR, calendar.get(Calendar.YEAR));
manager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pi);
}
}
FullYearCleaning.class
public class FullYearCleaning extends BroadcastReceiver {
@Inject
GeneralStorageHelper generalStorageHelper;
@Inject
CountryDaoModel countryDaoModel;
@Override
public void onReceive(Context context, Intent intent) {
AndroidInjection.inject(this, context);
Log.d(TAG, "Running ending event!");
countryDaoModel.clearCountriesValues();
generalStorageHelper.putIntIntStorage(SP_HALF_YEAR, NO_HALF_YEAR_NOTIFICATION);
generalStorageHelper.putIntIntStorage(SP_COMPLETE_YEAR, NO_ALL_YEAR_NOTIFICATION);
}
}
manifest
<receiver
android:name=".model.FullYearCleaning"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<action android:name="android.intent.action.REBOOT"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</receiver>
The issue is because of using the same broadcast receiver class for boot completed and alarm triggered There are two solutions to overcome this
adding Extras to pending intent and depending on intent extras in on receive you can choose what to do.
if(intent.hasExtra("ALARM")){
//clear values
}else{
// create alarm here
}