我正在开发一个应用程序,其中通知必须在一段时间后触发。触发通知的代码在方法中。我想在退出应用程序一段时间后执行此方法。我试过Alarm Manager,它运行正常,但它需要一个意图。我不想展示活动,我只想在状态栏中显示通知。有没有其他方法可以做到这一点?我想要运行的方法是 fireNotification 。使用Alarm Manager似乎是合乎逻辑的,但它可以触发Intent而不是方法。当应用程序未运行时,我需要一些方法来运行此方法。
private void fireNotification(long Id, String Title)
{
//Define sound URI
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle(Title)
.setContentText("Tap here to view")
.setSound(soundUri)
.setAutoCancel(true);
Intent resultIntent = new Intent(this, ViewActivity.class);
resultIntent.putExtra("noteId", noteId);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack
stackBuilder.addParentStack(ViewNoteActivity.class);
// Adds the Intent to the top of the stack
stackBuilder.addNextIntent(resultIntent);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
// Sets an ID for the notification
int mNotificationId = safeLongToInt(safeLongToInt(Id));
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
}
public static int safeLongToInt(long l) {
if (l < Integer.MIN_VALUE || l > Integer.MAX_VALUE) {
throw new IllegalArgumentException
(l + " cannot be cast to int without changing its value : Notification ID.");
}
return (int) l;
}