Search code examples
androidandroid-serviceandroid-notificationsandroid-broadcastreceiver

notification when user don't use app 24 hours


Hellow. I develop app in which need show local notification when user don't use app 24 hours.

My code:

MainActivity

@Override
protected void onDestroy() {
    super.onDestroy();
    Calendar calendar = Calendar.getInstance();
    Intent myIntent = new Intent(MainActivity.this, ReminderReceiver.class);
    pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent, 0);
    AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), getInterval(), pendingIntent);
}

 private int getInterval() {
    int hours = 24;
    int minutes = 60;
    int seconds = 60;
    int milliseconds = 1000;
    return hours * minutes * seconds * milliseconds;
}

ReminderReceiver

 public class ReminderReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Intent service1 = new Intent(context, ReminderService.class);
    context.startService(service1);
}
}

ReminderService

public class ReminderService extends Service {
private static final int NOTIFICATION_ID = 1;
private NotificationManager notificationManager;
private PendingIntent pendingIntent;

@Override
public IBinder onBind(Intent arg0)
{
    return null;
}

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
    Context context = this.getApplicationContext();
    notificationManager = (NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
    Intent mIntent = new Intent(this, MainActivity.class);
    pendingIntent = PendingIntent.getActivity(context, 0, mIntent, PendingIntent.FLAG_CANCEL_CURRENT);
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
    builder.setContentTitle("Get Your PSN Code for FREE Now!");
    builder.setSmallIcon(R.mipmap.ic_launcher);
    builder.setContentIntent(pendingIntent);
    notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    notificationManager.notify(NOTIFICATION_ID, builder.build());
}
}

But it does not work as it should, the notification is shown right away when I close the application. I understand that this is due to the fact that I give the initial time calendar.getTimeInMillis(), but I do not know how else.

How to do it right?

Thanks.


Solution

  • It helped me

    alarmManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis() + AlarmManager.INTERVAL_DAY, AlarmManager.INTERVAL_DAY, pendingIntent);