AppOpsState.java revision 90b3b211efda80535ac2981032f66e117ffeb221
1/**
2 * Copyright (C) 2013 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
5 * use this file except in compliance with the License. You may obtain a copy
6 * 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, WITHOUT
12 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13 * License for the specific language governing permissions and limitations
14 * under the License.
15 */
16
17package com.android.settings.applications;
18
19import android.app.AppOpsManager;
20import android.content.Context;
21import android.content.pm.ApplicationInfo;
22import android.content.pm.PackageInfo;
23import android.content.pm.PackageManager;
24import android.content.pm.PackageManager.NameNotFoundException;
25import android.content.res.Resources;
26import android.graphics.drawable.Drawable;
27import android.os.Parcel;
28import android.os.Parcelable;
29import android.text.format.DateUtils;
30
31import android.util.Log;
32import android.util.SparseArray;
33import com.android.settings.R;
34
35import java.io.File;
36import java.text.Collator;
37import java.util.ArrayList;
38import java.util.Collections;
39import java.util.Comparator;
40import java.util.HashMap;
41import java.util.List;
42
43public class AppOpsState {
44    static final String TAG = "AppOpsState";
45    static final boolean DEBUG = false;
46
47    final Context mContext;
48    final AppOpsManager mAppOps;
49    final PackageManager mPm;
50    final CharSequence[] mOpSummaries;
51    final CharSequence[] mOpLabels;
52
53    List<AppOpEntry> mApps;
54
55    public AppOpsState(Context context) {
56        mContext = context;
57        mAppOps = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE);
58        mPm = context.getPackageManager();
59        mOpSummaries = context.getResources().getTextArray(R.array.app_ops_summaries);
60        mOpLabels = context.getResources().getTextArray(R.array.app_ops_labels);
61    }
62
63    public static class OpsTemplate implements Parcelable {
64        public final int[] ops;
65        public final boolean[] showPerms;
66
67        public OpsTemplate(int[] _ops, boolean[] _showPerms) {
68            ops = _ops;
69            showPerms = _showPerms;
70        }
71
72        OpsTemplate(Parcel src) {
73            ops = src.createIntArray();
74            showPerms = src.createBooleanArray();
75        }
76
77        @Override
78        public int describeContents() {
79            return 0;
80        }
81
82        @Override
83        public void writeToParcel(Parcel dest, int flags) {
84            dest.writeIntArray(ops);
85            dest.writeBooleanArray(showPerms);
86        }
87
88        public static final Creator<OpsTemplate> CREATOR = new Creator<OpsTemplate>() {
89            @Override public OpsTemplate createFromParcel(Parcel source) {
90                return new OpsTemplate(source);
91            }
92
93            @Override public OpsTemplate[] newArray(int size) {
94                return new OpsTemplate[size];
95            }
96        };
97    }
98
99    public static final OpsTemplate LOCATION_TEMPLATE = new OpsTemplate(
100            new int[] { AppOpsManager.OP_COARSE_LOCATION,
101                    AppOpsManager.OP_FINE_LOCATION,
102                    AppOpsManager.OP_GPS,
103                    AppOpsManager.OP_WIFI_SCAN,
104                    AppOpsManager.OP_NEIGHBORING_CELLS,
105                    AppOpsManager.OP_MONITOR_LOCATION,
106                    AppOpsManager.OP_MONITOR_HIGH_POWER_LOCATION },
107            new boolean[] { true,
108                    true,
109                    false,
110                    false,
111                    false,
112                    false,
113                    false }
114            );
115
116    public static final OpsTemplate PERSONAL_TEMPLATE = new OpsTemplate(
117            new int[] { AppOpsManager.OP_READ_CONTACTS,
118                    AppOpsManager.OP_WRITE_CONTACTS,
119                    AppOpsManager.OP_READ_CALL_LOG,
120                    AppOpsManager.OP_WRITE_CALL_LOG,
121                    AppOpsManager.OP_READ_CALENDAR,
122                    AppOpsManager.OP_WRITE_CALENDAR,
123                    AppOpsManager.OP_READ_CLIPBOARD,
124                    AppOpsManager.OP_WRITE_CLIPBOARD },
125            new boolean[] { true,
126                    true,
127                    true,
128                    true,
129                    true,
130                    true,
131                    false,
132                    false }
133            );
134
135    public static final OpsTemplate MESSAGING_TEMPLATE = new OpsTemplate(
136            new int[] { AppOpsManager.OP_READ_SMS,
137                    AppOpsManager.OP_RECEIVE_SMS,
138                    AppOpsManager.OP_RECEIVE_EMERGECY_SMS,
139                    AppOpsManager.OP_RECEIVE_MMS,
140                    AppOpsManager.OP_RECEIVE_WAP_PUSH,
141                    AppOpsManager.OP_WRITE_SMS,
142                    AppOpsManager.OP_SEND_SMS,
143                    AppOpsManager.OP_READ_ICC_SMS,
144                    AppOpsManager.OP_WRITE_ICC_SMS },
145            new boolean[] { true,
146                    true,
147                    true,
148                    true,
149                    true,
150                    true,
151                    true,
152                    true,
153                    true }
154            );
155
156    public static final OpsTemplate MEDIA_TEMPLATE = new OpsTemplate(
157            new int[] { AppOpsManager.OP_VIBRATE,
158                    AppOpsManager.OP_CAMERA,
159                    AppOpsManager.OP_RECORD_AUDIO,
160                    AppOpsManager.OP_PLAY_AUDIO,
161                    AppOpsManager.OP_TAKE_MEDIA_BUTTONS,
162                    AppOpsManager.OP_TAKE_AUDIO_FOCUS,
163                    AppOpsManager.OP_AUDIO_MASTER_VOLUME,
164                    AppOpsManager.OP_AUDIO_VOICE_VOLUME,
165                    AppOpsManager.OP_AUDIO_RING_VOLUME,
166                    AppOpsManager.OP_AUDIO_MEDIA_VOLUME,
167                    AppOpsManager.OP_AUDIO_ALARM_VOLUME,
168                    AppOpsManager.OP_AUDIO_NOTIFICATION_VOLUME,
169                    AppOpsManager.OP_AUDIO_BLUETOOTH_VOLUME,
170                    AppOpsManager.OP_MUTE_MICROPHONE},
171            new boolean[] { false,
172                    true,
173                    true,
174                    false,
175                    false,
176                    false,
177                    false,
178                    false,
179                    false,
180                    false,
181                    false,
182                    false,
183                    false }
184            );
185
186    public static final OpsTemplate DEVICE_TEMPLATE = new OpsTemplate(
187            new int[] { AppOpsManager.OP_POST_NOTIFICATION,
188                    AppOpsManager.OP_ACCESS_NOTIFICATIONS,
189                    AppOpsManager.OP_CALL_PHONE,
190                    AppOpsManager.OP_WRITE_SETTINGS,
191                    AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
192                    AppOpsManager.OP_WAKE_LOCK,
193                    AppOpsManager.OP_PROJECT_MEDIA,
194                    AppOpsManager.OP_ACTIVATE_VPN, },
195            new boolean[] { false,
196                    true,
197                    true,
198                    true,
199                    true,
200                    true,
201                    false,
202                    false, }
203            );
204
205    public static final OpsTemplate[] ALL_TEMPLATES = new OpsTemplate[] {
206            LOCATION_TEMPLATE, PERSONAL_TEMPLATE, MESSAGING_TEMPLATE,
207            MEDIA_TEMPLATE, DEVICE_TEMPLATE
208    };
209
210    /**
211     * This class holds the per-item data in our Loader.
212     */
213    public static class AppEntry {
214        private final AppOpsState mState;
215        private final ApplicationInfo mInfo;
216        private final File mApkFile;
217        private final SparseArray<AppOpsManager.OpEntry> mOps
218                = new SparseArray<AppOpsManager.OpEntry>();
219        private final SparseArray<AppOpEntry> mOpSwitches
220                = new SparseArray<AppOpEntry>();
221        private String mLabel;
222        private Drawable mIcon;
223        private boolean mMounted;
224
225        public AppEntry(AppOpsState state, ApplicationInfo info) {
226            mState = state;
227            mInfo = info;
228            mApkFile = new File(info.sourceDir);
229        }
230
231        public void addOp(AppOpEntry entry, AppOpsManager.OpEntry op) {
232            mOps.put(op.getOp(), op);
233            mOpSwitches.put(AppOpsManager.opToSwitch(op.getOp()), entry);
234        }
235
236        public boolean hasOp(int op) {
237            return mOps.indexOfKey(op) >= 0;
238        }
239
240        public AppOpEntry getOpSwitch(int op) {
241            return mOpSwitches.get(AppOpsManager.opToSwitch(op));
242        }
243
244        public ApplicationInfo getApplicationInfo() {
245            return mInfo;
246        }
247
248        public String getLabel() {
249            return mLabel;
250        }
251
252        public Drawable getIcon() {
253            if (mIcon == null) {
254                if (mApkFile.exists()) {
255                    mIcon = mInfo.loadIcon(mState.mPm);
256                    return mIcon;
257                } else {
258                    mMounted = false;
259                }
260            } else if (!mMounted) {
261                // If the app wasn't mounted but is now mounted, reload
262                // its icon.
263                if (mApkFile.exists()) {
264                    mMounted = true;
265                    mIcon = mInfo.loadIcon(mState.mPm);
266                    return mIcon;
267                }
268            } else {
269                return mIcon;
270            }
271
272            return mState.mContext.getResources().getDrawable(
273                    android.R.drawable.sym_def_app_icon);
274        }
275
276        @Override public String toString() {
277            return mLabel;
278        }
279
280        void loadLabel(Context context) {
281            if (mLabel == null || !mMounted) {
282                if (!mApkFile.exists()) {
283                    mMounted = false;
284                    mLabel = mInfo.packageName;
285                } else {
286                    mMounted = true;
287                    CharSequence label = mInfo.loadLabel(context.getPackageManager());
288                    mLabel = label != null ? label.toString() : mInfo.packageName;
289                }
290            }
291        }
292    }
293
294    /**
295     * This class holds the per-item data in our Loader.
296     */
297    public static class AppOpEntry {
298        private final AppOpsManager.PackageOps mPkgOps;
299        private final ArrayList<AppOpsManager.OpEntry> mOps
300                = new ArrayList<AppOpsManager.OpEntry>();
301        private final ArrayList<AppOpsManager.OpEntry> mSwitchOps
302                = new ArrayList<AppOpsManager.OpEntry>();
303        private final AppEntry mApp;
304        private final int mSwitchOrder;
305
306        public AppOpEntry(AppOpsManager.PackageOps pkg, AppOpsManager.OpEntry op, AppEntry app,
307                int switchOrder) {
308            mPkgOps = pkg;
309            mApp = app;
310            mSwitchOrder = switchOrder;
311            mApp.addOp(this, op);
312            mOps.add(op);
313            mSwitchOps.add(op);
314        }
315
316        private static void addOp(ArrayList<AppOpsManager.OpEntry> list, AppOpsManager.OpEntry op) {
317            for (int i=0; i<list.size(); i++) {
318                AppOpsManager.OpEntry pos = list.get(i);
319                if (pos.isRunning() != op.isRunning()) {
320                    if (op.isRunning()) {
321                        list.add(i, op);
322                        return;
323                    }
324                    continue;
325                }
326                if (pos.getTime() < op.getTime()) {
327                    list.add(i, op);
328                    return;
329                }
330            }
331            list.add(op);
332        }
333
334        public void addOp(AppOpsManager.OpEntry op) {
335            mApp.addOp(this, op);
336            addOp(mOps, op);
337            if (mApp.getOpSwitch(AppOpsManager.opToSwitch(op.getOp())) == null) {
338                addOp(mSwitchOps, op);
339            }
340        }
341
342        public AppEntry getAppEntry() {
343            return mApp;
344        }
345
346        public int getSwitchOrder() {
347            return mSwitchOrder;
348        }
349
350        public AppOpsManager.PackageOps getPackageOps() {
351            return mPkgOps;
352        }
353
354        public int getNumOpEntry() {
355            return mOps.size();
356        }
357
358        public AppOpsManager.OpEntry getOpEntry(int pos) {
359            return mOps.get(pos);
360        }
361
362        private CharSequence getCombinedText(ArrayList<AppOpsManager.OpEntry> ops,
363                CharSequence[] items) {
364            if (ops.size() == 1) {
365                return items[ops.get(0).getOp()];
366            } else {
367                StringBuilder builder = new StringBuilder();
368                for (int i=0; i<ops.size(); i++) {
369                    if (i > 0) {
370                        builder.append(", ");
371                    }
372                    builder.append(items[ops.get(i).getOp()]);
373                }
374                return builder.toString();
375            }
376        }
377
378        public CharSequence getSummaryText(AppOpsState state) {
379            return getCombinedText(mOps, state.mOpSummaries);
380        }
381
382        public CharSequence getSwitchText(AppOpsState state) {
383            if (mSwitchOps.size() > 0) {
384                return getCombinedText(mSwitchOps, state.mOpLabels);
385            } else {
386                return getCombinedText(mOps, state.mOpLabels);
387            }
388        }
389
390        public CharSequence getTimeText(Resources res, boolean showEmptyText) {
391            if (isRunning()) {
392                return res.getText(R.string.app_ops_running);
393            }
394            if (getTime() > 0) {
395                return DateUtils.getRelativeTimeSpanString(getTime(),
396                        System.currentTimeMillis(),
397                        DateUtils.MINUTE_IN_MILLIS,
398                        DateUtils.FORMAT_ABBREV_RELATIVE);
399            }
400            return showEmptyText ? res.getText(R.string.app_ops_never_used) : "";
401        }
402
403        public boolean isRunning() {
404            return mOps.get(0).isRunning();
405        }
406
407        public long getTime() {
408            return mOps.get(0).getTime();
409        }
410
411        @Override public String toString() {
412            return mApp.getLabel();
413        }
414    }
415
416    /**
417     * Perform alphabetical comparison of application entry objects.
418     */
419    public static final Comparator<AppOpEntry> APP_OP_COMPARATOR = new Comparator<AppOpEntry>() {
420        private final Collator sCollator = Collator.getInstance();
421        @Override
422        public int compare(AppOpEntry object1, AppOpEntry object2) {
423            if (object1.getSwitchOrder() != object2.getSwitchOrder()) {
424                return object1.getSwitchOrder() < object2.getSwitchOrder() ? -1 : 1;
425            }
426            if (object1.isRunning() != object2.isRunning()) {
427                // Currently running ops go first.
428                return object1.isRunning() ? -1 : 1;
429            }
430            if (object1.getTime() != object2.getTime()) {
431                // More recent times go first.
432                return object1.getTime() > object2.getTime() ? -1 : 1;
433            }
434            return sCollator.compare(object1.getAppEntry().getLabel(),
435                    object2.getAppEntry().getLabel());
436        }
437    };
438
439    private void addOp(List<AppOpEntry> entries, AppOpsManager.PackageOps pkgOps,
440            AppEntry appEntry, AppOpsManager.OpEntry opEntry, boolean allowMerge, int switchOrder) {
441        if (allowMerge && entries.size() > 0) {
442            AppOpEntry last = entries.get(entries.size()-1);
443            if (last.getAppEntry() == appEntry) {
444                boolean lastExe = last.getTime() != 0;
445                boolean entryExe = opEntry.getTime() != 0;
446                if (lastExe == entryExe) {
447                    if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
448                            + pkgOps.getPackageName() + ": append to " + last);
449                    last.addOp(opEntry);
450                    return;
451                }
452            }
453        }
454        AppOpEntry entry = appEntry.getOpSwitch(opEntry.getOp());
455        if (entry != null) {
456            entry.addOp(opEntry);
457            return;
458        }
459        entry = new AppOpEntry(pkgOps, opEntry, appEntry, switchOrder);
460        if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
461                + pkgOps.getPackageName() + ": making new " + entry);
462        entries.add(entry);
463    }
464
465    public List<AppOpEntry> buildState(OpsTemplate tpl) {
466        return buildState(tpl, 0, null);
467    }
468
469    private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,
470            final String packageName, ApplicationInfo appInfo) {
471        AppEntry appEntry = appEntries.get(packageName);
472        if (appEntry == null) {
473            if (appInfo == null) {
474                try {
475                    appInfo = mPm.getApplicationInfo(packageName,
476                            PackageManager.GET_DISABLED_COMPONENTS
477                            | PackageManager.GET_UNINSTALLED_PACKAGES);
478                } catch (PackageManager.NameNotFoundException e) {
479                    Log.w(TAG, "Unable to find info for package " + packageName);
480                    return null;
481                }
482            }
483            appEntry = new AppEntry(this, appInfo);
484            appEntry.loadLabel(context);
485            appEntries.put(packageName, appEntry);
486        }
487        return appEntry;
488    }
489
490    public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName) {
491        final Context context = mContext;
492
493        final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();
494        final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();
495
496        final ArrayList<String> perms = new ArrayList<String>();
497        final ArrayList<Integer> permOps = new ArrayList<Integer>();
498        final int[] opToOrder = new int[AppOpsManager._NUM_OP];
499        for (int i=0; i<tpl.ops.length; i++) {
500            if (tpl.showPerms[i]) {
501                String perm = AppOpsManager.opToPermission(tpl.ops[i]);
502                if (perm != null && !perms.contains(perm)) {
503                    perms.add(perm);
504                    permOps.add(tpl.ops[i]);
505                    opToOrder[tpl.ops[i]] = i;
506                }
507            }
508        }
509
510        List<AppOpsManager.PackageOps> pkgs;
511        if (packageName != null) {
512            pkgs = mAppOps.getOpsForPackage(uid, packageName, tpl.ops);
513        } else {
514            pkgs = mAppOps.getPackagesForOps(tpl.ops);
515        }
516
517        if (pkgs != null) {
518            for (int i=0; i<pkgs.size(); i++) {
519                AppOpsManager.PackageOps pkgOps = pkgs.get(i);
520                AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null);
521                if (appEntry == null) {
522                    continue;
523                }
524                for (int j=0; j<pkgOps.getOps().size(); j++) {
525                    AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
526                    addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
527                            packageName == null ? 0 : opToOrder[opEntry.getOp()]);
528                }
529            }
530        }
531
532        List<PackageInfo> apps;
533        if (packageName != null) {
534            apps = new ArrayList<PackageInfo>();
535            try {
536                PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
537                apps.add(pi);
538            } catch (NameNotFoundException e) {
539            }
540        } else {
541            String[] permsArray = new String[perms.size()];
542            perms.toArray(permsArray);
543            apps = mPm.getPackagesHoldingPermissions(permsArray, 0);
544        }
545        for (int i=0; i<apps.size(); i++) {
546            PackageInfo appInfo = apps.get(i);
547            AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName,
548                    appInfo.applicationInfo);
549            if (appEntry == null) {
550                continue;
551            }
552            List<AppOpsManager.OpEntry> dummyOps = null;
553            AppOpsManager.PackageOps pkgOps = null;
554            if (appInfo.requestedPermissions != null) {
555                for (int j=0; j<appInfo.requestedPermissions.length; j++) {
556                    if (appInfo.requestedPermissionsFlags != null) {
557                        if ((appInfo.requestedPermissionsFlags[j]
558                                & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
559                            if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm "
560                                    + appInfo.requestedPermissions[j] + " not granted; skipping");
561                            continue;
562                        }
563                    }
564                    if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + ": requested perm "
565                            + appInfo.requestedPermissions[j]);
566                    for (int k=0; k<perms.size(); k++) {
567                        if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {
568                            continue;
569                        }
570                        if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + perms.get(k)
571                                + " has op " + permOps.get(k) + ": " + appEntry.hasOp(permOps.get(k)));
572                        if (appEntry.hasOp(permOps.get(k))) {
573                            continue;
574                        }
575                        if (dummyOps == null) {
576                            dummyOps = new ArrayList<AppOpsManager.OpEntry>();
577                            pkgOps = new AppOpsManager.PackageOps(
578                                    appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
579
580                        }
581                        AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(
582                                permOps.get(k), AppOpsManager.MODE_ALLOWED, 0, 0, 0);
583                        dummyOps.add(opEntry);
584                        addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
585                                packageName == null ? 0 : opToOrder[opEntry.getOp()]);
586                    }
587                }
588            }
589        }
590
591        // Sort the list.
592        Collections.sort(entries, APP_OP_COMPARATOR);
593
594        // Done!
595        return entries;
596    }
597}
598