I would like to notify the user that he has an expense that expires the next day, but without the need for the application to be running, I currently have a code that notifies me from the moment I enter the application, I would like to do so (without user interaction) notify 0h00 every day in case you have any expenses expiring the next day.
Code I already have
LoginActivity - onCreate method
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 1);
calendar.set(Calendar.AM_PM, Calendar.AM);
Intent myIntent = new Intent(this, MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
Receiver
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, MyService.class);
context.startService(service1);
}
}
Service
public class MyService extends Service {
private NotificationManager mManager;
public MyService() {
}
@Override
public void onCreate() {
super.onCreate();
}
@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Calendar calendar = Calendar.getInstance();
DespesaDAO DAO = new DespesaDAO(getApplicationContext());
List<Despesa> list = DAO.getAllVencidasAmanha(calendar);
if (list.size() > 0) {
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), LoginActivity.class);
Notification notification = new Notification(R.drawable.ic_launcher, "Existem "+list.size()+" despesas que vencerão amanhã!", System.currentTimeMillis());
intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
notification.setLatestEventInfo(this.getApplicationContext(), String.valueOf(list.size()) + " despesas vencem amanhã", "Fique alerta para não se endividar!", pendingNotificationIntent);
mManager.notify(0, notification);
}
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}