android - 在给定的时间后只调用一次通知

一箫一剑平生意,负尽狂名十五年。这篇文章主要讲述android - 在给定的时间后只调用一次通知相关的知识,希望能为你提供帮助。
我正在制作一个简单的预算应用程序,用于跟踪给定时间段内的钱,可能是一天或一周。在一天或一周过后,会弹出一条通知,提示预算时间已经结束。
我想在给定的时间后发送一个通知并且只发送一次,假设在1天之后弹出通知,并且用户可以重置预算。
【android - 在给定的时间后只调用一次通知】我尝试过使用Calendar和Timer而没有运气。有没有办法在给定的时间后只弹出一次通知?
这是我目前使用的代码。

public static final int MY_NOTIFICATION = 1; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_budget); ... // Inner codedisplayNotification(); }private void displayNotification(){ Intent intent = new Intent(getApplicationContext(), SecondActivity.class); PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); Notification notify = new Notification.Builder(this) .setWhen(System.currentTimeMillis()) .setSmallIcon(R.mipmap.ic_alarm) .setTicker("Budget has ended!") .setAutoCancel(true) .setContentIntent(pendingIntent) .setContentTitle("The Budget App") .setContentText("Your budget has expired!") .getNotification(); NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); manager.notify(MY_NOTIFICATION, notify); }

答案要在特定时间执行特定任务而不管应用程序是否打开,您需要一种警报类型的机制。根据android版本,可以在Android应用程序中使用JobScheduler,GcmNetworkManager或AlarmManager。我建议使用Evernote的图书馆来处理所有事情。
A utility library for Android to run jobs delayed in the background. Depending on the Android version either the JobScheduler, GcmNetworkManager or AlarmManager is getting used. You can find out in this blog post or in these slides why you should prefer this library than each separate API. All features from Android Oreo are backward compatible back to Ice Cream Sandwich.

    推荐阅读