1 /* 2 * Copyright (C) 2016 The Android Open Source Project 3 * Copyright (C) 2016 Mopria Alliance, Inc. 4 * 5 * Licensed under the Apache License, Version 2.0 (the "License"); 6 * you may not use this file except in compliance with the License. 7 * You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software 12 * distributed under the License is distributed on an "AS IS" BASIS, 13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 * See the License for the specific language governing permissions and 15 * limitations under the License. 16 */ 17 18 package com.android.bips.discovery; 19 20 import android.util.Log; 21 22 import com.android.bips.BuiltInPrintService; 23 import com.android.bips.util.WifiMonitor; 24 25 import java.util.ArrayList; 26 import java.util.Arrays; 27 import java.util.List; 28 29 /** Combines the behavior of multiple child {@link Discovery} objects to a single one */ 30 public class MultiDiscovery extends Discovery { 31 private static final String TAG = MultiDiscovery.class.getSimpleName(); 32 private static final boolean DEBUG = false; 33 34 private final List<Discovery> mDiscoveries = new ArrayList<>(); 35 private final Listener mChildListener; 36 private final WifiMonitor.Factory mWifiMonitorFactory; 37 private WifiMonitor mWifiMonitor; 38 MultiDiscovery(BuiltInPrintService printService, WifiMonitor.Factory wifiMonitorFactory, Discovery... discoveries)39 public MultiDiscovery(BuiltInPrintService printService, WifiMonitor.Factory wifiMonitorFactory, 40 Discovery... discoveries) { 41 super(printService); 42 mDiscoveries.addAll(Arrays.asList(discoveries)); 43 mWifiMonitorFactory = wifiMonitorFactory; 44 mChildListener = new Listener() { 45 @Override 46 public void onPrinterFound(DiscoveredPrinter printer) { 47 DiscoveredPrinter oldPrinter = getPrinter(printer.getUri()); 48 if (oldPrinter != null) { 49 printer = printer.bestOf(oldPrinter); 50 } 51 52 MultiDiscovery.this.printerFound(printer); 53 } 54 55 @Override 56 public void onPrinterLost(DiscoveredPrinter printer) { 57 MultiDiscovery.this.printerLost(printer.getUri()); 58 } 59 }; 60 } 61 62 @Override onStart()63 void onStart() { 64 if (DEBUG) Log.d(TAG, "onStart()"); 65 mWifiMonitor = mWifiMonitorFactory.create(getPrintService(), connected -> { 66 if (connected) { 67 if (DEBUG) Log.d(TAG, "Connected, starting discovery"); 68 for (Discovery discovery : mDiscoveries) { 69 discovery.start(mChildListener); 70 } 71 } else { 72 if (DEBUG) Log.d(TAG, "Disconnected, stopping discovery"); 73 for (Discovery discovery : mDiscoveries) { 74 discovery.stop(mChildListener); 75 } 76 allPrintersLost(); 77 } 78 }); 79 } 80 81 @Override onStop()82 void onStop() { 83 if (DEBUG) Log.d(TAG, "onStop()"); 84 mWifiMonitor.close(); 85 for (Discovery discovery : mDiscoveries) { 86 discovery.stop(mChildListener); 87 } 88 allPrintersLost(); 89 } 90 }