aboutsummaryrefslogtreecommitdiff
path: root/src/com/android/tv/recommendation/NotificationService.java
blob: c00a508ee8af55dbd869b229a855686ef27eaba4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.tv.recommendation;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Rect;
import android.media.tv.TvInputInfo;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseLongArray;
import android.view.View;

import com.android.tv.R;
import com.android.tv.TvApplication;
import com.android.tv.common.WeakHandler;
import com.android.tv.data.Channel;
import com.android.tv.data.Program;
import com.android.tv.util.BitmapUtils;
import com.android.tv.util.BitmapUtils.ScaledBitmapInfo;
import com.android.tv.util.TvInputManagerHelper;
import com.android.tv.util.Utils;

import java.util.List;

/**
 * A local service for notify recommendation at home launcher.
 */
public class NotificationService extends Service implements Recommender.Listener {
    private static final boolean DEBUG = false;
    private static final String TAG = "NotificationService";

    public static final String ACTION_SHOW_RECOMMENDATION =
            "com.android.tv.notification.ACTION_SHOW_RECOMMENDATION";
    public static final String ACTION_HIDE_RECOMMENDATION =
            "com.android.tv.notification.ACTION_HIDE_RECOMMENDATION";

    /**
     * Recommendation intent has an extra data for the recommendation type. It'll be also
     * sent to a TV input as a tune parameter.
     */
    public static final String TUNE_PARAMS_RECOMMENDATION_TYPE =
            "com.android.tv.recommendation_type";

    private static final String TYPE_RANDOM_RECOMMENDATION = "random";
    private static final String TYPE_ROUTINE_WATCH_RECOMMENDATION = "routine_watch";
    private static final String TYPE_ROUTINE_WATCH_AND_FAVORITE_CHANNEL_RECOMMENDATION =
            "routine_watch_and_favorite";

    private static final String NOTIFY_TAG = "tv_recommendation";
    // TODO: find out proper number of notifications and whether to make it dynamically
    // configurable from system property or etc.
    private static final int NOTIFICATION_COUNT = 3;

    private static final int MSG_INITIALIZE_RECOMMENDER = 1000;
    private static final int MSG_SHOW_RECOMMENDATION = 1001;
    private static final int MSG_UPDATE_RECOMMENDATION = 1002;
    private static final int MSG_HIDE_RECOMMENDATION = 1003;

    private static final long RECOMMENDATION_RETRY_TIME_MS = 5 * 60 * 1000;  // 5 min
    private static final long RECOMMENDATION_THRESHOLD_LEFT_TIME_MS = 10 * 60 * 1000;  // 10 min
    private static final int RECOMMENDATION_THRESHOLD_PROGRESS = 90;  // 90%
    private static final int MAX_PROGRAM_UPDATE_COUNT = 20;

    private TvInputManagerHelper mTvInputManagerHelper;
    private Recommender mRecommender;
    private boolean mShowRecommendationAfterRecommenderReady;
    private NotificationManager mNotificationManager;
    private HandlerThread mHandlerThread;
    private Handler mHandler;
    private final String mRecommendationType;
    private int mCurrentNotificationCount;
    private long[] mNotificationChannels;

    private float mNotificationCardMaxWidth;
    private float mNotificationCardHeight;
    private int mCardImageHeight;
    private int mCardImageMaxWidth;
    private int mCardImageMinWidth;
    private int mChannelLogoMaxWidth;
    private int mChannelLogoMaxHeight;
    private int mLogoPaddingStart;
    private int mLogoPaddingBottom;

    public NotificationService() {
        mRecommendationType = TYPE_ROUTINE_WATCH_AND_FAVORITE_CHANNEL_RECOMMENDATION;
    }

    @Override
    public void onCreate() {
        if (DEBUG) Log.d(TAG, "onCreate");
        super.onCreate();

        mCurrentNotificationCount = 0;
        mNotificationChannels = new long[NOTIFICATION_COUNT];
        for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
            mNotificationChannels[i] = Channel.INVALID_ID;
        }
        mNotificationCardMaxWidth = getResources().getDimensionPixelSize(
                R.dimen.notif_card_img_max_width);
        mNotificationCardHeight = getResources().getDimensionPixelSize(
                R.dimen.notif_card_img_height);
        mCardImageHeight = getResources().getDimensionPixelSize(R.dimen.notif_card_img_height);
        mCardImageMaxWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_max_width);
        mCardImageMinWidth = getResources().getDimensionPixelSize(R.dimen.notif_card_img_min_width);
        mChannelLogoMaxWidth =
                getResources().getDimensionPixelSize(R.dimen.notif_ch_logo_max_width);
        mChannelLogoMaxHeight =
                getResources().getDimensionPixelSize(R.dimen.notif_ch_logo_max_height);
        mLogoPaddingStart =
                getResources().getDimensionPixelOffset(R.dimen.notif_ch_logo_padding_start);
        mLogoPaddingBottom =
                getResources().getDimensionPixelOffset(R.dimen.notif_ch_logo_padding_bottom);

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        TvApplication application = ((TvApplication) getApplicationContext());
        mTvInputManagerHelper = application.getTvInputManagerHelper();
        mHandlerThread = new HandlerThread("tv notification");
        mHandlerThread.start();
        mHandler = new NotificationHandler(mHandlerThread.getLooper(), this);
        mHandler.sendEmptyMessage(MSG_INITIALIZE_RECOMMENDER);

        // Just called for early initialization.
        application.getChannelDataManager();
        application.getProgramDataManager();
    }

    private void handleInitializeRecommender() {
        mRecommender = new Recommender(NotificationService.this, NotificationService.this, true);
        if (TYPE_RANDOM_RECOMMENDATION.equals(mRecommendationType)) {
            mRecommender.registerEvaluator(new RandomEvaluator());
        } else if (TYPE_ROUTINE_WATCH_RECOMMENDATION.equals(mRecommendationType)) {
            mRecommender.registerEvaluator(new RoutineWatchEvaluator());
        } else if (TYPE_ROUTINE_WATCH_AND_FAVORITE_CHANNEL_RECOMMENDATION
                .equals(mRecommendationType)) {
            mRecommender.registerEvaluator(new FavoriteChannelEvaluator(), 0.5, 0.5);
            mRecommender.registerEvaluator(new RoutineWatchEvaluator(), 1.0, 1.0);
        } else {
            throw new IllegalStateException(
                    "Undefined recommendation type: " + mRecommendationType);
        }
    }

    private void handleShowRecommendation() {
        if (!mRecommender.isReady()) {
            mShowRecommendationAfterRecommenderReady = true;
        } else {
            showRecommendation();
        }
    }

    private void handleUpdateRecommendation(int notificationId, Channel channel) {
        if (mNotificationChannels[notificationId] == Channel.INVALID_ID || !sendNotification(
                channel.getId(), notificationId)) {
            changeRecommendation(notificationId);
        }
    }

    private void handleHideRecommendation() {
        if (!mRecommender.isReady()) {
            mShowRecommendationAfterRecommenderReady = false;
        } else {
            hideAllRecommendation();
        }
    }

    @Override
    public void onDestroy() {
        mRecommender.release();
        mRecommender = null;
        mHandlerThread.quit();
        mHandlerThread = null;
        mHandler = null;
        super.onDestroy();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (DEBUG) Log.d(TAG, "onStartCommand");
        if (intent != null) {
            String action = intent.getAction();
            if (ACTION_SHOW_RECOMMENDATION.equals(action)) {
                mHandler.removeMessages(MSG_SHOW_RECOMMENDATION);
                mHandler.removeMessages(MSG_HIDE_RECOMMENDATION);
                mHandler.obtainMessage(MSG_SHOW_RECOMMENDATION).sendToTarget();
            } else if (ACTION_HIDE_RECOMMENDATION.equals(action)) {
                mHandler.removeMessages(MSG_SHOW_RECOMMENDATION);
                mHandler.removeMessages(MSG_UPDATE_RECOMMENDATION);
                mHandler.removeMessages(MSG_HIDE_RECOMMENDATION);
                mHandler.obtainMessage(MSG_HIDE_RECOMMENDATION).sendToTarget();
            }
        }
        return START_STICKY;
    }

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

    @Override
    public void onRecommenderReady() {
        if (DEBUG) Log.d(TAG, "onRecommendationReady");
        if (mShowRecommendationAfterRecommenderReady) {
            mHandler.sendEmptyMessage(MSG_SHOW_RECOMMENDATION);
            mShowRecommendationAfterRecommenderReady = false;
        }
    }

    @Override
    public void onRecommendationChanged() {
        if (DEBUG) Log.d(TAG, "onRecommendationChanged");
        SparseLongArray notificationChannels = new SparseLongArray();
        for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
            if (mNotificationChannels[i] == Channel.INVALID_ID) {
                continue;
            }
            notificationChannels.put(i, mNotificationChannels[i]);
        }
        List<Channel> channels = mRecommender.recommendChannels();
        for (Channel c : channels) {
            int index = notificationChannels.indexOfValue(c.getId());
            if (index >= 0) {
                notificationChannels.removeAt(index);
            }
        }
        // Cancel notification whose channels are not recommended anymore.
        if (notificationChannels.size() > 0) {
            for (int i = 0; i < notificationChannels.size(); ++i) {
                int notificationId = notificationChannels.keyAt(i);
                mNotificationManager.cancel(NOTIFY_TAG, notificationId);
                mNotificationChannels[notificationId] = Channel.INVALID_ID;
                --mCurrentNotificationCount;
            }
            showRecommendation();
        }
    }

    private void showRecommendation() {
        if (DEBUG) Log.d(TAG, "showRecommendation");
        List<Channel> channels = mRecommender.recommendChannels();
        for (Channel c : channels) {
            if (mCurrentNotificationCount >= NOTIFICATION_COUNT) {
                break;
            }
            if (!isNotifiedChannel(c.getId())) {
                sendNotification(c.getId(), getAvailableNotificationId());
            }
        }
        if (mCurrentNotificationCount < NOTIFICATION_COUNT) {
            Message msg = mHandler.obtainMessage(MSG_SHOW_RECOMMENDATION);
            mHandler.sendMessageDelayed(msg, RECOMMENDATION_RETRY_TIME_MS);
        }
    }

    private void changeRecommendation(int notificationId) {
        if (DEBUG) Log.d(TAG, "changeRecommendation");
        List<Channel> channels = mRecommender.recommendChannels();
        if (mNotificationChannels[notificationId] != Channel.INVALID_ID) {
            mNotificationChannels[notificationId] = Channel.INVALID_ID;
            --mCurrentNotificationCount;
        }
        for (Channel c : channels) {
            if (!isNotifiedChannel(c.getId())) {
                if(sendNotification(c.getId(), notificationId)) {
                    return;
                }
            }
        }
        mNotificationManager.cancel(NOTIFY_TAG, notificationId);
    }

    private void hideAllRecommendation() {
       for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
           if (mNotificationChannels[i] != Channel.INVALID_ID) {
               mNotificationChannels[i] = Channel.INVALID_ID;
               mNotificationManager.cancel(NOTIFY_TAG, i);
           }
       }
       mCurrentNotificationCount = 0;
    }

    private boolean sendNotification(final long channelId, final int notificationId) {
        final ChannelRecord cr = mRecommender.getChannelRecord(channelId);
        if (cr == null) {
            return false;
        }
        final Channel channel = cr.getChannel();
        if (DEBUG) {
            Log.d(TAG, "sendNotification (channelName=" + channel.getDisplayName() + " notifyId="
                    + notificationId + ")");
        }
        Intent intent = new Intent(Intent.ACTION_VIEW, channel.getUri());
        intent.putExtra(TUNE_PARAMS_RECOMMENDATION_TYPE, mRecommendationType);
        final PendingIntent notificationIntent = PendingIntent.getActivity(this, 0, intent, 0);

        // TODO: Move some checking logic into TvRecommendation.
        String inputId = Utils.getInputIdForChannel(this, channel.getId());
        if (TextUtils.isEmpty(inputId)) {
            return false;
        }
        TvInputInfo inputInfo = mTvInputManagerHelper.getTvInputInfo(inputId);
        if (inputInfo == null) {
            return false;
        }
        final String inputDisplayName = inputInfo.loadLabel(this).toString();

        final Program program = Utils.getCurrentProgram(this, channel.getId());
        if (program == null) {
            return false;
        }
        final long programDurationMs = program.getEndTimeUtcMillis()
                - program.getStartTimeUtcMillis();
        long programLeftTimsMs = program.getEndTimeUtcMillis() - System.currentTimeMillis();
        final int programProgress = (programDurationMs <= 0) ? -1
                : 100 - (int) (programLeftTimsMs * 100 / programDurationMs);

        // We recommend those programs that meet the condition only.
        if (programProgress >= RECOMMENDATION_THRESHOLD_PROGRESS
                && programLeftTimsMs <= RECOMMENDATION_THRESHOLD_LEFT_TIME_MS) {
            return false;
        }

        // We don't trust TIS to provide us with proper sized image
        ScaledBitmapInfo posterArtBitmapInfo = BitmapUtils.decodeSampledBitmapFromUriString(this,
                program.getPosterArtUri(), (int) mNotificationCardMaxWidth,
                (int) mNotificationCardHeight);
        if (posterArtBitmapInfo == null) {
            Log.e(TAG, "Failed to decode poster image for " + program.getPosterArtUri());
            return false;
        }
        final Bitmap posterArtBitmap = posterArtBitmapInfo.bitmap;

        channel.loadBitmap(this, Channel.LOAD_IMAGE_TYPE_CHANNEL_LOGO, mChannelLogoMaxWidth,
                mChannelLogoMaxHeight, new Channel.LoadImageCallback() {
                    @Override
                    public void onLoadImageFinished(Channel channel, int type, Bitmap channelLogo) {
                        // This callback will run on the main thread.
                        Bitmap largeIconBitmap = (channelLogo == null) ? posterArtBitmap
                                : overlayChannelLogo(channelLogo, posterArtBitmap);
                        String channelDisplayName = channel.getDisplayName();
                        Notification notification =
                                new Notification.Builder(NotificationService.this)
                                        .setContentIntent(notificationIntent)
                                        .setContentTitle(program.getTitle())
                                        .setContentText(inputDisplayName + " " +
                                                (TextUtils.isEmpty(channelDisplayName)
                                                ? channel.getDisplayNumber() : channelDisplayName))
                                        .setContentInfo(channelDisplayName)
                                        .setAutoCancel(true)
                                        .setLargeIcon(largeIconBitmap)
                                        .setSmallIcon(R.drawable.ic_launcher_s)
                                        .setCategory(Notification.CATEGORY_RECOMMENDATION)
                                        .setProgress((programProgress > 0) ? 100 : 0,
                                                programProgress,
                                                false)
                                        .setSortKey(mRecommender.getChannelSortKey(channelId))
                                        .build();
                        notification.color = Utils.getColor(getResources(),
                                R.color.recommendation_card_background);
                        if (!TextUtils.isEmpty(program.getThumbnailUri())) {
                            notification.extras.putString(Notification.EXTRA_BACKGROUND_IMAGE_URI,
                                    program.getThumbnailUri());
                        }
                        mNotificationManager.notify(NOTIFY_TAG, notificationId, notification);
                        Message msg = mHandler.obtainMessage(
                                MSG_UPDATE_RECOMMENDATION, notificationId, 0, channel);
                        mHandler.sendMessageDelayed(msg,
                                programDurationMs / MAX_PROGRAM_UPDATE_COUNT);
                    }
                });

        if (mNotificationChannels[notificationId] == Channel.INVALID_ID) {
            ++mCurrentNotificationCount;
        }
        mNotificationChannels[notificationId] = channel.getId();

        return true;
    }

    private Bitmap overlayChannelLogo(Bitmap logo, Bitmap background) {
        Bitmap result = BitmapUtils.scaleBitmap(
                background, Integer.MAX_VALUE, mCardImageHeight);
        Bitmap scaledLogo = BitmapUtils.scaleBitmap(
                logo, mChannelLogoMaxWidth, mChannelLogoMaxHeight);
        Canvas canvas = new Canvas(result);
        canvas.drawBitmap(result, new Matrix(), null);
        Rect rect = new Rect();
        int startPadding;
        if (result.getWidth() < mCardImageMinWidth) {
            // TODO: check the positions.
            startPadding = mLogoPaddingStart;
            rect.bottom = result.getHeight() - mLogoPaddingBottom;
            rect.top = rect.bottom - scaledLogo.getHeight();
        } else if (result.getWidth() < mCardImageMaxWidth) {
            startPadding = mLogoPaddingStart;
            rect.bottom = result.getHeight() - mLogoPaddingBottom;
            rect.top = rect.bottom - scaledLogo.getHeight();
        } else {
            int marginStart = (result.getWidth() - mCardImageMaxWidth) / 2;
            startPadding = mLogoPaddingStart + marginStart;
            rect.bottom = result.getHeight() - mLogoPaddingBottom;
            rect.top = rect.bottom - scaledLogo.getHeight();
        }
        if (getResources().getConfiguration().getLayoutDirection() == View.LAYOUT_DIRECTION_LTR) {
            rect.left = startPadding;
            rect.right = startPadding + scaledLogo.getWidth();
        } else {
            rect.right = result.getWidth() - startPadding;
            rect.left = rect.right - scaledLogo.getWidth();
        }
        Paint paint = new Paint();
        paint.setAlpha(getResources().getInteger(R.integer.notif_card_ch_logo_alpha));
        canvas.drawBitmap(scaledLogo, null, rect, paint);
        return result;
    }

    private boolean isNotifiedChannel(long channelId) {
        for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
            if (mNotificationChannels[i] == channelId) {
                return true;
            }
        }
        return false;
    }

    private int getAvailableNotificationId() {
        for (int i = 0; i < NOTIFICATION_COUNT; ++i) {
            if (mNotificationChannels[i] == Channel.INVALID_ID) {
                return i;
            }
        }
        return -1;
    }

    private static class NotificationHandler extends WeakHandler<NotificationService> {
        public NotificationHandler(@NonNull Looper looper, NotificationService ref) {
            super(looper, ref);
        }

        @Override
        public void handleMessage(Message msg, @NonNull NotificationService notificationService) {
            switch (msg.what) {
                case MSG_INITIALIZE_RECOMMENDER: {
                    notificationService.handleInitializeRecommender();
                    break;
                }
                case MSG_SHOW_RECOMMENDATION: {
                    notificationService.handleShowRecommendation();
                    break;
                }
                case MSG_UPDATE_RECOMMENDATION: {
                    int notificationId = msg.arg1;
                    Channel channel = ((Channel) msg.obj);
                    notificationService.handleUpdateRecommendation(notificationId, channel);
                    break;
                }
                case MSG_HIDE_RECOMMENDATION: {
                    notificationService.handleHideRecommendation();
                    break;
                }
                default: {
                    super.handleMessage(msg);
                }
            }
        }
    }
}