1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5 * except in compliance with the License. You may obtain a copy of the License at
6 *
7 *      http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software distributed under the
10 * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11 * KIND, either express or implied. See the License for the specific language governing
12 * permissions and limitations under the License.
13 */
14
15package com.android.settings.applications;
16
17import android.content.Context;
18import android.content.pm.ApplicationInfo;
19import android.content.pm.PackageManager;
20import android.content.pm.UserInfo;
21import android.os.AsyncTask;
22import android.os.UserHandle;
23import android.os.UserManager;
24
25import com.android.settingslib.wrapper.PackageManagerWrapper;
26
27import java.util.List;
28
29public abstract class AppCounter extends AsyncTask<Void, Void, Integer> {
30
31    protected final PackageManagerWrapper mPm;
32    protected final UserManager mUm;
33
34    public AppCounter(Context context, PackageManagerWrapper packageManager) {
35        mPm = packageManager;
36        mUm = (UserManager) context.getSystemService(Context.USER_SERVICE);
37    }
38
39    @Override
40    protected Integer doInBackground(Void... params) {
41        int count = 0;
42        for (UserInfo user : mUm.getProfiles(UserHandle.myUserId())) {
43            final List<ApplicationInfo> list =
44                    mPm.getInstalledApplicationsAsUser(PackageManager.GET_DISABLED_COMPONENTS
45                            | PackageManager.GET_DISABLED_UNTIL_USED_COMPONENTS
46                            | (user.isAdmin() ? PackageManager.MATCH_ANY_USER : 0),
47                            user.id);
48            for (ApplicationInfo info : list) {
49                if (includeInCount(info)) {
50                    count++;
51                }
52            }
53        }
54        return count;
55    }
56
57    @Override
58    protected void onPostExecute(Integer count) {
59        onCountComplete(count);
60    }
61
62    void executeInForeground() {
63        onPostExecute(doInBackground());
64    }
65
66    protected abstract void onCountComplete(int num);
67    protected abstract boolean includeInCount(ApplicationInfo info);
68}
69