AppOpsState.java revision ec74da60cda5d0d7d1901e20a5a7806ef4cf387f
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            new boolean[] { true,
106                    true,
107                    false,
108                    false,
109                    false }
110            );
111
112    public static final OpsTemplate PERSONAL_TEMPLATE = new OpsTemplate(
113            new int[] { AppOpsManager.OP_READ_CONTACTS,
114                    AppOpsManager.OP_WRITE_CONTACTS,
115                    AppOpsManager.OP_READ_CALL_LOG,
116                    AppOpsManager.OP_WRITE_CALL_LOG,
117                    AppOpsManager.OP_READ_CALENDAR,
118                    AppOpsManager.OP_WRITE_CALENDAR,
119                    AppOpsManager.OP_READ_CLIPBOARD,
120                    AppOpsManager.OP_WRITE_CLIPBOARD },
121            new boolean[] { true,
122                    true,
123                    true,
124                    true,
125                    true,
126                    true,
127                    false,
128                    false }
129            );
130
131    public static final OpsTemplate MESSAGING_TEMPLATE = new OpsTemplate(
132            new int[] { AppOpsManager.OP_READ_SMS,
133                    AppOpsManager.OP_RECEIVE_SMS,
134                    AppOpsManager.OP_RECEIVE_EMERGECY_SMS,
135                    AppOpsManager.OP_RECEIVE_MMS,
136                    AppOpsManager.OP_RECEIVE_WAP_PUSH,
137                    AppOpsManager.OP_WRITE_SMS,
138                    AppOpsManager.OP_SEND_SMS,
139                    AppOpsManager.OP_READ_ICC_SMS,
140                    AppOpsManager.OP_WRITE_ICC_SMS },
141            new boolean[] { true,
142                    true,
143                    true,
144                    true,
145                    true,
146                    true,
147                    true,
148                    true,
149                    true }
150            );
151
152    public static final OpsTemplate MEDIA_TEMPLATE = new OpsTemplate(
153            new int[] { AppOpsManager.OP_VIBRATE,
154                    AppOpsManager.OP_CAMERA,
155                    AppOpsManager.OP_RECORD_AUDIO,
156                    AppOpsManager.OP_PLAY_AUDIO,
157                    AppOpsManager.OP_TAKE_MEDIA_BUTTONS,
158                    AppOpsManager.OP_TAKE_AUDIO_FOCUS,
159                    AppOpsManager.OP_AUDIO_MASTER_VOLUME,
160                    AppOpsManager.OP_AUDIO_VOICE_VOLUME,
161                    AppOpsManager.OP_AUDIO_RING_VOLUME,
162                    AppOpsManager.OP_AUDIO_MEDIA_VOLUME,
163                    AppOpsManager.OP_AUDIO_ALARM_VOLUME,
164                    AppOpsManager.OP_AUDIO_NOTIFICATION_VOLUME,
165                    AppOpsManager.OP_AUDIO_BLUETOOTH_VOLUME, },
166            new boolean[] { false,
167                    true,
168                    true,
169                    false,
170                    false,
171                    false,
172                    false,
173                    false,
174                    false,
175                    false,
176                    false,
177                    false,
178                    false }
179            );
180
181    public static final OpsTemplate DEVICE_TEMPLATE = new OpsTemplate(
182            new int[] { AppOpsManager.OP_POST_NOTIFICATION,
183                    AppOpsManager.OP_ACCESS_NOTIFICATIONS,
184                    AppOpsManager.OP_CALL_PHONE,
185                    AppOpsManager.OP_WRITE_SETTINGS,
186                    AppOpsManager.OP_SYSTEM_ALERT_WINDOW,
187                    AppOpsManager.OP_WAKE_LOCK },
188            new boolean[] { false,
189                    true,
190                    true,
191                    true,
192                    true,
193                    true,  }
194            );
195
196    public static final OpsTemplate[] ALL_TEMPLATES = new OpsTemplate[] {
197            LOCATION_TEMPLATE, PERSONAL_TEMPLATE, MESSAGING_TEMPLATE,
198            MEDIA_TEMPLATE, DEVICE_TEMPLATE
199    };
200
201    /**
202     * This class holds the per-item data in our Loader.
203     */
204    public static class AppEntry {
205        private final AppOpsState mState;
206        private final ApplicationInfo mInfo;
207        private final File mApkFile;
208        private final SparseArray<AppOpsManager.OpEntry> mOps
209                = new SparseArray<AppOpsManager.OpEntry>();
210        private final SparseArray<AppOpEntry> mOpSwitches
211                = new SparseArray<AppOpEntry>();
212        private String mLabel;
213        private Drawable mIcon;
214        private boolean mMounted;
215
216        public AppEntry(AppOpsState state, ApplicationInfo info) {
217            mState = state;
218            mInfo = info;
219            mApkFile = new File(info.sourceDir);
220        }
221
222        public void addOp(AppOpEntry entry, AppOpsManager.OpEntry op) {
223            mOps.put(op.getOp(), op);
224            mOpSwitches.put(AppOpsManager.opToSwitch(op.getOp()), entry);
225        }
226
227        public boolean hasOp(int op) {
228            return mOps.indexOfKey(op) >= 0;
229        }
230
231        public AppOpEntry getOpSwitch(int op) {
232            return mOpSwitches.get(AppOpsManager.opToSwitch(op));
233        }
234
235        public ApplicationInfo getApplicationInfo() {
236            return mInfo;
237        }
238
239        public String getLabel() {
240            return mLabel;
241        }
242
243        public Drawable getIcon() {
244            if (mIcon == null) {
245                if (mApkFile.exists()) {
246                    mIcon = mInfo.loadIcon(mState.mPm);
247                    return mIcon;
248                } else {
249                    mMounted = false;
250                }
251            } else if (!mMounted) {
252                // If the app wasn't mounted but is now mounted, reload
253                // its icon.
254                if (mApkFile.exists()) {
255                    mMounted = true;
256                    mIcon = mInfo.loadIcon(mState.mPm);
257                    return mIcon;
258                }
259            } else {
260                return mIcon;
261            }
262
263            return mState.mContext.getResources().getDrawable(
264                    android.R.drawable.sym_def_app_icon);
265        }
266
267        @Override public String toString() {
268            return mLabel;
269        }
270
271        void loadLabel(Context context) {
272            if (mLabel == null || !mMounted) {
273                if (!mApkFile.exists()) {
274                    mMounted = false;
275                    mLabel = mInfo.packageName;
276                } else {
277                    mMounted = true;
278                    CharSequence label = mInfo.loadLabel(context.getPackageManager());
279                    mLabel = label != null ? label.toString() : mInfo.packageName;
280                }
281            }
282        }
283    }
284
285    /**
286     * This class holds the per-item data in our Loader.
287     */
288    public static class AppOpEntry {
289        private final AppOpsManager.PackageOps mPkgOps;
290        private final ArrayList<AppOpsManager.OpEntry> mOps
291                = new ArrayList<AppOpsManager.OpEntry>();
292        private final ArrayList<AppOpsManager.OpEntry> mSwitchOps
293                = new ArrayList<AppOpsManager.OpEntry>();
294        private final AppEntry mApp;
295        private final int mSwitchOrder;
296
297        public AppOpEntry(AppOpsManager.PackageOps pkg, AppOpsManager.OpEntry op, AppEntry app,
298                int switchOrder) {
299            mPkgOps = pkg;
300            mApp = app;
301            mSwitchOrder = switchOrder;
302            mApp.addOp(this, op);
303            mOps.add(op);
304            mSwitchOps.add(op);
305        }
306
307        private static void addOp(ArrayList<AppOpsManager.OpEntry> list, AppOpsManager.OpEntry op) {
308            for (int i=0; i<list.size(); i++) {
309                AppOpsManager.OpEntry pos = list.get(i);
310                if (pos.isRunning() != op.isRunning()) {
311                    if (op.isRunning()) {
312                        list.add(i, op);
313                        return;
314                    }
315                    continue;
316                }
317                if (pos.getTime() < op.getTime()) {
318                    list.add(i, op);
319                    return;
320                }
321            }
322            list.add(op);
323        }
324
325        public void addOp(AppOpsManager.OpEntry op) {
326            mApp.addOp(this, op);
327            addOp(mOps, op);
328            if (mApp.getOpSwitch(AppOpsManager.opToSwitch(op.getOp())) == null) {
329                addOp(mSwitchOps, op);
330            }
331        }
332
333        public AppEntry getAppEntry() {
334            return mApp;
335        }
336
337        public int getSwitchOrder() {
338            return mSwitchOrder;
339        }
340
341        public AppOpsManager.PackageOps getPackageOps() {
342            return mPkgOps;
343        }
344
345        public int getNumOpEntry() {
346            return mOps.size();
347        }
348
349        public AppOpsManager.OpEntry getOpEntry(int pos) {
350            return mOps.get(pos);
351        }
352
353        private CharSequence getCombinedText(ArrayList<AppOpsManager.OpEntry> ops,
354                CharSequence[] items) {
355            if (ops.size() == 1) {
356                return items[ops.get(0).getOp()];
357            } else {
358                StringBuilder builder = new StringBuilder();
359                for (int i=0; i<ops.size(); i++) {
360                    if (i > 0) {
361                        builder.append(", ");
362                    }
363                    builder.append(items[ops.get(i).getOp()]);
364                }
365                return builder.toString();
366            }
367        }
368
369        public CharSequence getSummaryText(AppOpsState state) {
370            return getCombinedText(mOps, state.mOpSummaries);
371        }
372
373        public CharSequence getSwitchText(AppOpsState state) {
374            if (mSwitchOps.size() > 0) {
375                return getCombinedText(mSwitchOps, state.mOpLabels);
376            } else {
377                return getCombinedText(mOps, state.mOpLabels);
378            }
379        }
380
381        public CharSequence getTimeText(Resources res, boolean showEmptyText) {
382            if (isRunning()) {
383                return res.getText(R.string.app_ops_running);
384            }
385            if (getTime() > 0) {
386                return DateUtils.getRelativeTimeSpanString(getTime(),
387                        System.currentTimeMillis(),
388                        DateUtils.MINUTE_IN_MILLIS,
389                        DateUtils.FORMAT_ABBREV_RELATIVE);
390            }
391            return showEmptyText ? res.getText(R.string.app_ops_never_used) : "";
392        }
393
394        public boolean isRunning() {
395            return mOps.get(0).isRunning();
396        }
397
398        public long getTime() {
399            return mOps.get(0).getTime();
400        }
401
402        @Override public String toString() {
403            return mApp.getLabel();
404        }
405    }
406
407    /**
408     * Perform alphabetical comparison of application entry objects.
409     */
410    public static final Comparator<AppOpEntry> APP_OP_COMPARATOR = new Comparator<AppOpEntry>() {
411        private final Collator sCollator = Collator.getInstance();
412        @Override
413        public int compare(AppOpEntry object1, AppOpEntry object2) {
414            if (object1.getSwitchOrder() != object2.getSwitchOrder()) {
415                return object1.getSwitchOrder() < object2.getSwitchOrder() ? -1 : 1;
416            }
417            if (object1.isRunning() != object2.isRunning()) {
418                // Currently running ops go first.
419                return object1.isRunning() ? -1 : 1;
420            }
421            if (object1.getTime() != object2.getTime()) {
422                // More recent times go first.
423                return object1.getTime() > object2.getTime() ? -1 : 1;
424            }
425            return sCollator.compare(object1.getAppEntry().getLabel(),
426                    object2.getAppEntry().getLabel());
427        }
428    };
429
430    private void addOp(List<AppOpEntry> entries, AppOpsManager.PackageOps pkgOps,
431            AppEntry appEntry, AppOpsManager.OpEntry opEntry, boolean allowMerge, int switchOrder) {
432        if (allowMerge && entries.size() > 0) {
433            AppOpEntry last = entries.get(entries.size()-1);
434            if (last.getAppEntry() == appEntry) {
435                boolean lastExe = last.getTime() != 0;
436                boolean entryExe = opEntry.getTime() != 0;
437                if (lastExe == entryExe) {
438                    if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
439                            + pkgOps.getPackageName() + ": append to " + last);
440                    last.addOp(opEntry);
441                    return;
442                }
443            }
444        }
445        AppOpEntry entry = appEntry.getOpSwitch(opEntry.getOp());
446        if (entry != null) {
447            entry.addOp(opEntry);
448            return;
449        }
450        entry = new AppOpEntry(pkgOps, opEntry, appEntry, switchOrder);
451        if (DEBUG) Log.d(TAG, "Add op " + opEntry.getOp() + " to package "
452                + pkgOps.getPackageName() + ": making new " + entry);
453        entries.add(entry);
454    }
455
456    public List<AppOpEntry> buildState(OpsTemplate tpl) {
457        return buildState(tpl, 0, null);
458    }
459
460    private AppEntry getAppEntry(final Context context, final HashMap<String, AppEntry> appEntries,
461            final String packageName, ApplicationInfo appInfo) {
462        AppEntry appEntry = appEntries.get(packageName);
463        if (appEntry == null) {
464            if (appInfo == null) {
465                try {
466                    appInfo = mPm.getApplicationInfo(packageName,
467                            PackageManager.GET_DISABLED_COMPONENTS
468                            | PackageManager.GET_UNINSTALLED_PACKAGES);
469                } catch (PackageManager.NameNotFoundException e) {
470                    Log.w(TAG, "Unable to find info for package " + packageName);
471                    return null;
472                }
473            }
474            appEntry = new AppEntry(this, appInfo);
475            appEntry.loadLabel(context);
476            appEntries.put(packageName, appEntry);
477        }
478        return appEntry;
479    }
480
481    public List<AppOpEntry> buildState(OpsTemplate tpl, int uid, String packageName) {
482        final Context context = mContext;
483
484        final HashMap<String, AppEntry> appEntries = new HashMap<String, AppEntry>();
485        final List<AppOpEntry> entries = new ArrayList<AppOpEntry>();
486
487        final ArrayList<String> perms = new ArrayList<String>();
488        final ArrayList<Integer> permOps = new ArrayList<Integer>();
489        final int[] opToOrder = new int[AppOpsManager._NUM_OP];
490        for (int i=0; i<tpl.ops.length; i++) {
491            if (tpl.showPerms[i]) {
492                String perm = AppOpsManager.opToPermission(tpl.ops[i]);
493                if (perm != null && !perms.contains(perm)) {
494                    perms.add(perm);
495                    permOps.add(tpl.ops[i]);
496                    opToOrder[tpl.ops[i]] = i;
497                }
498            }
499        }
500
501        List<AppOpsManager.PackageOps> pkgs;
502        if (packageName != null) {
503            pkgs = mAppOps.getOpsForPackage(uid, packageName, tpl.ops);
504        } else {
505            pkgs = mAppOps.getPackagesForOps(tpl.ops);
506        }
507
508        if (pkgs != null) {
509            for (int i=0; i<pkgs.size(); i++) {
510                AppOpsManager.PackageOps pkgOps = pkgs.get(i);
511                AppEntry appEntry = getAppEntry(context, appEntries, pkgOps.getPackageName(), null);
512                if (appEntry == null) {
513                    continue;
514                }
515                for (int j=0; j<pkgOps.getOps().size(); j++) {
516                    AppOpsManager.OpEntry opEntry = pkgOps.getOps().get(j);
517                    addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
518                            packageName == null ? 0 : opToOrder[opEntry.getOp()]);
519                }
520            }
521        }
522
523        List<PackageInfo> apps;
524        if (packageName != null) {
525            apps = new ArrayList<PackageInfo>();
526            try {
527                PackageInfo pi = mPm.getPackageInfo(packageName, PackageManager.GET_PERMISSIONS);
528                apps.add(pi);
529            } catch (NameNotFoundException e) {
530            }
531        } else {
532            String[] permsArray = new String[perms.size()];
533            perms.toArray(permsArray);
534            apps = mPm.getPackagesHoldingPermissions(permsArray, 0);
535        }
536        for (int i=0; i<apps.size(); i++) {
537            PackageInfo appInfo = apps.get(i);
538            AppEntry appEntry = getAppEntry(context, appEntries, appInfo.packageName,
539                    appInfo.applicationInfo);
540            if (appEntry == null) {
541                continue;
542            }
543            List<AppOpsManager.OpEntry> dummyOps = null;
544            AppOpsManager.PackageOps pkgOps = null;
545            if (appInfo.requestedPermissions != null) {
546                for (int j=0; j<appInfo.requestedPermissions.length; j++) {
547                    if (appInfo.requestedPermissionsFlags != null) {
548                        if ((appInfo.requestedPermissionsFlags[j]
549                                & PackageInfo.REQUESTED_PERMISSION_GRANTED) == 0) {
550                            if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm "
551                                    + appInfo.requestedPermissions[j] + " not granted; skipping");
552                            break;
553                        }
554                    }
555                    if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + ": requested perm "
556                            + appInfo.requestedPermissions[j]);
557                    for (int k=0; k<perms.size(); k++) {
558                        if (!perms.get(k).equals(appInfo.requestedPermissions[j])) {
559                            continue;
560                        }
561                        if (DEBUG) Log.d(TAG, "Pkg " + appInfo.packageName + " perm " + perms.get(k)
562                                + " has op " + permOps.get(k) + ": " + appEntry.hasOp(permOps.get(k)));
563                        if (appEntry.hasOp(permOps.get(k))) {
564                            continue;
565                        }
566                        if (dummyOps == null) {
567                            dummyOps = new ArrayList<AppOpsManager.OpEntry>();
568                            pkgOps = new AppOpsManager.PackageOps(
569                                    appInfo.packageName, appInfo.applicationInfo.uid, dummyOps);
570
571                        }
572                        AppOpsManager.OpEntry opEntry = new AppOpsManager.OpEntry(
573                                permOps.get(k), AppOpsManager.MODE_ALLOWED, 0, 0, 0);
574                        dummyOps.add(opEntry);
575                        addOp(entries, pkgOps, appEntry, opEntry, packageName == null,
576                                packageName == null ? 0 : opToOrder[opEntry.getOp()]);
577                    }
578                }
579            }
580        }
581
582        // Sort the list.
583        Collections.sort(entries, APP_OP_COMPARATOR);
584
585        // Done!
586        return entries;
587    }
588}
589