1 /* 2 * Copyright (C) 2022 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.settings.wifi.helper; 18 19 import android.os.Handler; 20 import android.os.HandlerThread; 21 import android.os.Process; 22 import android.os.SimpleClock; 23 import android.os.SystemClock; 24 25 import androidx.annotation.NonNull; 26 import androidx.annotation.VisibleForTesting; 27 import androidx.lifecycle.DefaultLifecycleObserver; 28 import androidx.lifecycle.Lifecycle; 29 import androidx.lifecycle.LifecycleOwner; 30 31 import java.time.Clock; 32 import java.time.ZoneOffset; 33 34 /** 35 * Base class for the WifiTrackerLib related classes. 36 */ 37 public class WifiTrackerBase implements DefaultLifecycleObserver { 38 private static final String TAG = "WifiTrackerBase"; 39 40 // Max age of tracked WifiEntries 41 protected static final long MAX_SCAN_AGE_MILLIS = 15_000; 42 // Interval between initiating Wi-Fi Tracker scans 43 protected static final long SCAN_INTERVAL_MILLIS = 10_000; 44 // Clock used for evaluating the age of scans 45 protected static final Clock ELAPSED_REALTIME_CLOCK = new SimpleClock(ZoneOffset.UTC) { 46 @Override 47 public long millis() { 48 return SystemClock.elapsedRealtime(); 49 } 50 }; 51 52 @VisibleForTesting 53 protected HandlerThread mWorkerThread; 54 WifiTrackerBase(@onNull Lifecycle lifecycle)55 public WifiTrackerBase(@NonNull Lifecycle lifecycle) { 56 this(lifecycle, null /* handlerThread */); 57 } 58 59 @VisibleForTesting WifiTrackerBase(@onNull Lifecycle lifecycle, HandlerThread handlerThread)60 protected WifiTrackerBase(@NonNull Lifecycle lifecycle, HandlerThread handlerThread) { 61 lifecycle.addObserver(this); 62 mWorkerThread = (handlerThread != null) ? handlerThread : 63 new HandlerThread(getTag() 64 + "{" + Integer.toHexString(System.identityHashCode(this)) + "}", 65 Process.THREAD_PRIORITY_BACKGROUND); 66 mWorkerThread.start(); 67 } 68 getTag()69 protected String getTag() { 70 return TAG; 71 } 72 73 @Override onDestroy(@onNull LifecycleOwner owner)74 public void onDestroy(@NonNull LifecycleOwner owner) { 75 mWorkerThread.quit(); 76 } 77 78 /** Returns the worker thread handler. */ getWorkerThreadHandler()79 public Handler getWorkerThreadHandler() { 80 return mWorkerThread.getThreadHandler(); 81 } 82 } 83