如何设置用户选择的日期和时间的通知?

时间:2015-03-17 13:55:53

标签: android notifications android-notifications

下面是“iamverysmart”建议的代码,它的工作就像一个魅力。

但是现在,如何在用户选择的日期和时间设置通知?

如果设置了特定通知,我想如何取消通知?

提前致谢

private void addNotification() {

NotificationCompat.Builder builder =
        new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.icon1)
                .setContentTitle("Notifications Example")
                .setContentText("This is a test notification");

Intent notificationIntent = new Intent(this, MyActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
        PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);

// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(FM_NOTIFICATION_ID, builder.build());
}

1 个答案:

答案 0 :(得分:0)

此代码的大部分内容都来自How exactly to use Notification.Builder,所以在您提出

之前应该做更多的研究

在xml中添加切换按钮

<ToggleButton
    android:id="@+id/myButton"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textOn="on"
    android:textOff="off"
    android:onClick="myButtonClicked"/>

然后在onclick方法中我们调用我们的通知方法

public void myButtonClicked(View view) {

    boolean isOn = ((ToggleButton)view.findViewById(R.id.myButton)).isChecked();

    if (isOn) {
        // do stuff
    } else {
        addNotification()
    }
}

实际的通知方法。 FM_NOTIFICATION_ID是常量int

private void addNotification() {

    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.drawable.icon1)
                    .setContentTitle("Notifications Example")
                    .setContentText("This is a test notification");

    Intent notificationIntent = new Intent(this, MyActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
            PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    // Add as notification
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(FM_NOTIFICATION_ID, builder.build());
}

删除通知

private void removeNotification() {
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.cancel(FM_NOTIFICATION_ID);
}

我不确定您在用户选择的日期&#34;上的含义是什么?你的意思是当用户使用切换按钮时发送通知? myButtonClicked方法中包含的内容。更准确地说明你的意思。