1 /* 2 * Copyright (C) 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 17 package com.android.deviceaswebcam; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.hardware.usb.UsbManager; 23 import android.os.Bundle; 24 import android.util.Log; 25 26 import com.android.deviceaswebcam.utils.IgnoredV4L2Nodes; 27 28 /** 29 * Base abstract class that receives USB broadcasts from system server and starts the webcam 30 * foreground service when needed. 31 */ 32 public abstract class DeviceAsWebcamReceiver extends BroadcastReceiver { 33 private static final String TAG = DeviceAsWebcamReceiver.class.getSimpleName(); 34 private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); 35 36 static { 37 System.loadLibrary("jni_deviceAsWebcam"); 38 } 39 40 @Override onReceive(Context context, Intent intent)41 public final void onReceive(Context context, Intent intent) { 42 final String action = intent.getAction(); 43 Bundle extras = intent.getExtras(); 44 if (extras == null) { 45 return; 46 } 47 boolean uvcSelected = extras.getBoolean(UsbManager.USB_FUNCTION_UVC); 48 if (VERBOSE) { 49 Log.v(TAG, "Got broadcast with extras" + extras); 50 } 51 if (!UsbManager.isUvcSupportEnabled()) { 52 Log.i(TAG, "UVC support isn't enabled. Returning early."); 53 return; 54 } 55 if (UsbManager.ACTION_USB_STATE.equals(action) && uvcSelected) { 56 String[] ignoredNodes = IgnoredV4L2Nodes.getIgnoredNodes(context); 57 if (!DeviceAsWebcamFgService.shouldStartServiceNative(ignoredNodes)) { 58 if (VERBOSE) { 59 Log.v(TAG, "Shouldn't start service so returning"); 60 } 61 return; 62 } 63 Class<? extends DeviceAsWebcamFgService> klass = getForegroundServiceClass(); 64 Intent fgIntent = new Intent(context, klass); 65 context.startForegroundService(fgIntent); 66 if (VERBOSE) { 67 Log.v(TAG, "started foreground service"); 68 } 69 } 70 } 71 72 /** 73 * Return the concrete class for the foreground service. 74 * 75 * @return class that has the concrete implementation of {@link DeviceAsWebcamFgService} 76 */ getForegroundServiceClass()77 protected abstract Class<? extends DeviceAsWebcamFgService> getForegroundServiceClass(); 78 } 79