Move process stats screen into memory screen.

- Move process stats from developer options to top level
   settings item.
 - Some minor UI changes to the top of the page
 - Major UI updates to detail page, now shows info with processes
   as pref categories and services as prefs, with a way to kill
   them (taken from Running Services page).
 - Some major refactorings in code, in attempt to make it more
   usable
 - Added color bar on per app basis to visualize the avg/max
   relationship
 - Updated the way avg is calculated across multiple entries in
   ProcStatsPackageEntry to be more accurate
 - Change the way max memory is calculated in
   ProcStatsPackageEntry to be less accurate but more useful

Bug: 19443802
Change-Id: Ia6aaabe42c415c50997a09bfb814a6f6e5731772
This commit is contained in:
Jason Monk
2015-03-25 09:46:30 -04:00
parent c5184ff1af
commit 2583fc1e06
23 changed files with 1330 additions and 783 deletions

View File

@@ -17,60 +17,77 @@
package com.android.settings.applications;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlertDialog;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ServiceInfo;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Process;
import android.preference.PreferenceCategory;
import android.text.format.Formatter;
import android.view.LayoutInflater;
import android.util.ArrayMap;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.android.internal.logging.MetricsLogger;
import com.android.settings.InstrumentedFragment;
import com.android.settings.AppHeader;
import com.android.settings.CancellablePreference;
import com.android.settings.CancellablePreference.OnCancelListener;
import com.android.settings.R;
import com.android.settings.Utils;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.applications.ProcStatsEntry.Service;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import static com.android.settings.Utils.prepareCustomPreferencesList;
public class ProcessStatsDetail extends SettingsPreferenceFragment
implements Button.OnClickListener {
public class ProcessStatsDetail extends InstrumentedFragment implements Button.OnClickListener {
private static final String TAG = "ProcessStatsDetail";
public static final int ACTION_FORCE_STOP = 1;
public static final String EXTRA_PACKAGE_ENTRY = "package_entry";
public static final String EXTRA_USE_USS = "use_uss";
public static final String EXTRA_MAX_WEIGHT = "max_weight";
public static final String EXTRA_WEIGHT_TO_RAM = "weight_to_ram";
public static final String EXTRA_TOTAL_TIME = "total_time";
public static final String EXTRA_MAX_MEMORY_USAGE = "max_memory_usage";
public static final String EXTRA_TOTAL_SCALE = "total_scale";
private static final String KEY_DETAILS_HEADER = "details_header";
private final ArrayMap<ComponentName, CancellablePreference> mServiceMap = new ArrayMap<>();
private PackageManager mPm;
private DevicePolicyManager mDpm;
private ProcStatsPackageEntry mApp;
private boolean mUseUss;
private double mMaxWeight;
private double mWeightToRam;
private long mTotalTime;
private long mOnePercentTime;
private View mRootView;
private TextView mTitleView;
private ViewGroup mTwoButtonsPanel;
private Button mForceStopButton;
private Button mReportButton;
private ViewGroup mProcessesParent;
private ViewGroup mServicesParent;
private LinearColorBar mColorBar;
private float mMaxMemoryUsage;
private double mTotalScale;
@Override
public void onCreate(Bundle icicle) {
@@ -81,21 +98,23 @@ public class ProcessStatsDetail extends InstrumentedFragment implements Button.O
mApp = args.getParcelable(EXTRA_PACKAGE_ENTRY);
mApp.retrieveUiData(getActivity(), mPm);
mUseUss = args.getBoolean(EXTRA_USE_USS);
mMaxWeight = args.getDouble(EXTRA_MAX_WEIGHT);
mWeightToRam = args.getDouble(EXTRA_WEIGHT_TO_RAM);
mTotalTime = args.getLong(EXTRA_TOTAL_TIME);
mMaxMemoryUsage = args.getFloat(EXTRA_MAX_MEMORY_USAGE);
mTotalScale = args.getDouble(EXTRA_TOTAL_SCALE);
mOnePercentTime = mTotalTime/100;
mServiceMap.clear();
createDetails();
}
@Override
public View onCreateView(
LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.process_stats_details, container, false);
prepareCustomPreferencesList(container, view, view, false);
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
mRootView = view;
createDetails();
return view;
AppHeader.createAppHeader(getActivity(),
mApp.mUiTargetApp != null ? mApp.mUiTargetApp.loadIcon(mPm) : new ColorDrawable(0),
mApp.mUiLabel, null);
}
@Override
@@ -107,56 +126,88 @@ public class ProcessStatsDetail extends InstrumentedFragment implements Button.O
public void onResume() {
super.onResume();
checkForceStop();
updateRunningServices();
}
@Override
public void onPause() {
super.onPause();
private void updateRunningServices() {
ActivityManager activityManager = (ActivityManager)
getActivity().getSystemService(Context.ACTIVITY_SERVICE);
List<RunningServiceInfo> runningServices =
activityManager.getRunningServices(Integer.MAX_VALUE);
// Set all services as not running, then turn back on the ones we find.
int N = mServiceMap.size();
for (int i = 0; i < N; i++) {
mServiceMap.valueAt(i).setCancellable(false);
}
N = runningServices.size();
for (int i = 0; i < N; i++) {
RunningServiceInfo runningService = runningServices.get(i);
if (!runningService.started && runningService.clientLabel == 0) {
continue;
}
if ((runningService.flags & RunningServiceInfo.FLAG_PERSISTENT_PROCESS) != 0) {
continue;
}
final ComponentName service = runningService.service;
CancellablePreference pref = mServiceMap.get(service);
if (pref != null) {
pref.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(CancellablePreference preference) {
stopService(service.getPackageName(), service.getClassName());
}
});
pref.setCancellable(true);
}
}
}
private void createDetails() {
final double percentOfWeight = (mApp.mBgWeight / mMaxWeight) * 100;
int appLevel = (int) Math.ceil(percentOfWeight);
String appLevelText = Formatter.formatShortFileSize(getActivity(),
(long)(mApp.mRunWeight * mWeightToRam));
// Set all values in the header.
mTitleView = (TextView) mRootView.findViewById(android.R.id.title);
mTitleView.setText(mApp.mUiLabel);
final TextView text1 = (TextView)mRootView.findViewById(android.R.id.text1);
text1.setText(appLevelText);
final ProgressBar progress = (ProgressBar) mRootView.findViewById(android.R.id.progress);
progress.setProgress(appLevel);
final ImageView icon = (ImageView) mRootView.findViewById(android.R.id.icon);
if (mApp.mUiTargetApp != null) {
icon.setImageDrawable(mApp.mUiTargetApp.loadIcon(mPm));
}
mTwoButtonsPanel = (ViewGroup)mRootView.findViewById(R.id.two_buttons_panel);
mForceStopButton = (Button)mRootView.findViewById(R.id.right_button);
mReportButton = (Button)mRootView.findViewById(R.id.left_button);
mForceStopButton.setEnabled(false);
mReportButton.setVisibility(View.INVISIBLE);
mProcessesParent = (ViewGroup)mRootView.findViewById(R.id.processes);
mServicesParent = (ViewGroup)mRootView.findViewById(R.id.services);
addPreferencesFromResource(R.xml.app_memory_settings);
fillProcessesSection();
fillServicesSection();
if (mServicesParent.getChildCount() <= 0) {
mServicesParent.setVisibility(View.GONE);
mRootView.findViewById(R.id.services_label).setVisibility(View.GONE);
}
LayoutPreference headerLayout = (LayoutPreference) findPreference(KEY_DETAILS_HEADER);
TextView avgUsed = (TextView) headerLayout.findViewById(R.id.memory_avg);
TextView maxUsed = (TextView) headerLayout.findViewById(R.id.memory_max);
avgUsed.setText(getString(R.string.memory_avg_desc,
Formatter.formatShortFileSize(getActivity(),
(long) (Math.max(mApp.mBgWeight, mApp.mRunWeight) * mWeightToRam))));
maxUsed.setText(getString(R.string.memory_max_desc,
Formatter.formatShortFileSize(getActivity(),
(long) (Math.max(mApp.mMaxBgMem, mApp.mMaxRunMem) * 1024 * mTotalScale))));
mForceStopButton = (Button) headerLayout.findViewById(R.id.right_button);
mReportButton = (Button) headerLayout.findViewById(R.id.left_button);
if (mApp.mEntries.get(0).mUid >= android.os.Process.FIRST_APPLICATION_UID) {
mForceStopButton.setEnabled(false);
mReportButton.setVisibility(View.INVISIBLE);
mForceStopButton.setText(R.string.force_stop);
mForceStopButton.setTag(ACTION_FORCE_STOP);
mForceStopButton.setOnClickListener(this);
mTwoButtonsPanel.setVisibility(View.VISIBLE);
} else {
mTwoButtonsPanel.setVisibility(View.GONE);
mReportButton.setVisibility(View.GONE);
mForceStopButton.setVisibility(View.GONE);
}
// TODO: Find way to share this code with ProcessStatsPreference.
boolean statsForeground = mApp.mRunWeight > mApp.mBgWeight;
float mAvgRatio = (statsForeground ? mApp.mAvgRunMem : mApp.mAvgBgMem) / mMaxMemoryUsage;
float mMaxRatio = (statsForeground ? mApp.mMaxRunMem : mApp.mMaxBgMem) / mMaxMemoryUsage
- mAvgRatio;
float mRemainingRatio = 1 - mAvgRatio - mMaxRatio;
mColorBar = (LinearColorBar) headerLayout.findViewById(R.id.color_bar);
Context context = getActivity();
mColorBar.setColors(context.getColor(R.color.memory_avg_use),
context.getColor(R.color.memory_max_use),
context.getColor(R.color.memory_remaining));
mColorBar.setRatios(mAvgRatio, mMaxRatio, mRemainingRatio);
}
public void onClick(View v) {
@@ -171,34 +222,6 @@ public class ProcessStatsDetail extends InstrumentedFragment implements Button.O
}
}
private void addPackageHeaderItem(ViewGroup parent, String packageName) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup item = (ViewGroup) inflater.inflate(R.layout.running_processes_item,
null);
parent.addView(item);
final ImageView icon = (ImageView) item.findViewById(R.id.icon);
TextView nameView = (TextView) item.findViewById(R.id.name);
TextView descriptionView = (TextView) item.findViewById(R.id.description);
try {
ApplicationInfo ai = mPm.getApplicationInfo(packageName, 0);
icon.setImageDrawable(ai.loadIcon(mPm));
nameView.setText(ai.loadLabel(mPm));
} catch (PackageManager.NameNotFoundException e) {
}
descriptionView.setText(packageName);
}
private void addDetailsItem(ViewGroup parent, CharSequence label, CharSequence value) {
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup item = (ViewGroup) inflater.inflate(R.layout.power_usage_detail_item_text,
null);
parent.addView(item);
TextView labelView = (TextView) item.findViewById(R.id.label);
TextView valueView = (TextView) item.findViewById(R.id.value);
labelView.setText(label);
valueView.setText(value);
}
final static Comparator<ProcStatsEntry> sEntryCompare = new Comparator<ProcStatsEntry>() {
@Override
public int compare(ProcStatsEntry lhs, ProcStatsEntry rhs) {
@@ -213,28 +236,35 @@ public class ProcessStatsDetail extends InstrumentedFragment implements Button.O
private void fillProcessesSection() {
final ArrayList<ProcStatsEntry> entries = new ArrayList<>();
for (int ie=0; ie<mApp.mEntries.size(); ie++) {
for (int ie = 0; ie < mApp.mEntries.size(); ie++) {
ProcStatsEntry entry = mApp.mEntries.get(ie);
if (entry.mPackage.equals("os")) {
entry.mLabel = entry.mName;
} else {
if (mApp.mEntries.size() > 1) {
entry.mLabel = getString(R.string.process_format, (ie + 1));
} else {
entry.mLabel = getString(R.string.process);
}
}
entries.add(entry);
}
Collections.sort(entries, sEntryCompare);
for (int ie=0; ie<entries.size(); ie++) {
for (int ie = 0; ie < entries.size(); ie++) {
ProcStatsEntry entry = entries.get(ie);
LayoutInflater inflater = getActivity().getLayoutInflater();
ViewGroup item = (ViewGroup) inflater.inflate(R.layout.process_stats_proc_details,
null);
mProcessesParent.addView(item);
((TextView)item.findViewById(R.id.processes_name)).setText(entry.mName);
addDetailsItem(item, getResources().getText(R.string.process_stats_ram_use),
Formatter.formatShortFileSize(getActivity(),
(long)(entry.mRunWeight * mWeightToRam)));
if (entry.mBgWeight > 0) {
addDetailsItem(item, getResources().getText(R.string.process_stats_bg_ram_use),
Formatter.formatShortFileSize(getActivity(),
(long)(entry.mBgWeight * mWeightToRam)));
}
addDetailsItem(item, getResources().getText(R.string.process_stats_run_time),
Utils.formatPercentage(entry.mRunDuration, mTotalTime));
PreferenceCategory processPref = new PreferenceCategory(getActivity());
processPref.setLayoutResource(R.layout.process_preference_category);
processPref.setTitle(entry.mLabel);
long memoryUse = Math.max((long)(entry.mRunWeight * mWeightToRam),
(long)(entry.mBgWeight * mWeightToRam));
String memoryString = Formatter.formatShortFileSize(getActivity(), memoryUse);
CharSequence frequency = ProcStatsPackageEntry.getFrequency(entry.mRunDuration
/ (float)mTotalTime, getActivity());
processPref.setSummary(
getString(R.string.memory_use_running_format, memoryString, frequency));
getPreferenceScreen().addPreference(processPref);
fillServicesSection(entry, processPref);
}
}
@@ -268,52 +298,97 @@ public class ProcessStatsDetail extends InstrumentedFragment implements Button.O
long mDuration;
}
private void fillServicesSection() {
private void fillServicesSection(ProcStatsEntry entry, PreferenceCategory processPref) {
final HashMap<String, PkgService> pkgServices = new HashMap<>();
final ArrayList<PkgService> pkgList = new ArrayList<>();
for (int ie=0; ie< mApp.mEntries.size(); ie++) {
ProcStatsEntry ent = mApp.mEntries.get(ie);
for (int ip=0; ip<ent.mServices.size(); ip++) {
String pkg = ent.mServices.keyAt(ip);
PkgService psvc = null;
ArrayList<ProcStatsEntry.Service> services = ent.mServices.valueAt(ip);
for (int is=services.size()-1; is>=0; is--) {
ProcStatsEntry.Service pent = services.get(is);
if (pent.mDuration >= mOnePercentTime) {
for (int ip = 0; ip < entry.mServices.size(); ip++) {
String pkg = entry.mServices.keyAt(ip);
PkgService psvc = null;
ArrayList<ProcStatsEntry.Service> services = entry.mServices.valueAt(ip);
for (int is=services.size()-1; is>=0; is--) {
ProcStatsEntry.Service pent = services.get(is);
if (pent.mDuration >= mOnePercentTime) {
if (psvc == null) {
psvc = pkgServices.get(pkg);
if (psvc == null) {
psvc = pkgServices.get(pkg);
if (psvc == null) {
psvc = new PkgService();
pkgServices.put(pkg, psvc);
pkgList.add(psvc);
}
psvc = new PkgService();
pkgServices.put(pkg, psvc);
pkgList.add(psvc);
}
psvc.mServices.add(pent);
psvc.mDuration += pent.mDuration;
}
psvc.mServices.add(pent);
psvc.mDuration += pent.mDuration;
}
}
}
Collections.sort(pkgList, sServicePkgCompare);
for (int ip=0; ip<pkgList.size(); ip++) {
for (int ip = 0; ip < pkgList.size(); ip++) {
ArrayList<ProcStatsEntry.Service> services = pkgList.get(ip).mServices;
Collections.sort(services, sServiceCompare);
if (pkgList.size() > 1) {
addPackageHeaderItem(mServicesParent, services.get(0).mPackage);
}
for (int is=0; is<services.size(); is++) {
ProcStatsEntry.Service service = services.get(is);
String label = service.mName;
int tail = label.lastIndexOf('.');
if (tail >= 0 && tail < (label.length()-1)) {
label = label.substring(tail+1);
}
String percentage = Utils.formatPercentage(service.mDuration, mTotalTime);
addDetailsItem(mServicesParent, label, percentage);
final ProcStatsEntry.Service service = services.get(is);
CharSequence label = getLabel(service);
CancellablePreference servicePref = new CancellablePreference(getActivity());
servicePref.setSelectable(false);
servicePref.setTitle(label);
servicePref.setSummary(ProcStatsPackageEntry.getFrequency(
service.mDuration / (float) mTotalTime, getActivity()));
processPref.addPreference(servicePref);
mServiceMap.put(new ComponentName(service.mPackage, service.mName), servicePref);
}
}
}
private CharSequence getLabel(Service service) {
// Try to get the service label, on the off chance that one exists.
try {
ServiceInfo serviceInfo = getPackageManager().getServiceInfo(
new ComponentName(service.mPackage, service.mName), 0);
if (serviceInfo.labelRes != 0) {
return serviceInfo.loadLabel(getPackageManager());
}
} catch (NameNotFoundException e) {
}
String label = service.mName;
int tail = label.lastIndexOf('.');
if (tail >= 0 && tail < (label.length()-1)) {
label = label.substring(tail+1);
}
return label;
}
private void stopService(String pkg, String name) {
try {
ApplicationInfo appInfo = getActivity().getPackageManager().getApplicationInfo(pkg, 0);
if ((appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
showStopServiceDialog(pkg, name);
return;
}
} catch (NameNotFoundException e) {
Log.e(TAG, "Can't find app " + pkg, e);
return;
}
doStopService(pkg, name);
}
private void showStopServiceDialog(final String pkg, final String name) {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.runningservicedetails_stop_dlg_title)
.setMessage(R.string.runningservicedetails_stop_dlg_text)
.setPositiveButton(R.string.dlg_ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
doStopService(pkg, name);
}
})
.setNegativeButton(R.string.dlg_cancel, null)
.show();
}
private void doStopService(String pkg, String name) {
getActivity().stopService(new Intent().setClassName(pkg, name));
updateRunningServices();
}
private void killProcesses() {
ActivityManager am = (ActivityManager)getActivity().getSystemService(
Context.ACTIVITY_SERVICE);