Home | History | Annotate | Download | only in com.example.android.wearable.wear.wearnotifications
      1 /*
      2 Copyright 2016 The Android Open Source Project
      3 
      4 Licensed under the Apache License, Version 2.0 (the "License");
      5 you may not use this file except in compliance with the License.
      6 You may obtain a copy of the License at
      7 
      8 http://www.apache.org/licenses/LICENSE-2.0
      9 
     10 Unless required by applicable law or agreed to in writing, software
     11 distributed under the License is distributed on an "AS IS" BASIS,
     12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13 See the License for the specific language governing permissions and
     14 limitations under the License.
     15  */
     16 package com.example.android.wearable.wear.wearnotifications;
     17 
     18 import android.app.Notification;
     19 import android.app.PendingIntent;
     20 import android.content.Intent;
     21 import android.graphics.BitmapFactory;
     22 import android.os.Build;
     23 import android.os.Bundle;
     24 import android.support.design.widget.Snackbar;
     25 import android.support.v4.app.NotificationCompat.BigPictureStyle;
     26 import android.support.v4.app.NotificationCompat.BigTextStyle;
     27 import android.support.v4.app.NotificationCompat.InboxStyle;
     28 import android.support.v4.app.NotificationCompat.MessagingStyle;
     29 import android.support.v4.app.NotificationManagerCompat;
     30 import android.support.v4.app.RemoteInput;
     31 import android.support.v4.app.TaskStackBuilder;
     32 import android.support.v7.app.AppCompatActivity;
     33 import android.support.v7.app.NotificationCompat;
     34 import android.util.Log;
     35 import android.view.View;
     36 import android.widget.AdapterView;
     37 import android.widget.ArrayAdapter;
     38 import android.widget.RelativeLayout;
     39 import android.widget.Spinner;
     40 import android.widget.TextView;
     41 
     42 
     43 
     44 import com.example.android.wearable.wear.wearnotifications.handlers.BigPictureSocialIntentService;
     45 import com.example.android.wearable.wear.wearnotifications.handlers.BigPictureSocialMainActivity;
     46 import com.example.android.wearable.wear.wearnotifications.handlers.BigTextIntentService;
     47 import com.example.android.wearable.wear.wearnotifications.handlers.BigTextMainActivity;
     48 import com.example.android.wearable.wear.wearnotifications.handlers.InboxMainActivity;
     49 import com.example.android.wearable.wear.wearnotifications.handlers.MessagingIntentService;
     50 import com.example.android.wearable.wear.wearnotifications.handlers.MessagingMainActivity;
     51 import com.example.android.wearable.wear.wearnotifications.mock.MockDatabase;
     52 
     53 /**
     54  * The Activity demonstrates several popular Notification.Style examples along with their best
     55  * practices (include proper Android Wear support when you don't have a dedicated Android Wear
     56  * app).
     57  */
     58 public class MainActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
     59 
     60     public static final String TAG = "MainActivity";
     61 
     62     public static final int NOTIFICATION_ID = 888;
     63 
     64     // Used for Notification Style array and switch statement for Spinner selection
     65     private static final String BIG_TEXT_STYLE = "BIG_TEXT_STYLE";
     66     private static final String BIG_PICTURE_STYLE = "BIG_PICTURE_STYLE";
     67     private static final String INBOX_STYLE = "INBOX_STYLE";
     68     private static final String MESSAGING_STYLE = "MESSAGING_STYLE";
     69 
     70     // Collection of notification styles to back ArrayAdapter for Spinner
     71     private static final String[] NOTIFICATION_STYLES =
     72             {BIG_TEXT_STYLE, BIG_PICTURE_STYLE, INBOX_STYLE, MESSAGING_STYLE};
     73 
     74     private static final String[] NOTIFICATION_STYLES_DESCRIPTION =
     75             {
     76                     "Demos reminder type app using BIG_TEXT_STYLE",
     77                     "Demos social type app using BIG_PICTURE_STYLE + inline notification response",
     78                     "Demos email type app using INBOX_STYLE",
     79                     "Demos messaging app using MESSAGING_STYLE + inline notification responses"
     80             };
     81 
     82     private NotificationManagerCompat mNotificationManagerCompat;
     83 
     84     private int mSelectedNotification = 0;
     85 
     86     // RelativeLayout is needed for SnackBars to alert users when Notifications are disabled for app
     87     private RelativeLayout mMainRelativeLayout;
     88     private Spinner mSpinner;
     89     private TextView mNotificationDetailsTextView;
     90 
     91     @Override
     92     protected void onCreate(Bundle savedInstanceState) {
     93 
     94         super.onCreate(savedInstanceState);
     95         setContentView(R.layout.activity_main);
     96 
     97         mMainRelativeLayout = (RelativeLayout) findViewById(R.id.mainRelativeLayout);
     98         mNotificationDetailsTextView = (TextView) findViewById(R.id.notificationDetails);
     99         mSpinner = (Spinner) findViewById(R.id.spinner);
    100 
    101         mNotificationManagerCompat = NotificationManagerCompat.from(getApplicationContext());
    102 
    103         // Create an ArrayAdapter using the string array and a default spinner layout
    104         ArrayAdapter<CharSequence> adapter =
    105                 new ArrayAdapter(
    106                         this,
    107                         android.R.layout.simple_spinner_item,
    108                         NOTIFICATION_STYLES);
    109         // Specify the layout to use when the list of choices appears
    110         adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    111         // Apply the adapter to the spinner
    112         mSpinner.setAdapter(adapter);
    113         mSpinner.setOnItemSelectedListener(this);
    114     }
    115 
    116     @Override
    117     public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    118         Log.d(TAG, "onItemSelected(): position: " + position + " id: " + id);
    119 
    120         mSelectedNotification = position;
    121 
    122         mNotificationDetailsTextView.setText(
    123                 NOTIFICATION_STYLES_DESCRIPTION[mSelectedNotification]);
    124     }
    125     @Override
    126     public void onNothingSelected(AdapterView<?> parent) {
    127         // Required
    128     }
    129 
    130     public void onClick(View view) {
    131 
    132         Log.d(TAG, "onClick()");
    133 
    134         boolean areNotificationsEnabled = mNotificationManagerCompat.areNotificationsEnabled();
    135 
    136         if (!areNotificationsEnabled) {
    137             // Because the user took an action to create a notification, we create a prompt to let
    138             // the user re-enable notifications for this application again.
    139             Snackbar snackbar = Snackbar
    140                     .make(
    141                             mMainRelativeLayout,
    142                             "You need to enable notifications for this app",
    143                             Snackbar.LENGTH_LONG)
    144                     .setAction("ENABLE", new View.OnClickListener() {
    145                         @Override
    146                         public void onClick(View view) {
    147                             // Links to this app's notification settings
    148                             openNotificationSettingsForApp();
    149                         }
    150                     });
    151             snackbar.show();
    152             return;
    153         }
    154 
    155         String notificationStyle = NOTIFICATION_STYLES[mSelectedNotification];
    156 
    157         switch (notificationStyle) {
    158             case BIG_TEXT_STYLE:
    159                 generateBigTextStyleNotification();
    160                 break;
    161 
    162             case BIG_PICTURE_STYLE:
    163                 generateBigPictureStyleNotification();
    164                 break;
    165 
    166             case INBOX_STYLE:
    167                 generateInboxStyleNotification();
    168                 break;
    169 
    170             case MESSAGING_STYLE:
    171                 generateMessagingStyleNotification();
    172                 break;
    173 
    174             default:
    175                 // continue below
    176         }
    177     }
    178 
    179     /*
    180      * Generates a BIG_TEXT_STYLE Notification that supports both phone/tablet and wear. For devices
    181      * on API level 16 (4.1.x - Jelly Bean) and after, displays BIG_TEXT_STYLE. Otherwise, displays
    182      * a basic notification.
    183      */
    184     private void generateBigTextStyleNotification() {
    185 
    186         Log.d(TAG, "generateBigTextStyleNotification()");
    187 
    188         // Main steps for building a BIG_TEXT_STYLE notification:
    189         //      0. Get your data
    190         //      1. Build the BIG_TEXT_STYLE
    191         //      2. Set up main Intent for notification
    192         //      3. Create additional Actions for the Notification
    193         //      4. Build and issue the notification
    194 
    195         // 0. Get your data (everything unique per Notification)
    196         MockDatabase.BigTextStyleReminderAppData bigTextStyleReminderAppData =
    197                 MockDatabase.getBigTextStyleData();
    198 
    199         // 1. Build the BIG_TEXT_STYLE
    200         BigTextStyle bigTextStyle = new NotificationCompat.BigTextStyle()
    201                 // Overrides ContentText in the big form of the template
    202                 .bigText(bigTextStyleReminderAppData.getBigText())
    203                 // Overrides ContentTitle in the big form of the template
    204                 .setBigContentTitle(bigTextStyleReminderAppData.getBigContentTitle())
    205                 // Summary line after the detail section in the big form of the template
    206                 // Note: To improve readability, don't overload the user with info. If Summary Text
    207                 // doesn't add critical information, you should skip it.
    208                 .setSummaryText(bigTextStyleReminderAppData.getSummaryText());
    209 
    210 
    211         // 2. Set up main Intent for notification
    212         Intent notifyIntent = new Intent(this, BigTextMainActivity.class);
    213 
    214         // When creating your Intent, you need to take into account the back state, i.e., what
    215         // happens after your Activity launches and the user presses the back button.
    216 
    217         // There are two options:
    218         //      1. Regular activity - You're starting an Activity that's part of the application's
    219         //      normal workflow.
    220 
    221         //      2. Special activity - The user only sees this Activity if it's started from a
    222         //      notification. In a sense, the Activity extends the notification by providing
    223         //      information that would be hard to display in the notification itself.
    224 
    225         // For the BIG_TEXT_STYLE notification, we will consider the activity launched by the main
    226         // Intent as a special activity, so we will follow option 2.
    227 
    228         // For an example of option 1, check either the MESSAGING_STYLE or BIG_PICTURE_STYLE
    229         // examples.
    230 
    231         // For more information, check out our dev article:
    232         // https://developer.android.com/training/notify-user/navigation.html
    233 
    234         // Sets the Activity to start in a new, empty task
    235         notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    236 
    237         PendingIntent notifyPendingIntent =
    238                 PendingIntent.getActivity(
    239                         this,
    240                         0,
    241                         notifyIntent,
    242                         PendingIntent.FLAG_UPDATE_CURRENT
    243                 );
    244 
    245 
    246         // 3. Create additional Actions (Intents) for the Notification
    247 
    248         // In our case, we create two additional actions: a Snooze action and a Dismiss action
    249         // Snooze Action
    250         Intent snoozeIntent = new Intent(this, BigTextIntentService.class);
    251         snoozeIntent.setAction(BigTextIntentService.ACTION_SNOOZE);
    252 
    253         PendingIntent snoozePendingIntent = PendingIntent.getService(this, 0, snoozeIntent, 0);
    254         NotificationCompat.Action snoozeAction =
    255                 new NotificationCompat.Action.Builder(
    256                         R.drawable.ic_alarm_white_48dp,
    257                         "Snooze",
    258                         snoozePendingIntent)
    259                         .build();
    260 
    261 
    262         // Dismiss Action
    263         Intent dismissIntent = new Intent(this, BigTextIntentService.class);
    264         dismissIntent.setAction(BigTextIntentService.ACTION_DISMISS);
    265 
    266         PendingIntent dismissPendingIntent = PendingIntent.getService(this, 0, dismissIntent, 0);
    267         NotificationCompat.Action dismissAction =
    268                 new NotificationCompat.Action.Builder(
    269                         R.drawable.ic_cancel_white_48dp,
    270                         "Dismiss",
    271                         dismissPendingIntent)
    272                         .build();
    273 
    274 
    275         // 4. Build and issue the notification
    276 
    277         // Because we want this to be a new notification (not updating a previous notification), we
    278         // create a new Builder. Later, we use the same global builder to get back the notification
    279         // we built here for the snooze action, that is, canceling the notification and relaunching
    280         // it several seconds later.
    281 
    282         NotificationCompat.Builder notificationCompatBuilder =
    283                 new NotificationCompat.Builder(getApplicationContext());
    284 
    285         GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);
    286 
    287         Notification notification = notificationCompatBuilder
    288                 // BIG_TEXT_STYLE sets title and content for API 16 (4.1 and after)
    289                 .setStyle(bigTextStyle)
    290                 // Title for API <16 (4.0 and below) devices
    291                 .setContentTitle(bigTextStyleReminderAppData.getContentTitle())
    292                 // Content for API <24 (7.0 and below) devices
    293                 .setContentText(bigTextStyleReminderAppData.getContentText())
    294                 .setSmallIcon(R.drawable.ic_launcher)
    295                 .setLargeIcon(BitmapFactory.decodeResource(
    296                         getResources(),
    297                         R.drawable.ic_alarm_white_48dp))
    298                 .setContentIntent(notifyPendingIntent)
    299                 // Set primary color (important for Wear 2.0 Notifications)
    300                 .setColor(getResources().getColor(R.color.colorPrimary))
    301 
    302                 // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
    303                 // devices and all Android Wear devices. If you have more than one notification and
    304                 // you prefer a different summary notification, set a group key and create a
    305                 // summary notification via
    306                 // .setGroupSummary(true)
    307                 // .setGroup(GROUP_KEY_YOUR_NAME_HERE)
    308 
    309                 .setCategory(Notification.CATEGORY_REMINDER)
    310                 .setPriority(Notification.PRIORITY_HIGH)
    311 
    312                 // Shows content on the lock-screen
    313                 .setVisibility(Notification.VISIBILITY_PUBLIC)
    314 
    315                 // Adds additional actions specified above
    316                 .addAction(snoozeAction)
    317                 .addAction(dismissAction)
    318 
    319                 .build();
    320 
    321         mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
    322     }
    323 
    324     /*
    325      * Generates a BIG_PICTURE_STYLE Notification that supports both phone/tablet and wear. For
    326      * devices on API level 16 (4.1.x - Jelly Bean) and after, displays BIG_PICTURE_STYLE.
    327      * Otherwise, displays a basic notification.
    328      *
    329      * This example Notification is a social post. It allows updating the notification with
    330      * comments/responses via RemoteInput and the BigPictureSocialIntentService on 24+ (N+) and
    331      * Android Wear devices.
    332      */
    333     private void generateBigPictureStyleNotification() {
    334 
    335         Log.d(TAG, "generateBigPictureStyleNotification()");
    336 
    337         // Main steps for building a BIG_PICTURE_STYLE notification:
    338         //      0. Get your data
    339         //      1. Build the BIG_PICTURE_STYLE
    340         //      2. Set up main Intent for notification
    341         //      3. Set up RemoteInput, so users can input (keyboard and voice) from notification
    342         //      4. Build and issue the notification
    343 
    344         // 0. Get your data (everything unique per Notification)
    345         MockDatabase.BigPictureStyleSocialAppData bigPictureStyleSocialAppData =
    346                 MockDatabase.getBigPictureStyleData();
    347 
    348         // 1. Build the BIG_PICTURE_STYLE
    349         BigPictureStyle bigPictureStyle = new NotificationCompat.BigPictureStyle()
    350                 // Provides the bitmap for the BigPicture notification
    351                 .bigPicture(
    352                         BitmapFactory.decodeResource(
    353                                 getResources(),
    354                                 bigPictureStyleSocialAppData.getBigImage()))
    355                 // Overrides ContentTitle in the big form of the template
    356                 .setBigContentTitle(bigPictureStyleSocialAppData.getBigContentTitle())
    357                 // Summary line after the detail section in the big form of the template
    358                 .setSummaryText(bigPictureStyleSocialAppData.getSummaryText());
    359 
    360         // 2. Set up main Intent for notification
    361         Intent mainIntent = new Intent(this, BigPictureSocialMainActivity.class);
    362 
    363         // When creating your Intent, you need to take into account the back state, i.e., what
    364         // happens after your Activity launches and the user presses the back button.
    365 
    366         // There are two options:
    367         //      1. Regular activity - You're starting an Activity that's part of the application's
    368         //      normal workflow.
    369 
    370         //      2. Special activity - The user only sees this Activity if it's started from a
    371         //      notification. In a sense, the Activity extends the notification by providing
    372         //      information that would be hard to display in the notification itself.
    373 
    374         // Even though this sample's MainActivity doesn't link to the Activity this Notification
    375         // launches directly, i.e., it isn't part of the normal workflow, a social app generally
    376         // always links to individual posts as part of the app flow, so we will follow option 1.
    377 
    378         // For an example of option 2, check out the BIG_TEXT_STYLE example.
    379 
    380         // For more information, check out our dev article:
    381         // https://developer.android.com/training/notify-user/navigation.html
    382 
    383         TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    384         // Adds the back stack
    385         stackBuilder.addParentStack(BigPictureSocialMainActivity.class);
    386         // Adds the Intent to the top of the stack
    387         stackBuilder.addNextIntent(mainIntent);
    388         // Gets a PendingIntent containing the entire back stack
    389         PendingIntent mainPendingIntent =
    390                 PendingIntent.getActivity(
    391                         this,
    392                         0,
    393                         mainIntent,
    394                         PendingIntent.FLAG_UPDATE_CURRENT
    395                 );
    396 
    397         // 3. Set up RemoteInput, so users can input (keyboard and voice) from notification
    398 
    399         // Note: For API <24 (M and below) we need to use an Activity, so the lock-screen presents
    400         // the auth challenge. For API 24+ (N and above), we use a Service (could be a
    401         // BroadcastReceiver), so the user can input from Notification or lock-screen (they have
    402         // choice to allow) without leaving the notification.
    403 
    404         // Create the RemoteInput
    405         String replyLabel = getString(R.string.reply_label);
    406         RemoteInput remoteInput =
    407                 new RemoteInput.Builder(BigPictureSocialIntentService.EXTRA_COMMENT)
    408                         .setLabel(replyLabel)
    409                         // List of quick response choices for any wearables paired with the phone
    410                         .setChoices(bigPictureStyleSocialAppData.getPossiblePostResponses())
    411                         .build();
    412 
    413         // Pending intent =
    414         //      API <24 (M and below): activity so the lock-screen presents the auth challenge
    415         //      API 24+ (N and above): this should be a Service or BroadcastReceiver
    416         PendingIntent replyActionPendingIntent;
    417 
    418         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    419             Intent intent = new Intent(this, BigPictureSocialIntentService.class);
    420             intent.setAction(BigPictureSocialIntentService.ACTION_COMMENT);
    421             replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);
    422 
    423         } else {
    424             replyActionPendingIntent = mainPendingIntent;
    425         }
    426 
    427         NotificationCompat.Action replyAction =
    428                 new NotificationCompat.Action.Builder(
    429                         R.drawable.ic_reply_white_18dp,
    430                         replyLabel,
    431                         replyActionPendingIntent)
    432                         .addRemoteInput(remoteInput)
    433                         .build();
    434 
    435         // 4. Build and issue the notification
    436 
    437         // Because we want this to be a new notification (not updating a previous notification), we
    438         // create a new Builder. Later, we use the same global builder to get back the notification
    439         // we built here for a comment on the post.
    440 
    441         NotificationCompat.Builder notificationCompatBuilder =
    442                 new NotificationCompat.Builder(getApplicationContext());
    443 
    444         GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);
    445 
    446         // 4. Build and issue the notification
    447         notificationCompatBuilder
    448                 // BIG_PICTURE_STYLE sets title and content for API 16 (4.1 and after)
    449                 .setStyle(bigPictureStyle)
    450                 // Title for API <16 (4.0 and below) devices
    451                 .setContentTitle(bigPictureStyleSocialAppData.getContentTitle())
    452                 // Content for API <24 (7.0 and below) devices
    453                 .setContentText(bigPictureStyleSocialAppData.getContentText())
    454                 .setSmallIcon(R.drawable.ic_launcher)
    455                 .setLargeIcon(BitmapFactory.decodeResource(
    456                         getResources(),
    457                         R.drawable.ic_person_black_48dp))
    458                 .setContentIntent(mainPendingIntent)
    459                 // Set primary color (important for Wear 2.0 Notifications)
    460                 .setColor(getResources().getColor(R.color.colorPrimary))
    461 
    462                 // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
    463                 // devices and all Android Wear devices. If you have more than one notification and
    464                 // you prefer a different summary notification, set a group key and create a
    465                 // summary notification via
    466                 // .setGroupSummary(true)
    467                 // .setGroup(GROUP_KEY_YOUR_NAME_HERE)
    468 
    469                 .setSubText(Integer.toString(1))
    470                 .addAction(replyAction)
    471                 .setCategory(Notification.CATEGORY_SOCIAL)
    472                 .setPriority(Notification.PRIORITY_HIGH)
    473 
    474                 // Hides content on the lock-screen
    475                 .setVisibility(Notification.VISIBILITY_PRIVATE);
    476 
    477         // If the phone is in "Do not disturb mode, the user will still be notified if
    478         // the sender(s) is starred as a favorite.
    479         for (String name : bigPictureStyleSocialAppData.getParticipants()) {
    480             notificationCompatBuilder.addPerson(name);
    481         }
    482 
    483         Notification notification = notificationCompatBuilder.build();
    484 
    485         mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
    486     }
    487 
    488     /*
    489      * Generates a INBOX_STYLE Notification that supports both phone/tablet and wear. For devices
    490      * on API level 16 (4.1.x - Jelly Bean) and after, displays INBOX_STYLE. Otherwise, displays a
    491      * basic notification.
    492      */
    493     private void generateInboxStyleNotification() {
    494 
    495         Log.d(TAG, "generateInboxStyleNotification()");
    496 
    497 
    498         // Main steps for building a INBOX_STYLE notification:
    499         //      0. Get your data
    500         //      1. Build the INBOX_STYLE
    501         //      2. Set up main Intent for notification
    502         //      3. Build and issue the notification
    503 
    504         // 0. Get your data (everything unique per Notification)
    505         MockDatabase.InboxStyleEmailAppData inboxStyleEmailAppData =
    506                 MockDatabase.getInboxStyleData();
    507 
    508         // 1. Build the INBOX_STYLE
    509         InboxStyle inboxStyle = new NotificationCompat.InboxStyle()
    510                 // This title is slightly different than regular title, since I know INBOX_STYLE is
    511                 // available.
    512                 .setBigContentTitle(inboxStyleEmailAppData.getBigContentTitle())
    513                 .setSummaryText(inboxStyleEmailAppData.getSummaryText());
    514 
    515         // Add each summary line of the new emails, you can add up to 5
    516         for (String summary : inboxStyleEmailAppData.getIndividualEmailSummary()) {
    517             inboxStyle.addLine(summary);
    518         }
    519 
    520         // 2. Set up main Intent for notification
    521         Intent mainIntent = new Intent(this, InboxMainActivity.class);
    522 
    523         // When creating your Intent, you need to take into account the back state, i.e., what
    524         // happens after your Activity launches and the user presses the back button.
    525 
    526         // There are two options:
    527         //      1. Regular activity - You're starting an Activity that's part of the application's
    528         //      normal workflow.
    529 
    530         //      2. Special activity - The user only sees this Activity if it's started from a
    531         //      notification. In a sense, the Activity extends the notification by providing
    532         //      information that would be hard to display in the notification itself.
    533 
    534         // Even though this sample's MainActivity doesn't link to the Activity this Notification
    535         // launches directly, i.e., it isn't part of the normal workflow, a eamil app generally
    536         // always links to individual emails as part of the app flow, so we will follow option 1.
    537 
    538         // For an example of option 2, check out the BIG_TEXT_STYLE example.
    539 
    540         // For more information, check out our dev article:
    541         // https://developer.android.com/training/notify-user/navigation.html
    542 
    543         TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    544         // Adds the back stack
    545         stackBuilder.addParentStack(InboxMainActivity.class);
    546         // Adds the Intent to the top of the stack
    547         stackBuilder.addNextIntent(mainIntent);
    548         // Gets a PendingIntent containing the entire back stack
    549         PendingIntent mainPendingIntent =
    550                 PendingIntent.getActivity(
    551                         this,
    552                         0,
    553                         mainIntent,
    554                         PendingIntent.FLAG_UPDATE_CURRENT
    555                 );
    556 
    557         // 3. Build and issue the notification
    558 
    559         // Because we want this to be a new notification (not updating a previous notification), we
    560         // create a new Builder. However, we don't need to update this notification later, so we
    561         // will not need to set a global builder for access to the notification later.
    562 
    563         NotificationCompat.Builder notificationCompatBuilder =
    564                 new NotificationCompat.Builder(getApplicationContext());
    565 
    566         GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);
    567 
    568         // 4. Build and issue the notification
    569         notificationCompatBuilder
    570 
    571                 // INBOX_STYLE sets title and content for API 16+ (4.1 and after) when the
    572                 // notification is expanded
    573                 .setStyle(inboxStyle)
    574 
    575                 // Title for API <16 (4.0 and below) devices and API 16+ (4.1 and after) when the
    576                 // notification is collapsed
    577                 .setContentTitle(inboxStyleEmailAppData.getContentTitle())
    578 
    579                 // Content for API <24 (7.0 and below) devices and API 16+ (4.1 and after) when the
    580                 // notification is collapsed
    581                 .setContentText(inboxStyleEmailAppData.getContentText())
    582                 .setSmallIcon(R.drawable.ic_launcher)
    583                 .setLargeIcon(BitmapFactory.decodeResource(
    584                         getResources(),
    585                         R.drawable.ic_person_black_48dp))
    586                 .setContentIntent(mainPendingIntent)
    587                 // Set primary color (important for Wear 2.0 Notifications)
    588                 .setColor(getResources().getColor(R.color.colorPrimary))
    589 
    590                 // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
    591                 // devices and all Android Wear devices. If you have more than one notification and
    592                 // you prefer a different summary notification, set a group key and create a
    593                 // summary notification via
    594                 // .setGroupSummary(true)
    595                 // .setGroup(GROUP_KEY_YOUR_NAME_HERE)
    596 
    597                 // Sets large number at the right-hand side of the notification for API <24 devices
    598                 .setSubText(Integer.toString(inboxStyleEmailAppData.getNumberOfNewEmails()))
    599 
    600                 .setCategory(Notification.CATEGORY_EMAIL)
    601                 .setPriority(Notification.PRIORITY_HIGH)
    602 
    603                 // Hides content on the lock-screen
    604                 .setVisibility(Notification.VISIBILITY_PRIVATE);
    605 
    606         // If the phone is in "Do not disturb mode, the user will still be notified if
    607         // the sender(s) is starred as a favorite.
    608         for (String name : inboxStyleEmailAppData.getParticipants()) {
    609             notificationCompatBuilder.addPerson(name);
    610         }
    611 
    612         Notification notification = notificationCompatBuilder.build();
    613 
    614         mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
    615     }
    616 
    617     /*
    618      * Generates a MESSAGING_STYLE Notification that supports both phone/tablet and wear. For
    619      * devices on API level 24 (7.0 - Nougat) and after, displays MESSAGING_STYLE. Otherwise,
    620      * displays a basic BIG_TEXT_STYLE.
    621      */
    622     private void generateMessagingStyleNotification() {
    623 
    624         Log.d(TAG, "generateMessagingStyleNotification()");
    625 
    626         // Main steps for building a MESSAGING_STYLE notification:
    627         //      0. Get your data
    628         //      1. Build the MESSAGING_STYLE
    629         //      2. Add support for Wear 1.+
    630         //      3. Set up main Intent for notification
    631         //      4. Set up RemoteInput (users can input directly from notification)
    632         //      5. Build and issue the notification
    633 
    634         // 0. Get your data (everything unique per Notification)
    635         MockDatabase.MessagingStyleCommsAppData messagingStyleCommsAppData =
    636                 MockDatabase.getMessagingStyleData();
    637 
    638         // 1. Build the Notification.Style (MESSAGING_STYLE)
    639         String contentTitle = messagingStyleCommsAppData.getContentTitle();
    640 
    641         MessagingStyle messagingStyle =
    642                 new NotificationCompat.MessagingStyle(messagingStyleCommsAppData.getReplayName())
    643                         // You could set a different title to appear when the messaging style
    644                         // is supported on device (24+) if you wish. In our case, we use the same
    645                         // title.
    646                         .setConversationTitle(contentTitle);
    647 
    648         // Adds all Messages
    649         // Note: Messages include the text, timestamp, and sender
    650         for (MessagingStyle.Message message : messagingStyleCommsAppData.getMessages()) {
    651             messagingStyle.addMessage(message);
    652         }
    653 
    654 
    655         // 2. Add support for Wear 1.+
    656 
    657         // Since Wear 1.0 doesn't support the MESSAGING_STYLE, we use the BIG_TEXT_STYLE, so all the
    658         // text is visible.
    659 
    660         // This is basically a toString() of all the Messages above.
    661         String fullMessageForWearVersion1 = messagingStyleCommsAppData.getFullConversation();
    662 
    663         Notification chatHistoryForWearV1 = new NotificationCompat.Builder(getApplicationContext())
    664                 .setStyle(new BigTextStyle().bigText(fullMessageForWearVersion1))
    665                 .setContentTitle(contentTitle)
    666                 .setSmallIcon(R.drawable.ic_launcher)
    667                 .setContentText(fullMessageForWearVersion1)
    668                 .build();
    669 
    670         // Adds page with all text to support Wear 1.+.
    671         NotificationCompat.WearableExtender wearableExtenderForWearVersion1 =
    672                 new NotificationCompat.WearableExtender()
    673                         .addPage(chatHistoryForWearV1);
    674 
    675 
    676 
    677         // 3. Set up main Intent for notification
    678         Intent notifyIntent = new Intent(this, MessagingMainActivity.class);
    679 
    680         // When creating your Intent, you need to take into account the back state, i.e., what
    681         // happens after your Activity launches and the user presses the back button.
    682 
    683         // There are two options:
    684         //      1. Regular activity - You're starting an Activity that's part of the application's
    685         //      normal workflow.
    686 
    687         //      2. Special activity - The user only sees this Activity if it's started from a
    688         //      notification. In a sense, the Activity extends the notification by providing
    689         //      information that would be hard to display in the notification itself.
    690 
    691         // Even though this sample's MainActivity doesn't link to the Activity this Notification
    692         // launches directly, i.e., it isn't part of the normal workflow, a chat app generally
    693         // always links to individual conversations as part of the app flow, so we will follow
    694         // option 1.
    695 
    696         // For an example of option 2, check out the BIG_TEXT_STYLE example.
    697 
    698         // For more information, check out our dev article:
    699         // https://developer.android.com/training/notify-user/navigation.html
    700 
    701         TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    702         // Adds the back stack
    703         stackBuilder.addParentStack(MessagingMainActivity.class);
    704         // Adds the Intent to the top of the stack
    705         stackBuilder.addNextIntent(notifyIntent);
    706         // Gets a PendingIntent containing the entire back stack
    707         PendingIntent mainPendingIntent =
    708                 PendingIntent.getActivity(
    709                         this,
    710                         0,
    711                         notifyIntent,
    712                         PendingIntent.FLAG_UPDATE_CURRENT
    713                 );
    714 
    715 
    716         // 4. Set up RemoteInput, so users can input (keyboard and voice) from notification
    717 
    718         // Note: For API <24 (M and below) we need to use an Activity, so the lock-screen present
    719         // the auth challenge. For API 24+ (N and above), we use a Service (could be a
    720         // BroadcastReceiver), so the user can input from Notification or lock-screen (they have
    721         // choice to allow) without leaving the notification.
    722 
    723         // Create the RemoteInput specifying this key
    724         String replyLabel = getString(R.string.reply_label);
    725         RemoteInput remoteInput = new RemoteInput.Builder(MessagingIntentService.EXTRA_REPLY)
    726                 .setLabel(replyLabel)
    727                 .build();
    728 
    729         // Pending intent =
    730         //      API <24 (M and below): activity so the lock-screen presents the auth challenge
    731         //      API 24+ (N and above): this should be a Service or BroadcastReceiver
    732         PendingIntent replyActionPendingIntent;
    733 
    734         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
    735             Intent intent = new Intent(this, MessagingIntentService.class);
    736             intent.setAction(MessagingIntentService.ACTION_REPLY);
    737             replyActionPendingIntent = PendingIntent.getService(this, 0, intent, 0);
    738 
    739         } else {
    740             replyActionPendingIntent = mainPendingIntent;
    741         }
    742 
    743         NotificationCompat.Action replyAction =
    744                 new NotificationCompat.Action.Builder(
    745                         R.drawable.ic_reply_white_18dp,
    746                         replyLabel,
    747                         replyActionPendingIntent)
    748                         .addRemoteInput(remoteInput)
    749                         // Allows system to generate replies by context of conversation
    750                         .setAllowGeneratedReplies(true)
    751                         .build();
    752 
    753 
    754         // 5. Build and issue the notification
    755 
    756         // Because we want this to be a new notification (not updating current notification), we
    757         // create a new Builder. Later, we update this same notification, so we need to save this
    758         // Builder globally (as outlined earlier).
    759 
    760         NotificationCompat.Builder notificationCompatBuilder =
    761                 new NotificationCompat.Builder(getApplicationContext());
    762 
    763         GlobalNotificationBuilder.setNotificationCompatBuilderInstance(notificationCompatBuilder);
    764 
    765         // Builds and issues notification
    766         notificationCompatBuilder
    767                 // MESSAGING_STYLE sets title and content for API 24+ (N and above) devices
    768                 .setStyle(messagingStyle)
    769                 // Title for API <24 (M and below) devices
    770                 .setContentTitle(contentTitle)
    771                 // Content for API <24 (M and below) devices
    772                 .setContentText(messagingStyleCommsAppData.getContentText())
    773                 .setSmallIcon(R.drawable.ic_launcher)
    774                 .setLargeIcon(BitmapFactory.decodeResource(
    775                         getResources(),
    776                         R.drawable.ic_person_black_48dp))
    777                 .setContentIntent(mainPendingIntent)
    778                 // Set primary color (important for Wear 2.0 Notifications)
    779                 .setColor(getResources().getColor(R.color.colorPrimary))
    780 
    781                 // SIDE NOTE: Auto-bundling is enabled for 4 or more notifications on API 24+ (N+)
    782                 // devices and all Android Wear devices. If you have more than one notification and
    783                 // you prefer a different summary notification, set a group key and create a
    784                 // summary notification via
    785                 // .setGroupSummary(true)
    786                 // .setGroup(GROUP_KEY_YOUR_NAME_HERE)
    787 
    788                 // Number of new notifications for API <24 (M and below) devices
    789                 .setSubText(Integer.toString(messagingStyleCommsAppData.getNumberOfNewMessages()))
    790 
    791                 .addAction(replyAction)
    792                 .setCategory(Notification.CATEGORY_MESSAGE)
    793                 .setPriority(Notification.PRIORITY_HIGH)
    794 
    795                 // Hides content on the lock-screen
    796                 .setVisibility(Notification.VISIBILITY_PRIVATE)
    797 
    798                 // Adds multiple pages for easy consumption on a wear device.
    799                 .extend(wearableExtenderForWearVersion1);
    800 
    801         // If the phone is in "Do not disturb mode, the user will still be notified if
    802         // the sender(s) is starred as a favorite.
    803         for (String name : messagingStyleCommsAppData.getParticipants()) {
    804             notificationCompatBuilder.addPerson(name);
    805         }
    806 
    807         Notification notification = notificationCompatBuilder.build();
    808         mNotificationManagerCompat.notify(NOTIFICATION_ID, notification);
    809     }
    810 
    811     /**
    812      * Helper method for the SnackBar action, i.e., if the user has this application's notifications
    813      * disabled, this opens up the dialog to turn them back on after the user requests a
    814      * Notification launch.
    815      *
    816      * IMPORTANT NOTE: You should not do this action unless the user takes an action to see your
    817      * Notifications like this sample demonstrates. Spamming users to re-enable your notifications
    818      * is a bad idea.
    819      */
    820     private void openNotificationSettingsForApp() {
    821         // Links to this app's notification settings
    822         Intent intent = new Intent();
    823         intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
    824         intent.putExtra("app_package", getPackageName());
    825         intent.putExtra("app_uid", getApplicationInfo().uid);
    826         startActivity(intent);
    827     }
    828 }