blob: 1816c504dcaeddd683f5b4dd74e97035634f425d [file] [log] [blame]
Adam Lesinski468d3912014-07-22 10:01:08 -07001/*
2 * Copyright (C) 2014 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
17package com.android.settings;
18
19import com.android.internal.content.PackageMonitor;
20
21import android.Manifest;
22import android.app.ActivityThread;
Adam Lesinskie01dfd12014-08-11 20:54:12 -070023import android.app.AlertDialog;
Adam Lesinski468d3912014-07-22 10:01:08 -070024import android.app.AppOpsManager;
Adam Lesinskie01dfd12014-08-11 20:54:12 -070025import android.app.Dialog;
26import android.app.DialogFragment;
Adam Lesinski468d3912014-07-22 10:01:08 -070027import android.content.Context;
Adam Lesinskie01dfd12014-08-11 20:54:12 -070028import android.content.DialogInterface;
Adam Lesinski468d3912014-07-22 10:01:08 -070029import android.content.pm.IPackageManager;
30import android.content.pm.PackageInfo;
31import android.content.pm.PackageManager;
32import android.os.AsyncTask;
33import android.os.Bundle;
34import android.os.Looper;
35import android.os.RemoteException;
36import android.preference.Preference;
Adam Lesinskie01dfd12014-08-11 20:54:12 -070037import android.preference.PreferenceCategory;
Adam Lesinski468d3912014-07-22 10:01:08 -070038import android.preference.SwitchPreference;
39import android.util.ArrayMap;
40import android.util.Log;
41
42import java.util.List;
43
44public class UsageAccessSettings extends SettingsPreferenceFragment implements
45 Preference.OnPreferenceChangeListener {
46
47 private static final String TAG = "UsageAccessSettings";
48
49 private static final String[] PM_USAGE_STATS_PERMISSION = new String[] {
50 Manifest.permission.PACKAGE_USAGE_STATS
51 };
52
53 private static final int[] APP_OPS_OP_CODES = new int[] {
54 AppOpsManager.OP_GET_USAGE_STATS
55 };
56
57 private static class PackageEntry {
58 public PackageEntry(String packageName) {
59 this.packageName = packageName;
60 this.appOpMode = AppOpsManager.MODE_DEFAULT;
61 }
62
63 final String packageName;
64 PackageInfo packageInfo;
65 boolean permissionGranted;
66 int appOpMode;
67
68 SwitchPreference preference;
69 }
70
71 /**
72 * Fetches the list of Apps that are requesting access to the UsageStats API and updates
73 * the PreferenceScreen with the results when complete.
74 */
75 private class AppsRequestingAccessFetcher extends
76 AsyncTask<Void, Void, ArrayMap<String, PackageEntry>> {
77
78 private final Context mContext;
79 private final PackageManager mPackageManager;
80 private final IPackageManager mIPackageManager;
81
82 public AppsRequestingAccessFetcher(Context context) {
83 mContext = context;
84 mPackageManager = context.getPackageManager();
85 mIPackageManager = ActivityThread.getPackageManager();
86 }
87
88 @Override
89 protected ArrayMap<String, PackageEntry> doInBackground(Void... params) {
90 final String[] packages;
91 try {
92 packages = mIPackageManager.getAppOpPermissionPackages(
93 Manifest.permission.PACKAGE_USAGE_STATS);
94 } catch (RemoteException e) {
95 Log.w(TAG, "PackageManager is dead. Can't get list of packages requesting "
96 + Manifest.permission.PACKAGE_USAGE_STATS);
97 return null;
98 }
99
100 if (packages == null) {
101 // No packages are requesting permission to use the UsageStats API.
102 return null;
103 }
104
105 ArrayMap<String, PackageEntry> entries = new ArrayMap<>();
106 for (final String packageName : packages) {
107 if (!shouldIgnorePackage(packageName)) {
108 entries.put(packageName, new PackageEntry(packageName));
109 }
110 }
111
112 // Load the packages that have been granted the PACKAGE_USAGE_STATS permission.
113 final List<PackageInfo> packageInfos = mPackageManager.getPackagesHoldingPermissions(
114 PM_USAGE_STATS_PERMISSION, 0);
115 final int packageInfoCount = packageInfos != null ? packageInfos.size() : 0;
116 for (int i = 0; i < packageInfoCount; i++) {
117 final PackageInfo packageInfo = packageInfos.get(i);
118 final PackageEntry pe = entries.get(packageInfo.packageName);
119 if (pe != null) {
120 pe.packageInfo = packageInfo;
121 pe.permissionGranted = true;
122 }
123 }
124
125 // Load the remaining packages that have requested but don't have the
126 // PACKAGE_USAGE_STATS permission.
127 int packageCount = entries.size();
128 for (int i = 0; i < packageCount; i++) {
129 final PackageEntry pe = entries.valueAt(i);
130 if (pe.packageInfo == null) {
131 try {
132 pe.packageInfo = mPackageManager.getPackageInfo(pe.packageName, 0);
133 } catch (PackageManager.NameNotFoundException e) {
134 // This package doesn't exist. This may occur when an app is uninstalled for
135 // one user, but it is not removed from the system.
136 entries.removeAt(i);
137 i--;
138 packageCount--;
139 }
140 }
141 }
142
143 // Find out which packages have been granted permission from AppOps.
144 final List<AppOpsManager.PackageOps> packageOps = mAppOpsManager.getPackagesForOps(
145 APP_OPS_OP_CODES);
146 final int packageOpsCount = packageOps != null ? packageOps.size() : 0;
147 for (int i = 0; i < packageOpsCount; i++) {
148 final AppOpsManager.PackageOps packageOp = packageOps.get(i);
149 final PackageEntry pe = entries.get(packageOp.getPackageName());
150 if (pe == null) {
151 Log.w(TAG, "AppOp permission exists for package " + packageOp.getPackageName()
152 + " but package doesn't exist or did not request UsageStats access");
153 continue;
154 }
155
Adam Lesinski366e7a22014-07-25 10:20:26 -0700156 if (packageOp.getUid() != pe.packageInfo.applicationInfo.uid) {
157 // This AppOp does not belong to this user.
158 continue;
159 }
160
Adam Lesinski468d3912014-07-22 10:01:08 -0700161 if (packageOp.getOps().size() < 1) {
162 Log.w(TAG, "No AppOps permission exists for package "
163 + packageOp.getPackageName());
164 continue;
165 }
166
167 pe.appOpMode = packageOp.getOps().get(0).getMode();
168 }
169
170 return entries;
171 }
172
173 @Override
174 protected void onPostExecute(ArrayMap<String, PackageEntry> newEntries) {
175 mLastFetcherTask = null;
176
177 if (getActivity() == null) {
178 // We must have finished the Activity while we were processing in the background.
179 return;
180 }
181
182 if (newEntries == null) {
183 mPackageEntryMap.clear();
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700184 mAppsCategory.removeAll();
Adam Lesinski468d3912014-07-22 10:01:08 -0700185 return;
186 }
187
188 // Find the deleted entries and remove them from the PreferenceScreen.
189 final int oldPackageCount = mPackageEntryMap.size();
190 for (int i = 0; i < oldPackageCount; i++) {
191 final PackageEntry oldPackageEntry = mPackageEntryMap.valueAt(i);
192 final PackageEntry newPackageEntry = newEntries.get(oldPackageEntry.packageName);
193 if (newPackageEntry == null) {
194 // This package has been removed.
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700195 mAppsCategory.removePreference(oldPackageEntry.preference);
Adam Lesinski468d3912014-07-22 10:01:08 -0700196 } else {
197 // This package already exists in the preference hierarchy, so reuse that
198 // Preference.
199 newPackageEntry.preference = oldPackageEntry.preference;
200 }
201 }
202
203 // Now add new packages to the PreferenceScreen.
204 final int packageCount = newEntries.size();
205 for (int i = 0; i < packageCount; i++) {
206 final PackageEntry packageEntry = newEntries.valueAt(i);
207 if (packageEntry.preference == null) {
208 packageEntry.preference = new SwitchPreference(mContext);
209 packageEntry.preference.setPersistent(false);
210 packageEntry.preference.setOnPreferenceChangeListener(UsageAccessSettings.this);
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700211 mAppsCategory.addPreference(packageEntry.preference);
Adam Lesinski468d3912014-07-22 10:01:08 -0700212 }
213 updatePreference(packageEntry);
214 }
215
216 mPackageEntryMap.clear();
217 mPackageEntryMap = newEntries;
218 }
219
220 private void updatePreference(PackageEntry pe) {
221 pe.preference.setIcon(pe.packageInfo.applicationInfo.loadIcon(mPackageManager));
222 pe.preference.setTitle(pe.packageInfo.applicationInfo.loadLabel(mPackageManager));
223 pe.preference.setKey(pe.packageName);
224
225 boolean check = false;
226 if (pe.appOpMode == AppOpsManager.MODE_ALLOWED) {
227 check = true;
228 } else if (pe.appOpMode == AppOpsManager.MODE_DEFAULT) {
229 // If the default AppOps mode is set, then fall back to
230 // whether the app has been granted permission by PackageManager.
231 check = pe.permissionGranted;
232 }
233
234 if (check != pe.preference.isChecked()) {
235 pe.preference.setChecked(check);
236 }
237 }
238 }
239
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700240 static boolean shouldIgnorePackage(String packageName) {
Adam Lesinski468d3912014-07-22 10:01:08 -0700241 return packageName.equals("android") || packageName.equals("com.android.settings");
242 }
243
Adam Lesinski468d3912014-07-22 10:01:08 -0700244 private AppsRequestingAccessFetcher mLastFetcherTask;
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700245 ArrayMap<String, PackageEntry> mPackageEntryMap = new ArrayMap<>();
246 AppOpsManager mAppOpsManager;
247 PreferenceCategory mAppsCategory;
Adam Lesinski468d3912014-07-22 10:01:08 -0700248
249 @Override
250 public void onCreate(Bundle icicle) {
251 super.onCreate(icicle);
252
253 addPreferencesFromResource(R.xml.usage_access_settings);
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700254 mAppsCategory = (PreferenceCategory) getPreferenceScreen().findPreference("apps");
255 mAppsCategory.setOrderingAsAdded(false);
Adam Lesinski468d3912014-07-22 10:01:08 -0700256 mAppOpsManager = (AppOpsManager) getSystemService(Context.APP_OPS_SERVICE);
257 }
258
259 @Override
260 public void onResume() {
261 super.onResume();
262
263 updateInterestedApps();
264 mPackageMonitor.register(getActivity(), Looper.getMainLooper(), false);
265 }
266
267 @Override
268 public void onPause() {
269 super.onPause();
270
271 mPackageMonitor.unregister();
272 if (mLastFetcherTask != null) {
273 mLastFetcherTask.cancel(true);
274 mLastFetcherTask = null;
275 }
276 }
277
278 private void updateInterestedApps() {
279 if (mLastFetcherTask != null) {
280 // Canceling can only fail for some obscure reason since mLastFetcherTask would be
281 // null if the task has already completed. So we ignore the result of cancel and
282 // spawn a new task to get fresh data. AsyncTask executes tasks serially anyways,
283 // so we are safe from running two tasks at the same time.
284 mLastFetcherTask.cancel(true);
285 }
286
287 mLastFetcherTask = new AppsRequestingAccessFetcher(getActivity());
288 mLastFetcherTask.execute();
289 }
290
291 @Override
292 public boolean onPreferenceChange(Preference preference, Object newValue) {
293 final String packageName = preference.getKey();
294 final PackageEntry pe = mPackageEntryMap.get(packageName);
295 if (pe == null) {
296 Log.w(TAG, "Preference change event for package " + packageName
297 + " but that package is no longer valid.");
298 return false;
299 }
300
301 if (!(newValue instanceof Boolean)) {
302 Log.w(TAG, "Preference change event for package " + packageName
303 + " had non boolean value of type " + newValue.getClass().getName());
304 return false;
305 }
306
307 final int newMode = (Boolean) newValue ?
308 AppOpsManager.MODE_ALLOWED : AppOpsManager.MODE_IGNORED;
Adam Lesinski366e7a22014-07-25 10:20:26 -0700309
310 // Check if we need to do any work.
311 if (pe.appOpMode != newMode) {
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700312 if (newMode != AppOpsManager.MODE_ALLOWED) {
313 // Turning off the setting has no warning.
314 setNewMode(pe, newMode);
315 return true;
316 }
317
318 // Turning on the setting has a Warning.
319 getFragmentManager().beginTransaction()
320 .add(new WarningDialog(pe), "warning")
321 .commit();
322 return false;
Adam Lesinski366e7a22014-07-25 10:20:26 -0700323 }
Adam Lesinski468d3912014-07-22 10:01:08 -0700324 return true;
325 }
326
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700327 void setNewMode(PackageEntry pe, int newMode) {
328 mAppOpsManager.setMode(AppOpsManager.OP_GET_USAGE_STATS,
329 pe.packageInfo.applicationInfo.uid, pe.packageName, newMode);
330 pe.appOpMode = newMode;
331 }
332
Adam Lesinski468d3912014-07-22 10:01:08 -0700333 private final PackageMonitor mPackageMonitor = new PackageMonitor() {
334 @Override
335 public void onPackageAdded(String packageName, int uid) {
336 updateInterestedApps();
337 }
338
339 @Override
340 public void onPackageRemoved(String packageName, int uid) {
341 updateInterestedApps();
342 }
343 };
Adam Lesinskie01dfd12014-08-11 20:54:12 -0700344
345 private class WarningDialog extends DialogFragment
346 implements DialogInterface.OnClickListener {
347 private final PackageEntry mEntry;
348
349 public WarningDialog(PackageEntry pe) {
350 mEntry = pe;
351 }
352
353 @Override
354 public Dialog onCreateDialog(Bundle savedInstanceState) {
355 return new AlertDialog.Builder(getActivity())
356 .setTitle(R.string.allow_usage_access_title)
357 .setMessage(R.string.allow_usage_access_message)
358 .setIconAttribute(android.R.attr.alertDialogIcon)
359 .setNegativeButton(R.string.cancel, this)
360 .setPositiveButton(R.string.allow, this)
361 .create();
362 }
363
364 @Override
365 public void onClick(DialogInterface dialog, int which) {
366 if (which == DialogInterface.BUTTON_POSITIVE) {
367 setNewMode(mEntry, AppOpsManager.MODE_ALLOWED);
368 mEntry.preference.setChecked(true);
369 } else {
370 dialog.cancel();
371 }
372 }
373 }
Adam Lesinski468d3912014-07-22 10:01:08 -0700374}