2

在特定时间后发出通知需要帮助,在这里看到了几个例子,但它对我不起作用。

在按钮单击时,调用一个方法以在 5 秒后设置 AlarmManager,这反过来又应该调用我的方法来放置通知。下面是相同的代码。

private void startAlarm() {
        AlarmManager alarmManager = (AlarmManager) this.getSystemService(this.ALARM_SERVICE);

        Calendar rightNow = Calendar.getInstance();
         long when = rightNow.getTimeInMillis()+5000;

        Intent intent = new Intent(this, RemainderService.class);
        PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
        alarmManager.set(AlarmManager.RTC_WAKEUP,when,pendingIntent);
    }

从另一个类(文件)RemainderService.java

public class RemainderService extends IntentService {
    public RemainderService() {
        super("RemainderService");
    }

    private static final int NOTIF_ID = 1;

    @Override
      protected void onHandleIntent(Intent intent) {

        NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        long when = System.currentTimeMillis();         // notification time

        Notification notification = new Notification(R.drawable.icon, "reminder", when);
        notification.defaults |= Notification.DEFAULT_SOUND;
        notification.flags |= notification.FLAG_AUTO_CANCEL;

        Intent notificationIntent = new Intent(this, Notify.class);
        notificationIntent.putExtra("notificationID", 20);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 20, notificationIntent , 0);

        notification.setLatestEventInfo(getApplicationContext(), "It's about time", "You should open the app now", contentIntent);

        nm.notify(NOTIF_ID, notification);
    }
}

基本人为错误,忘记在清单文件中添加详细信息。

4

0 回答 0