用户 24 小时不使用应用时的通知

notification when user don't use app 24 hours

你好。 我开发的应用程序需要在用户 24 小时不使用应用程序时显示本地通知。

我的代码:

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;
}

提醒接收器

 public class ReminderReceiver extends BroadcastReceiver {

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

提醒服务

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());
}
}

但它没有正常工作,当我关闭应用程序时,通知会立即显示。我知道这是因为我给了初始时间calendar.getTimeInMillis(),但我不知道怎么回事。

怎么做才对?

谢谢。

它帮助了我

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