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 package androidx.work.impl.constraints.trackers 17 18 import android.content.BroadcastReceiver 19 import android.content.Context 20 import android.content.Intent 21 import android.content.IntentFilter 22 import androidx.annotation.RestrictTo 23 import androidx.work.Logger 24 import androidx.work.impl.utils.taskexecutor.TaskExecutor 25 26 /** 27 * A [ConstraintTracker] with a [BroadcastReceiver] for monitoring constraint changes. 28 * 29 * @param T the constraint data type observed by this tracker 30 */ 31 @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP) 32 abstract class BroadcastReceiverConstraintTracker<T>(context: Context, taskExecutor: TaskExecutor) : 33 ConstraintTracker<T>(context, taskExecutor) { 34 private val broadcastReceiver: BroadcastReceiver = 35 object : BroadcastReceiver() { onReceivenull36 override fun onReceive(context: Context, intent: Intent) { 37 onBroadcastReceive(intent) 38 } 39 } 40 41 /** 42 * Called when the [BroadcastReceiver] is receiving an [Intent] broadcast and should handle the 43 * received [Intent]. 44 * 45 * @param intent The [Intent] being received. 46 */ onBroadcastReceivenull47 abstract fun onBroadcastReceive(intent: Intent) 48 49 /** @return The [IntentFilter] associated with this tracker. */ 50 abstract val intentFilter: IntentFilter 51 52 override fun startTracking() { 53 Logger.get().debug(TAG, "${javaClass.simpleName}: registering receiver") 54 appContext.registerReceiver(broadcastReceiver, intentFilter) 55 } 56 stopTrackingnull57 override fun stopTracking() { 58 Logger.get().debug(TAG, "${javaClass.simpleName}: unregistering receiver") 59 appContext.unregisterReceiver(broadcastReceiver) 60 } 61 } 62 63 private val TAG = Logger.tagWithPrefix("BrdcstRcvrCnstrntTrckr") 64