Как установить несколько напоминаний в Android на указанное пользователем время - PullRequest
0 голосов
/ 03 июня 2018

Я использую приведенный ниже учебник для установки напоминаний.Мне удалось установить одно напоминание, но для кратных оно все еще требует некоторых настроек.

http://blog.blundellapps.co.uk/notification-for-a-user-chosen-time/

Я передал notification_id и notificationText функции setAlarmForNotification вместе с каждым новым запросом на напоминание (чтобы однозначно идентифицировать их), но кажется, что все они заменяются последним напоминанием.И что интересно, напечатанные в logcat notification_id и notificationText являются первым напоминанием.

NotifyService.java

public class NotifyService extends Service {

//Text string of the notification
private String notificationText;

/**
 * Class for clients to access
 */
public class ServiceBinder extends Binder {
    NotifyService getService() {
        return NotifyService.this;
    }
}

// Unique id to identify the notification.
//private static final int NOTIFICATION = 123;
// Name of an intent extra we can use to identify if this service was started to create a notification
public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
// The system notification manager
private NotificationManager mNM;

@Override
public void onCreate() {
    Log.i("NotifyService", "onCreate()");
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i("LocalService", "Received start id " + startId + ": " + intent);

    notificationText = intent.getStringExtra("notification_text");
    int notiId = Integer.parseInt(intent.getStringExtra("notification_id"));

    // If this service was started by out AlarmTask intent then we want to show our notification
    if(intent.getBooleanExtra(INTENT_NOTIFY, false))
        showNotification(notiId);


    // We don't care if this service is stopped as we have already delivered our notification
    return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

// This is the object that receives interactions from clients
private final IBinder mBinder = new ServiceBinder();

/**
 * Creates a notification and shows it in the OS drag-down status bar
 */
private void showNotification(int notiId) {
    // This is the 'title' of the notification
    CharSequence title = "Alarm!!";
    // This is the icon to use on the notification
    int icon = R.drawable.ic_card_giftcard_white_24dp;
    // This is the scrolling text of the notification
    CharSequence text = "Your notification time is upon us.";
    // What time to show on the notification
    long time = System.currentTimeMillis();

    Notification notification = new Notification(icon, text, time);


    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0);

    // Set the info for the views that show in the notification panel.
    //notification.setLatestEventInfo(this, title, text, contentIntent);

    Notification.Builder builder = new Notification.Builder(this)
            .setContentIntent(contentIntent)
            .setSmallIcon(R.drawable.ic_shopping_cart_white_24dp)
            .setContentTitle(title)
            .setContentText(notificationText);

    notification = builder.build();

    // Clear the notification when it is pressed
    notification.flags |= Notification.FLAG_AUTO_CANCEL;



    // Send the notification to the system.
    mNM.notify(notiId, notification);

    // Stop the service when we are finished
    stopSelf();

}

}

Что необходимо изменить, чтобы оно работало корректно?

1 Ответ

0 голосов
/ 03 июня 2018

Я полагаю, что все ваши аварийные сигналы работают, но если вы установите NotifyService,java, у него есть поле

 private static final int NOTIFICATION = 123;

Это означает, что когда каждый из ваших отдельных аварийных сигналов срабатывает, они запускают службу, но уведомление ониУ продукта всегда будет одинаковый идентификатор.

Ссылка: https://developer.android.com/reference/android/app/NotificationManager.html#notify(int,%20android.app.Notification)

Разместите уведомление, которое будет отображаться в строке состояния. Если ваше приложение уже опубликовало уведомление с таким же идентификатором и еще не было отменено, оно будет заменено обновленной информацией.


Исправитьэто, вы хотели бы сделать этот идентификатор не константой.Возможно, передайте идентификатор в дополнительном намерении, вы можете получить подсказку о том, как сделать это таким же образом, как intent.putExtra(NotifyService.INTENT_NOTIFY, true); выполняется внутри AlarmTask.

...