blob: 5a14371b9cb94c225a984e0f03870955775f055d [file] [log] [blame]
Enrico Granata9a916d72017-09-19 14:33:08 -07001/*
2 * Copyright (C) 2017 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
17package com.android.car;
18
19import android.content.BroadcastReceiver;
20import android.content.Context;
21import android.content.Intent;
22import android.content.IntentFilter;
Keun young Parked6ef412019-11-14 18:27:45 -080023
Enrico Granata9a916d72017-09-19 14:33:08 -070024import java.util.concurrent.CopyOnWriteArrayList;
25import java.util.function.BiConsumer;
26
27/**
28 * This class allows one to register actions they want executed when the vehicle is being shutdown
29 * or rebooted.
30 *
31 * To use this class instantiate it as part of your long-lived service, and then add actions to it.
32 * Actions receive the Context and Intent that go with the shutdown/reboot action, which allows the
33 * action to differentiate the two cases, should it need to do so.
34 *
35 * The actions will run on the UI thread.
36 */
37class OnShutdownReboot {
38 private final Object mLock = new Object();
39
40 private final Context mContext;
41
42 private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
43 @Override
44 public void onReceive(Context context, Intent intent) {
45 for (BiConsumer<Context, Intent> action : mActions) {
46 action.accept(context, intent);
47 }
48 }
49 };
50
51 private final CopyOnWriteArrayList<BiConsumer<Context, Intent>> mActions =
52 new CopyOnWriteArrayList<>();
53
54 OnShutdownReboot(Context context) {
55 mContext = context;
Keun young Parked6ef412019-11-14 18:27:45 -080056 IntentFilter filter = new IntentFilter();
57 filter.addAction(Intent.ACTION_SHUTDOWN);
58 filter.addAction(Intent.ACTION_REBOOT);
59 mContext.registerReceiver(mReceiver, filter);
Enrico Granata9a916d72017-09-19 14:33:08 -070060 }
61
Enrico Granata1690a622018-01-22 17:34:46 -080062 OnShutdownReboot addAction(BiConsumer<Context, Intent> action) {
Enrico Granata9a916d72017-09-19 14:33:08 -070063 mActions.add(action);
Enrico Granata1690a622018-01-22 17:34:46 -080064 return this;
Enrico Granata9a916d72017-09-19 14:33:08 -070065 }
66
67 void clearActions() {
68 mActions.clear();
69 }
70}