summaryrefslogtreecommitdiff
path: root/src/com/android/emergency/action/service/EmergencyActionForegroundService.java
blob: dac8550e2b7cf0b1b1eeefa230e229542ecba6b1 (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
/*
 * Copyright (C) 2020 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.emergency.action.service;

import static android.app.NotificationManager.IMPORTANCE_HIGH;

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.telecom.TelecomManager;
import android.util.Log;
import android.widget.RemoteViews;

import com.android.emergency.R;
import com.android.emergency.action.broadcast.EmergencyActionBroadcastReceiver;
import com.android.settingslib.emergencynumber.EmergencyNumberUtils;

/**
 * A service that counts down for emergency gesture.
 */
public class EmergencyActionForegroundService extends Service {
    private static final String TAG = "EmergencyActionSvc";
    /** The notification that current service should be started with. */
    private static final String SERVICE_EXTRA_NOTIFICATION = "service.extra.notification";
    /** The remaining time in milliseconds before taking emergency action */
    private static final String SERVICE_EXTRA_REMAINING_TIME_MS = "service.extra.remaining_time_ms";
    /** Random unique number for the notification */
    private static final int COUNT_DOWN_NOTIFICATION_ID = 0x112;

    private TelecomManager mTelecomManager;
    private Vibrator mVibrator;
    private EmergencyNumberUtils mEmergencyNumberUtils;
    private NotificationManager mNotificationManager;


    @Override
    public void onCreate() {
        super.onCreate();
        PackageManager pm = getPackageManager();
        mVibrator = getSystemService(Vibrator.class);
        if (pm.hasSystemFeature(PackageManager.FEATURE_TELEPHONY)) {
            mTelecomManager = getSystemService(TelecomManager.class);
            mEmergencyNumberUtils = new EmergencyNumberUtils(this);
        }
        mNotificationManager = getSystemService(NotificationManager.class);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "Service started");
        if (mTelecomManager == null || mEmergencyNumberUtils == null) {
            Log.d(TAG, "Device does not have telephony support, nothing to do");
            stopSelf();
            return START_NOT_STICKY;
        }
        long remainingTimeMs = intent.getLongExtra(SERVICE_EXTRA_REMAINING_TIME_MS, -1);
        if (remainingTimeMs <= 0) {
            Log.d(TAG, "Invalid remaining countdown time, nothing to do");
            stopSelf();
            return START_NOT_STICKY;
        }
        mNotificationManager.createNotificationChannel(buildNotificationChannel(this));
        Notification notification = intent.getParcelableExtra(SERVICE_EXTRA_NOTIFICATION);

        // Immediately show notification And now put the service in foreground mode
        startForeground(COUNT_DOWN_NOTIFICATION_ID, notification);
        scheduleEmergencyCallBroadcast(remainingTimeMs);
        // vibration
        // TODO(b/175401642): Use correct vibrate pattern
        mVibrator.vibrate(
                VibrationEffect.get(VibrationEffect.EFFECT_HEAVY_CLICK));
        // TODO(b/172075832): sound

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        // Take notification down
        mNotificationManager.cancel(COUNT_DOWN_NOTIFICATION_ID);
        // TODO(b/172075832): Stop sound
        // Stop vibrate
        mVibrator.cancel();
        super.onDestroy();
    }

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

    /**
     * Build {@link Intent} that launches foreground service for emergency gesture's countdown
     * action
     */
    public static Intent newStartCountdownIntent(
            Context context, long remainingTimeMs) {
        return new Intent(context, EmergencyActionForegroundService.class)
                .putExtra(SERVICE_EXTRA_REMAINING_TIME_MS, remainingTimeMs)
                .putExtra(SERVICE_EXTRA_NOTIFICATION,
                        buildCountDownNotification(context, remainingTimeMs));
    }

    /** End all work in this service and remove the foreground notification. */
    public static void stopService(Context context) {
        context.stopService(new Intent(context, EmergencyActionForegroundService.class));
    }

    /**
     * Creates a {@link NotificationChannel} object for emergency action notifications.
     *
     * <p/> Note this does not create notification channel in the system.
     */
    private static NotificationChannel buildNotificationChannel(Context context) {
        NotificationChannel channel = new NotificationChannel("EmergencyGesture",
                context.getString(R.string.emergency_action_title), IMPORTANCE_HIGH);
        return channel;
    }

    private static Notification buildCountDownNotification(Context context, long remainingTimeMs) {
        NotificationChannel channel = buildNotificationChannel(context);
        EmergencyNumberUtils emergencyNumberUtils = new EmergencyNumberUtils(context);
        long targetTimeMs = SystemClock.elapsedRealtime() + remainingTimeMs;
        // TODO(b/172075832): Make UI prettier
        RemoteViews contentView =
                new RemoteViews(context.getPackageName(),
                        R.layout.emergency_action_count_down_notification);
        contentView.setTextViewText(R.id.notification_text,
                context.getString(R.string.emergency_action_subtitle,
                        emergencyNumberUtils.getPoliceNumber()));
        contentView.setChronometerCountDown(R.id.chronometer, true);
        contentView.setChronometer(
                R.id.chronometer,
                targetTimeMs,
                /* format= */ null,
                /* started= */ true);
        return new Notification.Builder(context, channel.getId())
                .setSmallIcon(R.drawable.ic_launcher_settings)
                .setStyle(new Notification.DecoratedCustomViewStyle())
                .setAutoCancel(false)
                .setOngoing(true)
                // This is set to make sure that device doesn't vibrate twice when client
                // attempts to post currently displayed notification again
                .setOnlyAlertOnce(true)
                .setCategory(Notification.CATEGORY_ALARM)
                .setCustomContentView(contentView)
                .addAction(new Notification.Action.Builder(null, context.getText(R.string.cancel),
                        EmergencyActionBroadcastReceiver.newCancelCountdownPendingIntent(
                                context)).build())
                .build();
    }

    private void scheduleEmergencyCallBroadcast(long remainingTimeMs) {
        long alarmTimeMs = System.currentTimeMillis() + remainingTimeMs;
        AlarmManager alarmManager = getSystemService(AlarmManager.class);
        alarmManager.setExactAndAllowWhileIdle(
                AlarmManager.RTC_WAKEUP, alarmTimeMs,
                EmergencyActionBroadcastReceiver.newCallEmergencyPendingIntent(this));
    }

}