1 /*
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 
17 package com.android.car;
18 
19 import android.content.BroadcastReceiver;
20 import android.content.Context;
21 import android.content.Intent;
22 import android.content.IntentFilter;
23 
24 import java.util.concurrent.CopyOnWriteArrayList;
25 import 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  */
37 class 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 
OnShutdownReboot(Context context)54     OnShutdownReboot(Context context) {
55         mContext = context;
56         IntentFilter filter = new IntentFilter();
57         filter.addAction(Intent.ACTION_SHUTDOWN);
58         filter.addAction(Intent.ACTION_REBOOT);
59         mContext.registerReceiver(mReceiver, filter);
60     }
61 
addAction(BiConsumer<Context, Intent> action)62     OnShutdownReboot addAction(BiConsumer<Context, Intent> action) {
63         mActions.add(action);
64         return this;
65     }
66 
clearActions()67     void clearActions() {
68         mActions.clear();
69     }
70 }
71