Home | History | Annotate | Download | only in cellbroadcastreceiver
      1 /*
      2  * Copyright (C) 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 
     17 package com.android.cellbroadcastreceiver;
     18 
     19 import android.app.Activity;
     20 import android.app.KeyguardManager;
     21 import android.app.NotificationManager;
     22 import android.content.Context;
     23 import android.content.Intent;
     24 import android.content.SharedPreferences;
     25 import android.content.res.Resources;
     26 import android.graphics.drawable.Drawable;
     27 import android.os.Bundle;
     28 import android.os.Handler;
     29 import android.os.Message;
     30 import android.os.PowerManager;
     31 import android.preference.PreferenceManager;
     32 import android.provider.Telephony;
     33 import android.telephony.CellBroadcastMessage;
     34 import android.telephony.SmsCbCmasInfo;
     35 import android.util.Log;
     36 import android.view.KeyEvent;
     37 import android.view.LayoutInflater;
     38 import android.view.View;
     39 import android.view.Window;
     40 import android.view.WindowManager;
     41 import android.widget.Button;
     42 import android.widget.ImageView;
     43 import android.widget.TextView;
     44 
     45 import java.util.ArrayList;
     46 import java.util.concurrent.atomic.AtomicInteger;
     47 
     48 /**
     49  * Custom alert dialog with optional flashing warning icon.
     50  * Alert audio and text-to-speech handled by {@link CellBroadcastAlertAudio}.
     51  */
     52 public class CellBroadcastAlertDialog extends Activity {
     53 
     54     private static final String TAG = "CellBroadcastAlertDialog";
     55 
     56     /** Intent extra for non-emergency alerts sent when user selects the notification. */
     57     static final String FROM_NOTIFICATION_EXTRA = "from_notification";
     58 
     59     // Intent extra to identify if notification was sent while trying to move away from the dialog
     60     //  without acknowledging the dialog
     61     static final String FROM_SAVE_STATE_NOTIFICATION_EXTRA = "from_save_state_notification";
     62 
     63     /** List of cell broadcast messages to display (oldest to newest). */
     64     protected ArrayList<CellBroadcastMessage> mMessageList;
     65 
     66     /** Whether a CMAS alert other than Presidential Alert was displayed. */
     67     private boolean mShowOptOutDialog;
     68 
     69     /** Length of time for the warning icon to be visible. */
     70     private static final int WARNING_ICON_ON_DURATION_MSEC = 800;
     71 
     72     /** Length of time for the warning icon to be off. */
     73     private static final int WARNING_ICON_OFF_DURATION_MSEC = 800;
     74 
     75     /** Length of time to keep the screen turned on. */
     76     private static final int KEEP_SCREEN_ON_DURATION_MSEC = 60000;
     77 
     78     /** Animation handler for the flashing warning icon (emergency alerts only). */
     79     private final AnimationHandler mAnimationHandler = new AnimationHandler();
     80 
     81     /** Handler to add and remove screen on flags for emergency alerts. */
     82     private final ScreenOffHandler mScreenOffHandler = new ScreenOffHandler();
     83 
     84     /**
     85      * Animation handler for the flashing warning icon (emergency alerts only).
     86      */
     87     private class AnimationHandler extends Handler {
     88         /** Latest {@code message.what} value for detecting old messages. */
     89         private final AtomicInteger mCount = new AtomicInteger();
     90 
     91         /** Warning icon state: visible == true, hidden == false. */
     92         private boolean mWarningIconVisible;
     93 
     94         /** The warning icon Drawable. */
     95         private Drawable mWarningIcon;
     96 
     97         /** The View containing the warning icon. */
     98         private ImageView mWarningIconView;
     99 
    100         /** Package local constructor (called from outer class). */
    101         AnimationHandler() {}
    102 
    103         /** Start the warning icon animation. */
    104         void startIconAnimation() {
    105             if (!initDrawableAndImageView()) {
    106                 return;     // init failure
    107             }
    108             mWarningIconVisible = true;
    109             mWarningIconView.setVisibility(View.VISIBLE);
    110             updateIconState();
    111             queueAnimateMessage();
    112         }
    113 
    114         /** Stop the warning icon animation. */
    115         void stopIconAnimation() {
    116             // Increment the counter so the handler will ignore the next message.
    117             mCount.incrementAndGet();
    118             if (mWarningIconView != null) {
    119                 mWarningIconView.setVisibility(View.GONE);
    120             }
    121         }
    122 
    123         /** Update the visibility of the warning icon. */
    124         private void updateIconState() {
    125             mWarningIconView.setImageAlpha(mWarningIconVisible ? 255 : 0);
    126             mWarningIconView.invalidateDrawable(mWarningIcon);
    127         }
    128 
    129         /** Queue a message to animate the warning icon. */
    130         private void queueAnimateMessage() {
    131             int msgWhat = mCount.incrementAndGet();
    132             sendEmptyMessageDelayed(msgWhat, mWarningIconVisible ? WARNING_ICON_ON_DURATION_MSEC
    133                     : WARNING_ICON_OFF_DURATION_MSEC);
    134         }
    135 
    136         @Override
    137         public void handleMessage(Message msg) {
    138             if (msg.what == mCount.get()) {
    139                 mWarningIconVisible = !mWarningIconVisible;
    140                 updateIconState();
    141                 queueAnimateMessage();
    142             }
    143         }
    144 
    145         /**
    146          * Initialize the Drawable and ImageView fields.
    147          * @return true if successful; false if any field failed to initialize
    148          */
    149         private boolean initDrawableAndImageView() {
    150             if (mWarningIcon == null) {
    151                 try {
    152                     mWarningIcon = getResources().getDrawable(R.drawable.ic_warning_googred);
    153                 } catch (Resources.NotFoundException e) {
    154                     Log.e(TAG, "warning icon resource not found", e);
    155                     return false;
    156                 }
    157             }
    158             if (mWarningIconView == null) {
    159                 mWarningIconView = (ImageView) findViewById(R.id.icon);
    160                 if (mWarningIconView != null) {
    161                     mWarningIconView.setImageDrawable(mWarningIcon);
    162                 } else {
    163                     Log.e(TAG, "failed to get ImageView for warning icon");
    164                     return false;
    165                 }
    166             }
    167             return true;
    168         }
    169     }
    170 
    171     /**
    172      * Handler to add {@code FLAG_KEEP_SCREEN_ON} for emergency alerts. After a short delay,
    173      * remove the flag so the screen can turn off to conserve the battery.
    174      */
    175     private class ScreenOffHandler extends Handler {
    176         /** Latest {@code message.what} value for detecting old messages. */
    177         private final AtomicInteger mCount = new AtomicInteger();
    178 
    179         /** Package local constructor (called from outer class). */
    180         ScreenOffHandler() {}
    181 
    182         /** Add screen on window flags and queue a delayed message to remove them later. */
    183         void startScreenOnTimer() {
    184             addWindowFlags();
    185             int msgWhat = mCount.incrementAndGet();
    186             removeMessages(msgWhat - 1);    // Remove previous message, if any.
    187             sendEmptyMessageDelayed(msgWhat, KEEP_SCREEN_ON_DURATION_MSEC);
    188             Log.d(TAG, "added FLAG_KEEP_SCREEN_ON, queued screen off message id " + msgWhat);
    189         }
    190 
    191         /** Remove the screen on window flags and any queued screen off message. */
    192         void stopScreenOnTimer() {
    193             removeMessages(mCount.get());
    194             clearWindowFlags();
    195         }
    196 
    197         /** Set the screen on window flags. */
    198         private void addWindowFlags() {
    199             getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
    200                     | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    201         }
    202 
    203         /** Clear the screen on window flags. */
    204         private void clearWindowFlags() {
    205             getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
    206                     | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
    207         }
    208 
    209         @Override
    210         public void handleMessage(Message msg) {
    211             int msgWhat = msg.what;
    212             if (msgWhat == mCount.get()) {
    213                 clearWindowFlags();
    214                 Log.d(TAG, "removed FLAG_KEEP_SCREEN_ON with id " + msgWhat);
    215             } else {
    216                 Log.e(TAG, "discarding screen off message with id " + msgWhat);
    217             }
    218         }
    219     }
    220 
    221     @Override
    222     protected void onCreate(Bundle savedInstanceState) {
    223         super.onCreate(savedInstanceState);
    224 
    225         final Window win = getWindow();
    226 
    227         // We use a custom title, so remove the standard dialog title bar
    228         win.requestFeature(Window.FEATURE_NO_TITLE);
    229 
    230         // Full screen alerts display above the keyguard and when device is locked.
    231         win.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
    232                 | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
    233                 | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
    234 
    235         setFinishOnTouchOutside(false);
    236 
    237         // Initialize the view.
    238         LayoutInflater inflater = LayoutInflater.from(this);
    239         setContentView(inflater.inflate(R.layout.cell_broadcast_alert, null));
    240 
    241         findViewById(R.id.dismissButton).setOnClickListener(
    242                 new Button.OnClickListener() {
    243                     @Override
    244                     public void onClick(View v) {
    245                         dismiss();
    246                     }
    247                 });
    248 
    249         // Get message list from saved Bundle or from Intent.
    250         if (savedInstanceState != null) {
    251             Log.d(TAG, "onCreate getting message list from saved instance state");
    252             mMessageList = savedInstanceState.getParcelableArrayList(
    253                     CellBroadcastMessage.SMS_CB_MESSAGE_EXTRA);
    254         } else {
    255             Log.d(TAG, "onCreate getting message list from intent");
    256             Intent intent = getIntent();
    257             mMessageList = intent.getParcelableArrayListExtra(
    258                     CellBroadcastMessage.SMS_CB_MESSAGE_EXTRA);
    259 
    260             // If we were started from a notification, dismiss it.
    261             clearNotification(intent);
    262         }
    263 
    264         if (mMessageList == null || mMessageList.size() == 0) {
    265             Log.e(TAG, "onCreate failed as message list is null or empty");
    266             finish();
    267         } else {
    268             Log.d(TAG, "onCreate loaded message list of size " + mMessageList.size());
    269         }
    270 
    271         // For emergency alerts, keep screen on so the user can read it
    272         CellBroadcastMessage message = getLatestMessage();
    273         if (message != null && CellBroadcastChannelManager.isEmergencyMessage(
    274                 this, message)) {
    275             Log.d(TAG, "onCreate setting screen on timer for emergency alert");
    276             mScreenOffHandler.startScreenOnTimer();
    277         }
    278 
    279         updateAlertText(message);
    280     }
    281 
    282     /**
    283      * Start animating warning icon.
    284      */
    285     @Override
    286     protected void onResume() {
    287         super.onResume();
    288         CellBroadcastMessage message = getLatestMessage();
    289         if (message != null && CellBroadcastChannelManager.isEmergencyMessage(this, message)) {
    290             mAnimationHandler.startIconAnimation();
    291         }
    292     }
    293 
    294     /**
    295      * Stop animating warning icon.
    296      */
    297     @Override
    298     protected void onPause() {
    299         Log.d(TAG, "onPause called");
    300         mAnimationHandler.stopIconAnimation();
    301         super.onPause();
    302     }
    303 
    304     @Override
    305     protected void onStop() {
    306         super.onStop();
    307         // When the activity goes in background eg. clicking Home button, send notification.
    308         // Avoid doing this when activity will be recreated because of orientation change or if
    309         // screen goes off
    310         PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
    311         if (!(isChangingConfigurations() || getLatestMessage() == null) && pm.isScreenOn()) {
    312             CellBroadcastAlertService.addToNotificationBar(getLatestMessage(), mMessageList,
    313                     getApplicationContext(), true);
    314         }
    315     }
    316 
    317     /** Returns the currently displayed message. */
    318     CellBroadcastMessage getLatestMessage() {
    319         int index = mMessageList.size() - 1;
    320         if (index >= 0) {
    321             return mMessageList.get(index);
    322         } else {
    323             Log.d(TAG, "getLatestMessage returns null");
    324             return null;
    325         }
    326     }
    327 
    328     /** Removes and returns the currently displayed message. */
    329     private CellBroadcastMessage removeLatestMessage() {
    330         int index = mMessageList.size() - 1;
    331         if (index >= 0) {
    332             return mMessageList.remove(index);
    333         } else {
    334             return null;
    335         }
    336     }
    337 
    338     /**
    339      * Save the list of messages so the state can be restored later.
    340      * @param outState Bundle in which to place the saved state.
    341      */
    342     @Override
    343     protected void onSaveInstanceState(Bundle outState) {
    344         super.onSaveInstanceState(outState);
    345         outState.putParcelableArrayList(CellBroadcastMessage.SMS_CB_MESSAGE_EXTRA, mMessageList);
    346     }
    347 
    348     /**
    349      * Update alert text when a new emergency alert arrives.
    350      * @param message CB message which is used to update alert text.
    351      */
    352     private void updateAlertText(CellBroadcastMessage message) {
    353         int titleId = CellBroadcastResources.getDialogTitleResource(
    354                 getApplicationContext(), message);
    355 
    356         String title = getText(titleId).toString();
    357         TextView titleTextView = findViewById(R.id.alertTitle);
    358 
    359         if (getApplicationContext().getResources().getBoolean(R.bool.show_date_time_title)) {
    360             titleTextView.setSingleLine(false);
    361             title += "\n" + message.getDateString(getApplicationContext());
    362         }
    363 
    364         setTitle(title);
    365         titleTextView.setText(title);
    366 
    367         ((TextView) findViewById(R.id.message)).setText(message.getMessageBody());
    368 
    369         String dismissButtonText = getString(R.string.button_dismiss);
    370 
    371         if (mMessageList.size() > 1) {
    372             dismissButtonText += "  (1/" + mMessageList.size() + ")";
    373         }
    374 
    375         ((TextView) findViewById(R.id.dismissButton)).setText(dismissButtonText);
    376     }
    377 
    378     /**
    379      * Called by {@link CellBroadcastAlertService} to add a new alert to the stack.
    380      * @param intent The new intent containing one or more {@link CellBroadcastMessage}s.
    381      */
    382     @Override
    383     protected void onNewIntent(Intent intent) {
    384         ArrayList<CellBroadcastMessage> newMessageList = intent.getParcelableArrayListExtra(
    385                 CellBroadcastMessage.SMS_CB_MESSAGE_EXTRA);
    386         if (newMessageList != null) {
    387             if (intent.getBooleanExtra(FROM_SAVE_STATE_NOTIFICATION_EXTRA, false)) {
    388                 mMessageList = newMessageList;
    389             } else {
    390                 mMessageList.addAll(newMessageList);
    391             }
    392             Log.d(TAG, "onNewIntent called with message list of size " + newMessageList.size());
    393             updateAlertText(getLatestMessage());
    394             // If the new intent was sent from a notification, dismiss it.
    395             clearNotification(intent);
    396         } else {
    397             Log.e(TAG, "onNewIntent called without SMS_CB_MESSAGE_EXTRA, ignoring");
    398         }
    399     }
    400 
    401     /**
    402      * Try to cancel any notification that may have started this activity.
    403      * @param intent Intent containing extras used to identify if notification needs to be cleared
    404      */
    405     private void clearNotification(Intent intent) {
    406         if (intent.getBooleanExtra(FROM_NOTIFICATION_EXTRA, false)) {
    407             NotificationManager notificationManager =
    408                     (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    409             notificationManager.cancel(CellBroadcastAlertService.NOTIFICATION_ID);
    410             CellBroadcastReceiverApp.clearNewMessageList();
    411         }
    412     }
    413 
    414     /**
    415      * Stop animating warning icon and stop the {@link CellBroadcastAlertAudio}
    416      * service if necessary.
    417      */
    418     void dismiss() {
    419         Log.d(TAG, "dismiss");
    420         // Stop playing alert sound/vibration/speech (if started)
    421         stopService(new Intent(this, CellBroadcastAlertAudio.class));
    422 
    423         // Cancel any pending alert reminder
    424         CellBroadcastAlertReminder.cancelAlertReminder();
    425 
    426         // Remove the current alert message from the list.
    427         CellBroadcastMessage lastMessage = removeLatestMessage();
    428         if (lastMessage == null) {
    429             Log.e(TAG, "dismiss() called with empty message list!");
    430             finish();
    431             return;
    432         }
    433 
    434         // Mark the alert as read.
    435         final long deliveryTime = lastMessage.getDeliveryTime();
    436 
    437         // Mark broadcast as read on a background thread.
    438         new CellBroadcastContentProvider.AsyncCellBroadcastTask(getContentResolver())
    439                 .execute(new CellBroadcastContentProvider.CellBroadcastOperation() {
    440                     @Override
    441                     public boolean execute(CellBroadcastContentProvider provider) {
    442                         return provider.markBroadcastRead(
    443                                 Telephony.CellBroadcasts.DELIVERY_TIME, deliveryTime);
    444                     }
    445                 });
    446 
    447         // Set the opt-out dialog flag if this is a CMAS alert (other than Presidential Alert).
    448         if (lastMessage.isCmasMessage() && lastMessage.getCmasMessageClass() !=
    449                 SmsCbCmasInfo.CMAS_CLASS_PRESIDENTIAL_LEVEL_ALERT) {
    450             mShowOptOutDialog = true;
    451         }
    452 
    453         // If there are older emergency alerts to display, update the alert text and return.
    454         CellBroadcastMessage nextMessage = getLatestMessage();
    455         if (nextMessage != null) {
    456             updateAlertText(nextMessage);
    457             if (CellBroadcastChannelManager.isEmergencyMessage(
    458                     this, nextMessage)) {
    459                 mAnimationHandler.startIconAnimation();
    460             } else {
    461                 mAnimationHandler.stopIconAnimation();
    462             }
    463             return;
    464         }
    465 
    466         // Remove pending screen-off messages (animation messages are removed in onPause()).
    467         mScreenOffHandler.stopScreenOnTimer();
    468 
    469         // Show opt-in/opt-out dialog when the first CMAS alert is received.
    470         if (mShowOptOutDialog) {
    471             SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    472             if (prefs.getBoolean(CellBroadcastSettings.KEY_SHOW_CMAS_OPT_OUT_DIALOG, true)) {
    473                 // Clear the flag so the user will only see the opt-out dialog once.
    474                 prefs.edit().putBoolean(CellBroadcastSettings.KEY_SHOW_CMAS_OPT_OUT_DIALOG, false)
    475                         .apply();
    476 
    477                 KeyguardManager km = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);
    478                 if (km.inKeyguardRestrictedInputMode()) {
    479                     Log.d(TAG, "Showing opt-out dialog in new activity (secure keyguard)");
    480                     Intent intent = new Intent(this, CellBroadcastOptOutActivity.class);
    481                     startActivity(intent);
    482                 } else {
    483                     Log.d(TAG, "Showing opt-out dialog in current activity");
    484                     CellBroadcastOptOutActivity.showOptOutDialog(this);
    485                     return; // don't call finish() until user dismisses the dialog
    486                 }
    487             }
    488         }
    489         NotificationManager notificationManager =
    490                 (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    491         notificationManager.cancel(CellBroadcastAlertService.NOTIFICATION_ID);
    492         finish();
    493     }
    494 
    495     @Override
    496     public boolean dispatchKeyEvent(KeyEvent event) {
    497         CellBroadcastMessage message = getLatestMessage();
    498         if (message != null && !message.isEtwsMessage()) {
    499             switch (event.getKeyCode()) {
    500                 // Volume keys and camera keys mute the alert sound/vibration (except ETWS).
    501                 case KeyEvent.KEYCODE_VOLUME_UP:
    502                 case KeyEvent.KEYCODE_VOLUME_DOWN:
    503                 case KeyEvent.KEYCODE_VOLUME_MUTE:
    504                 case KeyEvent.KEYCODE_CAMERA:
    505                 case KeyEvent.KEYCODE_FOCUS:
    506                     // Stop playing alert sound/vibration/speech (if started)
    507                     stopService(new Intent(this, CellBroadcastAlertAudio.class));
    508                     return true;
    509 
    510                 default:
    511                     break;
    512             }
    513         }
    514         return super.dispatchKeyEvent(event);
    515     }
    516 
    517     @Override
    518     public void onBackPressed() {
    519         // Disable back key
    520     }
    521 }
    522