1 /*
2  * Copyright 2023 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 android.media.cts;
17 
18 import android.content.ComponentName;
19 import android.content.Context;
20 import android.content.Intent;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.os.Messenger;
24 import android.util.Log;
25 
26 /**
27  * Helper class to interact with the {@link LocalMediaProjectionService}.
28  */
29 public final class ForegroundServiceUtil {
30     private static final String TAG = "LocalMediaProjectionServiceUtil";
31 
32     static final int MSG_START_FOREGROUND_DONE = 1;
33     static final int MSG_SERVICE_DESTROYED = 2;
34     static final String EXTRA_MESSENGER = "messenger";
35 
36 
37     /**
38      * Helper function to request to start the foreground service.
39      */
requestStartForegroundService(Context context, ComponentName name, Runnable serviceStarted, Runnable serviceStopped)40     public static void requestStartForegroundService(Context context, ComponentName name,
41             Runnable serviceStarted, Runnable serviceStopped) {
42         final Messenger messenger = new Messenger(new Handler(Looper.getMainLooper(), msg -> {
43             switch (msg.what) {
44                 case MSG_START_FOREGROUND_DONE:
45                     if (serviceStarted != null) {
46                         serviceStarted.run();
47                     }
48                     return true;
49                 case MSG_SERVICE_DESTROYED:
50                     if (serviceStopped != null) {
51                         serviceStopped.run();
52                     }
53                     return true;
54             }
55             Log.e(TAG, "Unknown message from the LocalMediaProjectionService: " + msg.what);
56             return false;
57         }));
58         final Intent intent = new Intent().setComponent(name)
59                 .putExtra(EXTRA_MESSENGER, messenger);
60         context.startForegroundService(intent);
61     }
62 }
63