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