InstalledAppDetails.java revision b45e27bc0f52d64a71aecba661770b30f6299301
1/**
2 * Copyright (C) 2007 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.Activity;
20import android.app.ActivityManager;
21import android.app.AlertDialog;
22import android.app.LoaderManager.LoaderCallbacks;
23import android.content.ActivityNotFoundException;
24import android.content.BroadcastReceiver;
25import android.content.ComponentName;
26import android.content.Context;
27import android.content.DialogInterface;
28import android.content.Intent;
29import android.content.Loader;
30import android.content.pm.ApplicationInfo;
31import android.content.pm.PackageInfo;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ResolveInfo;
35import android.net.INetworkStatsService;
36import android.net.INetworkStatsSession;
37import android.net.NetworkTemplate;
38import android.net.TrafficStats;
39import android.net.Uri;
40import android.os.AsyncTask;
41import android.os.BatteryStats;
42import android.os.Bundle;
43import android.os.RemoteException;
44import android.os.ServiceManager;
45import android.os.UserHandle;
46import android.preference.Preference;
47import android.preference.Preference.OnPreferenceClickListener;
48import android.provider.Settings;
49import android.text.format.DateUtils;
50import android.text.format.Formatter;
51import android.util.Log;
52import android.view.Menu;
53import android.view.MenuInflater;
54import android.view.MenuItem;
55import android.view.View;
56import android.widget.Button;
57import android.widget.ImageView;
58import android.widget.TextView;
59
60import com.android.internal.logging.MetricsLogger;
61import com.android.internal.os.BatterySipper;
62import com.android.internal.os.BatteryStatsHelper;
63import com.android.settings.DataUsageSummary;
64import com.android.settings.DataUsageSummary.AppItem;
65import com.android.settings.R;
66import com.android.settings.SettingsActivity;
67import com.android.settings.Utils;
68import com.android.settings.applications.ApplicationsState.AppEntry;
69import com.android.settings.fuelgauge.BatteryEntry;
70import com.android.settings.fuelgauge.PowerUsageDetail;
71import com.android.settings.net.ChartData;
72import com.android.settings.net.ChartDataLoader;
73import com.android.settings.notification.AppNotificationSettings;
74import com.android.settings.notification.NotificationBackend;
75import com.android.settings.notification.NotificationBackend.AppRow;
76
77import java.lang.ref.WeakReference;
78import java.util.ArrayList;
79import java.util.HashSet;
80import java.util.List;
81
82/**
83 * Activity to display application information from Settings. This activity presents
84 * extended information associated with a package like code, data, total size, permissions
85 * used by the application and also the set of default launchable activities.
86 * For system applications, an option to clear user data is displayed only if data size is > 0.
87 * System applications that do not want clear user data do not have this option.
88 * For non-system applications, there is no option to clear data. Instead there is an option to
89 * uninstall the application.
90 */
91public class InstalledAppDetails extends AppInfoBase
92        implements View.OnClickListener, OnPreferenceClickListener {
93
94    private static final String LOG_TAG = "InstalledAppDetails";
95
96    // Menu identifiers
97    public static final int UNINSTALL_ALL_USERS_MENU = 1;
98    public static final int UNINSTALL_UPDATES = 2;
99
100    // Result code identifiers
101    public static final int REQUEST_UNINSTALL = 0;
102    private static final int SUB_INFO_FRAGMENT = 1;
103
104    private static final int LOADER_CHART_DATA = 2;
105
106    private static final int DLG_FORCE_STOP = DLG_BASE + 1;
107    private static final int DLG_DISABLE = DLG_BASE + 2;
108    private static final int DLG_SPECIAL_DISABLE = DLG_BASE + 3;
109    private static final int DLG_FACTORY_RESET = DLG_BASE + 4;
110
111    private static final String KEY_HEADER = "header_view";
112    private static final String KEY_NOTIFICATION = "notification_settings";
113    private static final String KEY_STORAGE = "storage_settings";
114    private static final String KEY_PERMISSION = "permission_settings";
115    private static final String KEY_DATA = "data_settings";
116    private static final String KEY_LAUNCH = "preferred_settings";
117    private static final String KEY_BATTERY = "battery";
118
119    private final HashSet<String> mHomePackages = new HashSet<String>();
120
121    private boolean mInitialized;
122    private boolean mShowUninstalled;
123    private LayoutPreference mHeader;
124    private Button mUninstallButton;
125    private boolean mUpdatedSysApp = false;
126    private TextView mAppVersion;
127    private Button mForceStopButton;
128    private Preference mNotificationPreference;
129    private Preference mStoragePreference;
130    private Preference mPermissionsPreference;
131    private Preference mLaunchPreference;
132    private Preference mDataPreference;
133
134    private boolean mDisableAfterUninstall;
135    // Used for updating notification preference.
136    private final NotificationBackend mBackend = new NotificationBackend();
137
138    private ChartData mChartData;
139    private INetworkStatsSession mStatsSession;
140
141    private Preference mBatteryPreference;
142
143    private BatteryStatsHelper mBatteryHelper;
144    private BatterySipper mSipper;
145
146    private boolean handleDisableable(Button button) {
147        boolean disableable = false;
148        // Try to prevent the user from bricking their phone
149        // by not allowing disabling of apps signed with the
150        // system cert and any launcher app in the system.
151        if (mHomePackages.contains(mAppEntry.info.packageName)
152                || Utils.isSystemPackage(mPm, mPackageInfo)) {
153            // Disable button for core system applications.
154            button.setText(R.string.disable_text);
155        } else if (mAppEntry.info.enabled) {
156            button.setText(R.string.disable_text);
157            disableable = true;
158        } else {
159            button.setText(R.string.enable_text);
160            disableable = true;
161        }
162
163        return disableable;
164    }
165
166    private void initUninstallButtons() {
167        final boolean isBundled = (mAppEntry.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
168        boolean enabled = true;
169        if (isBundled) {
170            enabled = handleDisableable(mUninstallButton);
171        } else {
172            if ((mPackageInfo.applicationInfo.flags & ApplicationInfo.FLAG_INSTALLED) == 0
173                    && mUserManager.getUsers().size() >= 2) {
174                // When we have multiple users, there is a separate menu
175                // to uninstall for all users.
176                enabled = false;
177            }
178            mUninstallButton.setText(R.string.uninstall_text);
179        }
180        // If this is a device admin, it can't be uninstalled or disabled.
181        // We do this here so the text of the button is still set correctly.
182        if (mDpm.packageHasActiveAdmins(mPackageInfo.packageName)) {
183            enabled = false;
184        }
185
186        // Home apps need special handling.  Bundled ones we don't risk downgrading
187        // because that can interfere with home-key resolution.  Furthermore, we
188        // can't allow uninstallation of the only home app, and we don't want to
189        // allow uninstallation of an explicitly preferred one -- the user can go
190        // to Home settings and pick a different one, after which we'll permit
191        // uninstallation of the now-not-default one.
192        if (enabled && mHomePackages.contains(mPackageInfo.packageName)) {
193            if (isBundled) {
194                enabled = false;
195            } else {
196                ArrayList<ResolveInfo> homeActivities = new ArrayList<ResolveInfo>();
197                ComponentName currentDefaultHome  = mPm.getHomeActivities(homeActivities);
198                if (currentDefaultHome == null) {
199                    // No preferred default, so permit uninstall only when
200                    // there is more than one candidate
201                    enabled = (mHomePackages.size() > 1);
202                } else {
203                    // There is an explicit default home app -- forbid uninstall of
204                    // that one, but permit it for installed-but-inactive ones.
205                    enabled = !mPackageInfo.packageName.equals(currentDefaultHome.getPackageName());
206                }
207            }
208        }
209
210        if (mAppControlRestricted) {
211            enabled = false;
212        }
213
214        mUninstallButton.setEnabled(enabled);
215        if (enabled) {
216            // Register listener
217            mUninstallButton.setOnClickListener(this);
218        }
219    }
220
221    /** Called when the activity is first created. */
222    @Override
223    public void onCreate(Bundle icicle) {
224        super.onCreate(icicle);
225
226        setHasOptionsMenu(true);
227        addPreferencesFromResource(R.xml.installed_app_details);
228
229        if (Utils.isBandwidthControlEnabled()) {
230            INetworkStatsService statsService = INetworkStatsService.Stub.asInterface(
231                    ServiceManager.getService(Context.NETWORK_STATS_SERVICE));
232            try {
233                mStatsSession = statsService.openSession();
234            } catch (RemoteException e) {
235                throw new RuntimeException(e);
236            }
237        } else {
238            removePreference(KEY_DATA);
239        }
240        mBatteryHelper = new BatteryStatsHelper(getActivity(), true);
241    }
242
243    @Override
244    protected int getMetricsCategory() {
245        return MetricsLogger.APPLICATIONS_INSTALLED_APP_DETAILS;
246    }
247
248    @Override
249    public void onResume() {
250        super.onResume();
251        if (mFinishing) {
252            return;
253        }
254        AppItem app = new AppItem(mAppEntry.info.uid);
255        app.addUid(mAppEntry.info.uid);
256        if (mStatsSession != null) {
257            getLoaderManager().restartLoader(LOADER_CHART_DATA,
258                    ChartDataLoader.buildArgs(getTemplate(getContext()), app),
259                    mDataCallbacks);
260        }
261        new BatteryUpdater().execute();
262    }
263
264    @Override
265    public void onPause() {
266        getLoaderManager().destroyLoader(LOADER_CHART_DATA);
267        super.onPause();
268    }
269
270    @Override
271    public void onDestroy() {
272        TrafficStats.closeQuietly(mStatsSession);
273
274        super.onDestroy();
275    }
276
277    public void onActivityCreated(Bundle savedInstanceState) {
278        super.onActivityCreated(savedInstanceState);
279        if (mFinishing) {
280            return;
281        }
282        handleHeader();
283
284        mNotificationPreference = findPreference(KEY_NOTIFICATION);
285        mNotificationPreference.setOnPreferenceClickListener(this);
286        mStoragePreference = findPreference(KEY_STORAGE);
287        mStoragePreference.setOnPreferenceClickListener(this);
288        mPermissionsPreference = findPreference(KEY_PERMISSION);
289        mPermissionsPreference.setOnPreferenceClickListener(this);
290        mDataPreference = findPreference(KEY_DATA);
291        if (mDataPreference != null) {
292            mDataPreference.setOnPreferenceClickListener(this);
293        }
294        mBatteryPreference = findPreference(KEY_BATTERY);
295        mBatteryPreference.setEnabled(false);
296        mBatteryPreference.setOnPreferenceClickListener(this);
297
298        mLaunchPreference = findPreference(KEY_LAUNCH);
299        if (mAppEntry.info != null) {
300            if ((mAppEntry.info.flags&ApplicationInfo.FLAG_INSTALLED) == 0 ||
301                    !mAppEntry.info.enabled) {
302                mLaunchPreference.setEnabled(false);
303            } else {
304                mLaunchPreference.setOnPreferenceClickListener(this);
305            }
306        } else {
307            mLaunchPreference.setEnabled(false);
308        }
309    }
310
311    private void handleHeader() {
312        mHeader = (LayoutPreference) findPreference(KEY_HEADER);
313
314        // Get Control button panel
315        View btnPanel = mHeader.findViewById(R.id.control_buttons_panel);
316        mForceStopButton = (Button) btnPanel.findViewById(R.id.right_button);
317        mForceStopButton.setText(R.string.force_stop);
318        mUninstallButton = (Button) btnPanel.findViewById(R.id.left_button);
319        mForceStopButton.setEnabled(false);
320    }
321
322    @Override
323    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
324        menu.add(0, UNINSTALL_UPDATES, 0, R.string.app_factory_reset)
325                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
326        menu.add(0, UNINSTALL_ALL_USERS_MENU, 1, R.string.uninstall_all_users_text)
327                .setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
328    }
329
330    @Override
331    public void onPrepareOptionsMenu(Menu menu) {
332        boolean showIt = true;
333        if (mUpdatedSysApp) {
334            showIt = false;
335        } else if (mAppEntry == null) {
336            showIt = false;
337        } else if ((mAppEntry.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
338            showIt = false;
339        } else if (mPackageInfo == null || mDpm.packageHasActiveAdmins(mPackageInfo.packageName)) {
340            showIt = false;
341        } else if (UserHandle.myUserId() != 0) {
342            showIt = false;
343        } else if (mUserManager.getUsers().size() < 2) {
344            showIt = false;
345        }
346        menu.findItem(UNINSTALL_ALL_USERS_MENU).setVisible(showIt);
347        mUpdatedSysApp = (mAppEntry.info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
348        menu.findItem(UNINSTALL_UPDATES).setVisible(mUpdatedSysApp && !mAppControlRestricted);
349    }
350
351    @Override
352    public boolean onOptionsItemSelected(MenuItem item) {
353        switch (item.getItemId()) {
354            case UNINSTALL_ALL_USERS_MENU:
355                uninstallPkg(mAppEntry.info.packageName, true, false);
356                return true;
357            case UNINSTALL_UPDATES:
358                showDialogInner(DLG_FACTORY_RESET, 0);
359                return true;
360        }
361        return false;
362    }
363
364    @Override
365    public void onActivityResult(int requestCode, int resultCode, Intent data) {
366        super.onActivityResult(requestCode, resultCode, data);
367        if (requestCode == REQUEST_UNINSTALL) {
368            if (mDisableAfterUninstall) {
369                mDisableAfterUninstall = false;
370                try {
371                    ApplicationInfo ainfo = getActivity().getPackageManager().getApplicationInfo(
372                            mAppEntry.info.packageName, PackageManager.GET_UNINSTALLED_PACKAGES
373                            | PackageManager.GET_DISABLED_COMPONENTS);
374                    if ((ainfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) == 0) {
375                        new DisableChanger(this, mAppEntry.info,
376                                PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER)
377                                .execute((Object)null);
378                    }
379                } catch (NameNotFoundException e) {
380                }
381            }
382            if (!refreshUi()) {
383                setIntentAndFinish(true, true);
384            }
385        }
386    }
387
388    // Utility method to set application label and icon.
389    private void setAppLabelAndIcon(PackageInfo pkgInfo) {
390        final View appSnippet = mHeader.findViewById(R.id.app_snippet);
391        appSnippet.setPaddingRelative(0, appSnippet.getPaddingTop(), 0,
392                appSnippet.getPaddingBottom());
393
394        ImageView icon = (ImageView) appSnippet.findViewById(R.id.app_icon);
395        mState.ensureIcon(mAppEntry);
396        icon.setImageDrawable(mAppEntry.icon);
397        // Set application name.
398        TextView label = (TextView) appSnippet.findViewById(R.id.app_name);
399        label.setText(mAppEntry.label);
400        // Version number of application
401        mAppVersion = (TextView) appSnippet.findViewById(R.id.app_summary);
402
403        if (pkgInfo != null && pkgInfo.versionName != null) {
404            mAppVersion.setVisibility(View.VISIBLE);
405            mAppVersion.setText(getActivity().getString(R.string.version_text,
406                    String.valueOf(pkgInfo.versionName)));
407        } else {
408            mAppVersion.setVisibility(View.INVISIBLE);
409        }
410    }
411
412    private boolean signaturesMatch(String pkg1, String pkg2) {
413        if (pkg1 != null && pkg2 != null) {
414            try {
415                final int match = mPm.checkSignatures(pkg1, pkg2);
416                if (match >= PackageManager.SIGNATURE_MATCH) {
417                    return true;
418                }
419            } catch (Exception e) {
420                // e.g. named alternate package not found during lookup;
421                // this is an expected case sometimes
422            }
423        }
424        return false;
425    }
426
427    @Override
428    protected boolean refreshUi() {
429        retrieveAppEntry();
430        if (mAppEntry == null) {
431            return false; // onCreate must have failed, make sure to exit
432        }
433
434        if (mPackageInfo == null) {
435            return false; // onCreate must have failed, make sure to exit
436        }
437
438        // Get list of "home" apps and trace through any meta-data references
439        List<ResolveInfo> homeActivities = new ArrayList<ResolveInfo>();
440        mPm.getHomeActivities(homeActivities);
441        mHomePackages.clear();
442        for (int i = 0; i< homeActivities.size(); i++) {
443            ResolveInfo ri = homeActivities.get(i);
444            final String activityPkg = ri.activityInfo.packageName;
445            mHomePackages.add(activityPkg);
446
447            // Also make sure to include anything proxying for the home app
448            final Bundle metadata = ri.activityInfo.metaData;
449            if (metadata != null) {
450                final String metaPkg = metadata.getString(ActivityManager.META_HOME_ALTERNATE);
451                if (signaturesMatch(metaPkg, activityPkg)) {
452                    mHomePackages.add(metaPkg);
453                }
454            }
455        }
456
457        checkForceStop();
458        setAppLabelAndIcon(mPackageInfo);
459        initUninstallButtons();
460
461        // Update the preference summaries.
462        Activity context = getActivity();
463        mStoragePreference.setSummary(AppStorageSettings.getSummary(mAppEntry, context));
464//        mPermissionsPreference.setSummary(AppPermissionSettings.getSummary(mAppEntry, context));
465        mLaunchPreference.setSummary(Utils.getLaunchByDeafaultSummary(mAppEntry, mUsbManager,
466                mPm, context));
467        mNotificationPreference.setSummary(getNotificationSummary(mAppEntry, context,
468                mBackend));
469        if (mDataPreference != null) {
470            mDataPreference.setSummary(getDataSummary());
471        }
472
473        updateBattery();
474
475        if (!mInitialized) {
476            // First time init: are we displaying an uninstalled app?
477            mInitialized = true;
478            mShowUninstalled = (mAppEntry.info.flags&ApplicationInfo.FLAG_INSTALLED) == 0;
479        } else {
480            // All other times: if the app no longer exists then we want
481            // to go away.
482            try {
483                ApplicationInfo ainfo = context.getPackageManager().getApplicationInfo(
484                        mAppEntry.info.packageName, PackageManager.GET_UNINSTALLED_PACKAGES
485                        | PackageManager.GET_DISABLED_COMPONENTS);
486                if (!mShowUninstalled) {
487                    // If we did not start out with the app uninstalled, then
488                    // it transitioning to the uninstalled state for the current
489                    // user means we should go away as well.
490                    return (ainfo.flags&ApplicationInfo.FLAG_INSTALLED) != 0;
491                }
492            } catch (NameNotFoundException e) {
493                return false;
494            }
495        }
496
497        return true;
498    }
499
500    private void updateBattery() {
501        if (mSipper != null) {
502            mBatteryPreference.setEnabled(true);
503            int dischargeAmount = mBatteryHelper.getStats().getDischargeAmount(
504                    BatteryStats.STATS_SINCE_CHARGED);
505            final int percentOfMax = (int) ((mSipper.totalPowerMah)
506                    / mBatteryHelper.getTotalPower() * dischargeAmount + .5f);
507            mBatteryPreference.setSummary(getString(R.string.battery_summary, percentOfMax));
508        } else {
509            mBatteryPreference.setEnabled(false);
510            mBatteryPreference.setSummary(getString(R.string.no_battery_summary));
511        }
512    }
513
514    private CharSequence getDataSummary() {
515        if (mChartData != null) {
516            long totalBytes = mChartData.detail.getTotalBytes();
517            Context context = getActivity();
518            return getString(R.string.data_summary_format,
519                    Formatter.formatFileSize(context, totalBytes),
520                    DateUtils.formatDateTime(context, mChartData.detail.getStart(),
521                            DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_ABBREV_MONTH));
522        }
523        return getString(R.string.computing_size);
524    }
525
526    @Override
527    protected AlertDialog createDialog(int id, int errorCode) {
528        switch (id) {
529            case DLG_DISABLE:
530                return new AlertDialog.Builder(getActivity())
531                        .setTitle(getActivity().getText(R.string.app_disable_dlg_title))
532                        .setMessage(getActivity().getText(R.string.app_disable_dlg_text))
533                        .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
534                            public void onClick(DialogInterface dialog, int which) {
535                                // Disable the app
536                                new DisableChanger(InstalledAppDetails.this, mAppEntry.info,
537                                        PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER)
538                                .execute((Object)null);
539                            }
540                        })
541                        .setNegativeButton(R.string.dlg_cancel, null)
542                        .create();
543            case DLG_SPECIAL_DISABLE:
544                return new AlertDialog.Builder(getActivity())
545                        .setTitle(getActivity().getText(R.string.app_special_disable_dlg_title))
546                        .setMessage(getActivity().getText(R.string.app_special_disable_dlg_text))
547                        .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
548                            public void onClick(DialogInterface dialog, int which) {
549                                // Clear user data here
550                                uninstallPkg(mAppEntry.info.packageName,
551                                        false, true);
552                            }
553                        })
554                        .setNegativeButton(R.string.dlg_cancel, null)
555                        .create();
556            case DLG_FORCE_STOP:
557                return new AlertDialog.Builder(getActivity())
558                        .setTitle(getActivity().getText(R.string.force_stop_dlg_title))
559                        .setMessage(getActivity().getText(R.string.force_stop_dlg_text))
560                        .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
561                            public void onClick(DialogInterface dialog, int which) {
562                                // Force stop
563                                forceStopPackage(mAppEntry.info.packageName);
564                            }
565                        })
566                        .setNegativeButton(R.string.dlg_cancel, null)
567                        .create();
568            case DLG_FACTORY_RESET:
569                return new AlertDialog.Builder(getActivity())
570                        .setTitle(getActivity().getText(R.string.app_factory_reset_dlg_title))
571                        .setMessage(getActivity().getText(R.string.app_factory_reset_dlg_text))
572                        .setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
573                            public void onClick(DialogInterface dialog, int which) {
574                                // Clear user data here
575                                uninstallPkg(mAppEntry.info.packageName,
576                                        false, false);
577                            }
578                        })
579                        .setNegativeButton(R.string.dlg_cancel, null)
580                        .create();
581        }
582        return null;
583    }
584
585    private void uninstallPkg(String packageName, boolean allUsers, boolean andDisable) {
586         // Create new intent to launch Uninstaller activity
587        Uri packageURI = Uri.parse("package:"+packageName);
588        Intent uninstallIntent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE, packageURI);
589        uninstallIntent.putExtra(Intent.EXTRA_UNINSTALL_ALL_USERS, allUsers);
590        startActivityForResult(uninstallIntent, REQUEST_UNINSTALL);
591        mDisableAfterUninstall = andDisable;
592    }
593
594    private void forceStopPackage(String pkgName) {
595        ActivityManager am = (ActivityManager)getActivity().getSystemService(
596                Context.ACTIVITY_SERVICE);
597        am.forceStopPackage(pkgName);
598        int userId = UserHandle.getUserId(mAppEntry.info.uid);
599        mState.invalidatePackage(pkgName, userId);
600        ApplicationsState.AppEntry newEnt = mState.getEntry(pkgName, userId);
601        if (newEnt != null) {
602            mAppEntry = newEnt;
603        }
604        checkForceStop();
605    }
606
607    private void updateForceStopButton(boolean enabled) {
608        if (mAppControlRestricted) {
609            mForceStopButton.setEnabled(false);
610        } else {
611            mForceStopButton.setEnabled(enabled);
612            mForceStopButton.setOnClickListener(InstalledAppDetails.this);
613        }
614    }
615
616    private void checkForceStop() {
617        if (mDpm.packageHasActiveAdmins(mPackageInfo.packageName)) {
618            // User can't force stop device admin.
619            updateForceStopButton(false);
620        } else if ((mAppEntry.info.flags&ApplicationInfo.FLAG_STOPPED) == 0) {
621            // If the app isn't explicitly stopped, then always show the
622            // force stop button.
623            updateForceStopButton(true);
624        } else {
625            Intent intent = new Intent(Intent.ACTION_QUERY_PACKAGE_RESTART,
626                    Uri.fromParts("package", mAppEntry.info.packageName, null));
627            intent.putExtra(Intent.EXTRA_PACKAGES, new String[] { mAppEntry.info.packageName });
628            intent.putExtra(Intent.EXTRA_UID, mAppEntry.info.uid);
629            intent.putExtra(Intent.EXTRA_USER_HANDLE, UserHandle.getUserId(mAppEntry.info.uid));
630            getActivity().sendOrderedBroadcastAsUser(intent, UserHandle.CURRENT, null,
631                    mCheckKillProcessesReceiver, null, Activity.RESULT_CANCELED, null, null);
632        }
633    }
634
635    private void startManagePermissionsActivity() {
636        // start new activity to manage app permissions
637        Intent intent = new Intent(Intent.ACTION_MANAGE_APP_PERMISSIONS);
638        intent.putExtra(Intent.EXTRA_PACKAGE_NAME, mAppEntry.info.packageName);
639        intent.putExtra(AppInfoWithHeader.EXTRA_HIDE_INFO_BUTTON, true);
640        try {
641            startActivity(intent);
642        } catch (ActivityNotFoundException e) {
643            Log.w(LOG_TAG, "No app can handle android.intent.action.MANAGE_APP_PERMISSIONS");
644        }
645    }
646
647    private void startAppInfoFragment(Class<?> fragment, CharSequence title) {
648        // start new fragment to display extended information
649        Bundle args = new Bundle();
650        args.putString(ARG_PACKAGE_NAME, mAppEntry.info.packageName);
651        args.putInt(ARG_PACKAGE_UID, mAppEntry.info.uid);
652        args.putBoolean(AppInfoWithHeader.EXTRA_HIDE_INFO_BUTTON, true);
653
654        SettingsActivity sa = (SettingsActivity) getActivity();
655        sa.startPreferencePanel(fragment.getName(), args, -1, title, this, SUB_INFO_FRAGMENT);
656    }
657
658    /*
659     * Method implementing functionality of buttons clicked
660     * @see android.view.View.OnClickListener#onClick(android.view.View)
661     */
662    public void onClick(View v) {
663        String packageName = mAppEntry.info.packageName;
664        if(v == mUninstallButton) {
665            if ((mAppEntry.info.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
666                if (mAppEntry.info.enabled) {
667                    if (mUpdatedSysApp) {
668                        showDialogInner(DLG_SPECIAL_DISABLE, 0);
669                    } else {
670                        showDialogInner(DLG_DISABLE, 0);
671                    }
672                } else {
673                    new DisableChanger(this, mAppEntry.info,
674                            PackageManager.COMPONENT_ENABLED_STATE_DEFAULT)
675                                    .execute((Object) null);
676                }
677            } else if ((mAppEntry.info.flags & ApplicationInfo.FLAG_INSTALLED) == 0) {
678                uninstallPkg(packageName, true, false);
679            } else {
680                uninstallPkg(packageName, false, false);
681            }
682        } else if (v == mForceStopButton) {
683            showDialogInner(DLG_FORCE_STOP, 0);
684            //forceStopPackage(mAppInfo.packageName);
685        }
686    }
687
688    @Override
689    public boolean onPreferenceClick(Preference preference) {
690        if (preference == mStoragePreference) {
691            startAppInfoFragment(AppStorageSettings.class, mStoragePreference.getTitle());
692        } else if (preference == mNotificationPreference) {
693            startAppInfoFragment(AppNotificationSettings.class,
694                    getString(R.string.app_notifications_title));
695        } else if (preference == mPermissionsPreference) {
696            startManagePermissionsActivity();
697        } else if (preference == mLaunchPreference) {
698            startAppInfoFragment(AppLaunchSettings.class, mLaunchPreference.getTitle());
699        } else if (preference == mDataPreference) {
700            Bundle args = new Bundle();
701            args.putString(DataUsageSummary.EXTRA_SHOW_APP_IMMEDIATE_PKG,
702                    mAppEntry.info.packageName);
703
704            SettingsActivity sa = (SettingsActivity) getActivity();
705            sa.startPreferencePanel(DataUsageSummary.class.getName(), args, -1,
706                    getString(R.string.app_data_usage), this, SUB_INFO_FRAGMENT);
707        } else if (preference == mBatteryPreference) {
708            BatteryEntry entry = new BatteryEntry(getActivity(), null, mUserManager, mSipper);
709            PowerUsageDetail.startBatteryDetailPage((SettingsActivity) getActivity(),
710                    mBatteryHelper, BatteryStats.STATS_SINCE_CHARGED, entry, true);
711        } else {
712            return false;
713        }
714        return true;
715    }
716
717    private static NetworkTemplate getTemplate(Context context) {
718        if (DataUsageSummary.hasReadyMobileRadio(context)) {
719            return NetworkTemplate.buildTemplateMobileWildcard();
720        }
721        if (DataUsageSummary.hasWifiRadio(context)) {
722            return NetworkTemplate.buildTemplateWifiWildcard();
723        }
724        return NetworkTemplate.buildTemplateEthernet();
725    }
726
727    public static CharSequence getNotificationSummary(AppEntry appEntry, Context context) {
728        return getNotificationSummary(appEntry, context, new NotificationBackend());
729    }
730
731    public static CharSequence getNotificationSummary(AppEntry appEntry, Context context,
732            NotificationBackend backend) {
733        AppRow appRow = backend.loadAppRow(context.getPackageManager(), appEntry.info);
734        return getNotificationSummary(appRow, context);
735    }
736
737    public static CharSequence getNotificationSummary(AppRow appRow, Context context) {
738        if (appRow.banned) {
739            return context.getString(R.string.notifications_disabled);
740        }
741        ArrayList<CharSequence> notifSummary = new ArrayList<>();
742        if (appRow.priority) {
743            notifSummary.add(context.getString(R.string.notifications_priority));
744        }
745        if (appRow.sensitive) {
746            notifSummary.add(context.getString(R.string.notifications_sensitive));
747        }
748        if (!appRow.peekable) {
749            notifSummary.add(context.getString(R.string.notifications_no_peeking));
750        }
751        switch (notifSummary.size()) {
752            case 3:
753                return context.getString(R.string.notifications_three_items,
754                        notifSummary.get(0), notifSummary.get(1), notifSummary.get(2));
755            case 2:
756                return context.getString(R.string.notifications_two_items,
757                        notifSummary.get(0), notifSummary.get(1));
758            case 1:
759                return notifSummary.get(0);
760            default:
761                return context.getString(R.string.notifications_enabled);
762        }
763    }
764
765    private class BatteryUpdater extends AsyncTask<Void, Void, Void> {
766        @Override
767        protected Void doInBackground(Void... params) {
768            mBatteryHelper.create((Bundle) null);
769            mBatteryHelper.refreshStats(BatteryStats.STATS_SINCE_CHARGED,
770                    mUserManager.getUserProfiles());
771            List<BatterySipper> usageList = mBatteryHelper.getUsageList();
772            final int N = usageList.size();
773            for (int i = 0; i < N; i++) {
774                BatterySipper sipper = usageList.get(i);
775                if (sipper.getUid() == mPackageInfo.applicationInfo.uid) {
776                    mSipper = sipper;
777                    break;
778                }
779            }
780            return null;
781        }
782
783        @Override
784        protected void onPostExecute(Void result) {
785            refreshUi();
786        }
787    }
788
789    private static class DisableChanger extends AsyncTask<Object, Object, Object> {
790        final PackageManager mPm;
791        final WeakReference<InstalledAppDetails> mActivity;
792        final ApplicationInfo mInfo;
793        final int mState;
794
795        DisableChanger(InstalledAppDetails activity, ApplicationInfo info, int state) {
796            mPm = activity.mPm;
797            mActivity = new WeakReference<InstalledAppDetails>(activity);
798            mInfo = info;
799            mState = state;
800        }
801
802        @Override
803        protected Object doInBackground(Object... params) {
804            mPm.setApplicationEnabledSetting(mInfo.packageName, mState, 0);
805            return null;
806        }
807    }
808
809    private final LoaderCallbacks<ChartData> mDataCallbacks = new LoaderCallbacks<ChartData>() {
810
811        @Override
812        public Loader<ChartData> onCreateLoader(int id, Bundle args) {
813            return new ChartDataLoader(getActivity(), mStatsSession, args);
814        }
815
816        @Override
817        public void onLoadFinished(Loader<ChartData> loader, ChartData data) {
818            mChartData = data;
819            mDataPreference.setSummary(getDataSummary());
820        }
821
822        @Override
823        public void onLoaderReset(Loader<ChartData> loader) {
824            mChartData = null;
825            mDataPreference.setSummary(getDataSummary());
826        }
827    };
828
829    private final BroadcastReceiver mCheckKillProcessesReceiver = new BroadcastReceiver() {
830        @Override
831        public void onReceive(Context context, Intent intent) {
832            updateForceStopButton(getResultCode() != Activity.RESULT_CANCELED);
833        }
834    };
835}
836
837
838