Android Wear: Timer like notification card on wear

2019-07-23 18:56发布

问题:

I'm working on implementation of Pomodoro app for Android Wear.

I want to make similar to standard timer UI/UX, I guess it's implemented using displaying/updating notification with timer as title, so I'm showing notification and updating it periodically from Service:

private void updateNotification() {
    Intent stopActionIntent = new Intent(this, PomodoroActivity.class);
    stopActionIntent.setAction(PomodoroActivity.ACTION_STOP);
    PendingIntent stopActionPendingIntent = PendingIntent.getActivity(this, 0, stopActionIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Action stopAction = new NotificationCompat.Action.Builder(
            R.drawable.ic_stop,
            getString(R.string.stop_pomodoro),
            stopActionPendingIntent)
            .build();

    Notification notification = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.bg_pomodoro_timer))
            .setContentTitle(convertDiffToTimer(System.currentTimeMillis(), timerDeadlineMs))
            .setPriority(Notification.PRIORITY_MAX)
            .setOngoing(true)
            .extend(new NotificationCompat.WearableExtender().addAction(stopAction))
            .build();

    NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
    notificationManager.notify(1, notification);
}

Unpleasure problem with such solution is blinking of notificaiton.

Any ideas how escape blinking? Or maybe other way to achieve target behaviour?

回答1:

To update ongoing/existing notification -

  1. Use Same Id of Notification in Builder
  2. Use .setOnlyAlertOnce(true)

NotificationCompat.Builder notificationBuilder; public void generateNotificationForTimer(String timeInString, boolean isFirstTime) { if (isFirstTime) { notificationBuilder = new NotificationCompat.Builder(this) .setStyle(new NotificationCompat.BigPictureStyle()) .setOnlyAlertOnce(true) .setContentTitle("Timer Notification Demo") .setContentText("Time - " + timeInString) .setSmallIcon(R.drawable.common_signin_btn_icon_dark); NotificationManagerCompat.from(this).notify(110, notificationBuilder.build()); } else { notificationBuilder.setContentText(timeInString); NotificationManagerCompat.from(this).notify(110, notificationBuilder.build()); } }