1 /* 2 * Copyright (C) 2018 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.packageinstaller.permission.utils; 18 19 import android.content.BroadcastReceiver; 20 import android.content.Context; 21 import android.content.Intent; 22 import android.content.IntentFilter; 23 24 import androidx.annotation.NonNull; 25 26 /** 27 * Monitors the state of a package (esp. if it gets uninstalled) 28 */ 29 public abstract class PackageRemovalMonitor extends BroadcastReceiver { 30 private final @NonNull Context mContext; 31 private final @NonNull String mPackageName; 32 PackageRemovalMonitor(@onNull Context context, @NonNull String packageName)33 public PackageRemovalMonitor(@NonNull Context context, @NonNull String packageName) { 34 mContext = context; 35 mPackageName = packageName; 36 } 37 onPackageRemoved()38 protected abstract void onPackageRemoved(); 39 40 @Override onReceive(Context context, Intent intent)41 public void onReceive(Context context, Intent intent) { 42 if (Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction()) 43 && mPackageName.equals(intent.getData().getSchemeSpecificPart())) { 44 onPackageRemoved(); 45 } 46 } 47 48 /** 49 * Enable monitoring 50 */ register()51 public void register() { 52 IntentFilter packageRemovedFilter = new IntentFilter(); 53 packageRemovedFilter.addAction(Intent.ACTION_PACKAGE_REMOVED); 54 packageRemovedFilter.addDataScheme("package"); 55 56 mContext.registerReceiver(this, packageRemovedFilter); 57 } 58 59 /** 60 * Disable monitoring 61 */ unregister()62 public void unregister() { 63 mContext.unregisterReceiver(this); 64 } 65 } 66