As the company's project needs to increase the memory management function, I wrote this simple example. The implementation function is very simple, that is, to obtain all processes running in the system, obtain the memory size occupied by each process and the remaining memory size of the system, and display it. Then, click each process to choose whether to close the process (the system process cannot be closed ), you can use the plus sign in the upper right corner to refresh the page! Do not give me your advice! Not to mention the source code directly. The source code is at the end!
Main Code of the main Activity:
Package com. zs. memorymanager; import java. util. arrayList; import java. util. list; import android. app. activityManager; import android. app. activityManager. runningAppProcessInfo; import android. app. alertDialog; import android. app. service; import android. content. dialogInterface; import android. content. dialogInterface. onClickListener; import android. OS. bundle; import android. OS. debug. memoryInfo; import android. OS. handler; import android. OS. message; import android. util. log; import android. view. menu; import android. view. view; import android. widget. adapterView; import android. widget. adapterView. onItemClickListener; import android. widget. imageButton; import android. widget. listView; import android. widget. textView; import android. widget. toast; public class MemoryManageActivity extends BaseAmsActivity implements android. view. view. onClickListener {/*** display the listView */private ListView mListView of the program list;/*** listView adapter */private AppMemoryListAdapter appAdapter; /* top bar */private View title; private ImageButton titleBack, titleRefresh; private TextView titleName;/*** Bottom Bar */private TextView freemory; private ActivityManager activityManager; /*** stores the process information of each running program */private List
ListProcess;/*** stores the name of each running program */private List
ListName;/*** stores the ID of each running process */private int [] pIds; /*** memory usage details of processes storing each running program */private MemoryInfo [] pMemoryInfos; private List appList; /*** help class for getting program information */private TaskInfo taskInfo; private MemoryHandler mHandler; private MemoryThread mThread; @ Overrideprotected void onCreate (Bundle savedInstanceState) {super. onCreate (savedInstanceState); setContentView (R. layout. activity_memory_manage); taskInfo = new TaskInfo (this); mHandler = new MemoryHandler (); mThread = new MemoryThread (); initView (); initListener (); mThread. start ();} private void initData () {// TODO Auto-generated method stubif (activityManager = null) {activityManager = (ActivityManager) getSystemService (ACTIVITY_SERVICE );} if (listProcess! = Null) {listProcess. clear (); listProcess = null;} listProcess = activityManager. getRunningAppProcesses (); // obtain the list of all processes running on the device if (pIds! = Null) {pIds = null;} pIds = getAllProcessId (listProcess); // obtain the id array pIdsif (listName! = Null) {listName. clear (); listName = null;} listName = getAllProcessName (listProcess); if (pMemoryInfos! = Null) {pMemoryInfos = null;} pMemoryInfos = activityManager. getProcessMemoryInfo (pIds); // obtain the memory information object array of each process in the process list based on the pIds array of the process. pMemoryInfosif (appList! = Null) {appList. clear (); appList = null;} appList = new ArrayList (); AppMemory app = null; for (int I = 0; I <pIds. length; I ++) {app = new AppMemory (pIds [I], listName. get (I), listProcess. get (I ). processName, taskInfo. checkAppType (listProcess. get (I ). processName), pMemoryInfos [I]); appList. add (app) ;}} private void initView () {title = (View) findViewById (R. id. title_memory); titleBack = (ImageButton) title. findViewById (R. id. title_left_bt); titleRefresh = (ImageButton) title. findViewById (R. id. title_right_bt); titleName = (TextView) title. findViewById (R. id. title_text); titleName. setText ("Memory Management"); mListView = (ListView) findViewById (R. id. lv_memory_manager_app); freeMemory = (TextView) findViewById (R. id. free_memory);} private void initListener () {titleBack. setOnClickListener (this); titleRefresh. setOnClickListener (this); mListView. setOnItemClickListener (new OnItemClickListener () {@ Overridepublic void onItemClick (AdapterView
Parent, View view, int position, long id) {// TODO Auto-generated method stubfinal AppMemory appMemory = appList. get (position); AlertDialog. builder builder = new AlertDialog. builder (MemoryManageActivity. this); if (appMemory. isSystemApp () {builder. setTitle (appMemory. getName () + "is a system program. If it is completely disabled, the system may be unstable? "); Builder. setPositiveButton ("off", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stubActivityManager am = (ActivityManager) MemoryManageActivity. this. getSystemService (Service. ACTIVITY_SERVICE); am. killBackgroundProcesses (appMemory. getPackageName (); mThread = new MemoryThread (); mThread. start ();}}). setNegativeButt On ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog. cancel (); // cancel the display dialog box});} else {builder. setTitle ("are you sure you want to close the program permanently" + appMemory. getName () +? "); Builder. setPositiveButton ("off", new DialogInterface. onClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stubActivityManager am = (ActivityManager) MemoryManageActivity. this. getSystemService (Service. ACTIVITY_SERVICE); am. killBackgroundProcesses (appMemory. getPackageName (); mThread = new MemoryThread (); mThread. start ();}}). setNegativeButton ("cancel", new OnClickListener () {@ Overridepublic void onClick (DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog. cancel (); // cancel the display dialog box});} builder. create (). show () ;}}) ;}private void refreshView () {if (appAdapter = null) {appAdapter = new AppMemoryListAdapter (MemoryManageActivity. this, appList);} appAdapter. refreshData (appList); mListView. setAdapter (appAdapter); appAdapter. notifyDataSetChanged (); displayBriefMemory ();} private int [] getAllProcessId (List
Processes) {int [] ids = new int [processes. size ()]; for (int I = 0; I <processes. size (); I ++) {ids [I] = processes. get (I ). pid;} return ids ;} /*** obtain the software name of all processes * @ author zhangshuo * @ date 2013-8-19 10:13:32 am * @ version * @ param listProcess * @ return */private List
GetAllProcessName (List
ListProcess) {List
ListName = new ArrayList
(); For (int I = 0; I <listProcess. size (); I ++) {String name = taskInfo. getAppName (listProcess. get (I ). processName) + taskInfo. getAppVersion (listProcess. get (I ). processName); listName. add (name);} return listName;}/*** obtain system memory information * @ author zhangshuo * @ date 11:08:35 * @ version */private void displayBriefMemory () {activityManager = (ActivityManager) getSystemService (ACTIVITY_SERVICE); Activity Manager. memoryInfo info = new ActivityManager. memoryInfo (); activityManager. getMemoryInfo (info); freeMemory. setText (Math. round (info. availMem/1024/1024 f) * 100)/100f + "MB"); Log. I ("Tag", "remaining system memory:" + (info. availMem> 10) + "k"); Log. I ("Tag", "whether the system is running in low memory:" + info. lowMemory); Log. I ("Tag", "when the remaining memory of the system is lower than" + info. threshold + "low memory running");} @ Overridepublic boolean onCreateOptionsMenu (Menu menu) {// Inflate the menu; th Is adds items to the action bar if it is present. getMenuInflater (). inflate (R. menu. memory_manage, menu); return true;} class MemoryThread extends Thread {@ Overridepublic void run () {// TODO Auto-generated method stubsuper. run (); initData (); Message msg = mHandler. obtainMessage (); msg. what = 1; mHandler. sendMessage (msg) ;}} class MemoryHandler extends Handler {@ Overridepublic void handleMessage (Message msg ){ // TODO Auto-generated method stubsuper. handleMessage (msg); if (msg. what = 1) {refreshView ();} else {Toast. makeText (MemoryManageActivity. this, "failed to get process information! ", Toast. LENGTH_SHORT ). show () ;}}@ Overridepublic void onClick (View v) {// TODO Auto-generated method stubswitch (v. getId () {case R. id. title_left_bt: {ActivityManager am = (ActivityManager) MemoryManageActivity. this. getSystemService (Service. ACTIVITY_SERVICE); for (int I = 0; I <appList. size (); I ++) {am. killBackgroundProcesses (appList. get (I ). getPackageName ();} mThread = new MemoryThread (); mThread. start (); break;} case R. id. title_right_bt: {mThread = new MemoryThread (); mThread. start (); break ;}}}}
AppMemory code:
Package com. zs. memorymanager; import android. OS. debug. memoryInfo;/*** object of each program * @ author zhangshuo * @ date 4:37:54 * @ version * description: */public class AppMemory {private int id; private String name; private String packageName; private boolean isSystemApp; private MemoryInfo memoryInfo; public AppMemory (int id, String name, String pName, boolean type, MemoryInfo info) {this. id = id; this. name = name; this. packageName = pName; this. isSystemApp = type; this. memoryInfo = info;} public int getId () {return id;} public void setId (int id) {this. id = id;} public String getName () {return name;} public void setName (String name) {this. name = name;} public boolean isSystemApp () {return isSystemApp;} public void setSystemApp (boolean isSystemApp) {this. isSystemApp = isSystemApp;} public MemoryInfo getMemoryInfo () {return memoryInfo;} public void setMemoryInfo (MemoryInfo memoryInfo) {this. memoryInfo = memoryInfo;} public String getPackageName () {return packageName;} public void setPackageName (String packageName) {this. packageName = packageName ;}}
AppMemoryListAdapter code:
Package com. zs. memorymanager; import java. lang. ref. softReference; import java. util. hashMap; import java. util. list; import android. content. context; import android. graphics. drawable. drawable; import android. view. layoutInflater; import android. view. view; import android. view. viewGroup; import android. widget. baseAdapter; import android. widget. imageView; import android. widget. textView;/*** @ author zhangshuo * @ date 4:35:51 * @ version * description: */public class AppMemoryListAdapter extends BaseAdapter {private HashMap
> ImageCache; // image object cache, key: IDprivate Context context of the image; private List appList; private TaskInfo taskInfo; public AppMemoryListAdapter (Context con, List apps) {this. context = con; this. appList = apps; this. imageCache = new HashMap
> (); This. taskInfo = new TaskInfo (con);} private Drawable getImageDrawable (AppMemory app) {String id = String. valueOf (app. getId (); String pName = app. getPackageName (); Drawable drawable = null; if (imageCache. containsKey (id) {SoftReference
SoftRef = imageCache. get (id); drawable = softRef. get (); if (drawable = null) {imageCache. remove (id); drawable = taskInfo. getAppIcon (pName); if (drawable! = Null) {imageCache. put (id, new SoftReference
(Drawable) ;}}} else {drawable = taskInfo. getAppIcon (pName); if (drawable! = Null) {imageCache. put (id, new SoftReference
(Drawable) ;}} System. out. println ("program name:" + app. getName () + "package name:" + pName); System. out. println ("Image:" + drawable); return drawable;} public void refreshData (List apps) {this. appList = apps;} @ Overridepublic int getCount () {// TODO Auto-generated method stubreturn appList. size () ;}@ Overridepublic Object getItem (int position) {// TODO Auto-generated method stubreturn appList. get (position) ;}@ Overridepublic long getItemId (int position) {// TODO Auto-generated method stubreturn position ;}@ Overridepublic View getView (int position, View convertView, ViewGroup parent) {// TODO Auto-generated method stubHolderView holder; if (null = convertView) {holder = new HolderView (); convertView = LayoutInflater. from (context ). inflate (R. layout. layout_app_memory_item, null); holder. ivAppIcon = (ImageView) convertView. findViewById (R. id. iv_app_icon); holder. tvAppName = (TextView) convertView. findViewById (R. id. TV _app_name); holder. tvAppType = (TextView) convertView. findViewById (R. id. TV _app_type); holder. tvAppDirty = (TextView) convertView. findViewById (R. id. TV _app_dirty); convertView. setTag (holder);} else {holder = (HolderView) convertView. getTag ();} AppMemory app = appList. get (position); holder. ivAppIcon. setImageDrawable (this. getImageDrawable (app); holder. tvAppName. setText (app. getName (); float privateDirty = 0.0f; privateDirty = Math. round (app. getMemoryInfo (). getTotalPrivateDirty ()/1024f) * 100)/100f; holder. tvAppDirty. setText (privateDirty + "MB"); System. out. println (app. getMemoryInfo (). getTotalPrivateDirty (); if (app. isSystemApp () {holder. tvAppType. setText ("system process"); holder. tvAppName. setTextColor (context. getResources (). getColor (R. color. red); holder. tvAppType. setTextColor (context. getResources (). getColor (R. color. red); holder. tvAppDirty. setTextColor (context. getResources (). getColor (R. color. red);} else {holder. tvAppType. setText ("User Process"); holder. tvAppName. setTextColor (context. getResources (). getColor (R. color. green); holder. tvAppType. setTextColor (context. getResources (). getColor (R. color. green); holder. tvAppDirty. setTextColor (context. getResources (). getColor (R. color. red);} return convertView;} class HolderView {ImageView ivAppIcon; TextView tvAppName; TextView tvAppType; TextView tvAppDirty ;}}
TaskInfo tool class code:
Package com. zs. memorymanager; import java. util. list; import android. content. context; import android. content. intent; import android. content. pm. applicationInfo; import android. content. pm. packageInfo; import android. content. pm. packageManager; import android. content. pm. resolveInfo; import android. content. pm. packageManager. nameNotFoundException; import android. graphics. drawable. drawable;/*** tool class for obtaining various program information * @ aut Hor zhangshuo * @ date 5:39:50 * @ version * description: */public class TaskInfo {Context context; PackageManager pm; public TaskInfo (Context context) {this. context = context; pm = context. getPackageManager ();}/*** determines whether the program is a system program based on the package name * indicates that the system program returns true, the user program returns false * @ author zhangshuo * @ date 3:33:38 * @ version * @ param packName * @ return */public boolean checkAppType (String pack Name) {boolean flag = true; ApplicationInfo info; try {info = pm. getApplicationInfo (packName, 0); if (info. flags & ApplicationInfo. FLAG_UPDATED_SYSTEM_APP )! = 0) {flag = false;} else if (info. flags & ApplicationInfo. FLAG_SYSTEM) = 0) {flag = false;} catch (NameNotFoundException e) {// TODO Auto-generated catch blocke. printStackTrace ();} return flag;}/** query the icon by package name */public Drawable getAppIcon (String packname) {try {ApplicationInfo = pm. getApplicationInfo (packname, 0); return info. loadIcon (pm);} catch (NameNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace (); return null ;}} public Drawable getAppIcon2 (String packName) {System. out. println ("what is the Start? "); Intent mainIntent = new Intent (Intent. ACTION_MAIN, null); mainIntent. addCategory (Intent. CATEGORY_LAUNCHER); // obtain all ResolveInfo objects through query. List
ResolveInfos = pm. queryIntentActivities (mainIntent, 0); System. out. println ("what is the situation? "); For (ResolveInfo reInfo: resolveInfos) {System. out. println ("package name comparison: reInfo packName:" + reInfo. activityInfo. packageName + "packName:" + packName); if (reInfo. activityInfo. packageName = packName) {System. out. println ("Get image:" + reInfo. loadIcon (pm); return reInfo. loadIcon (pm) ;}} return null;}/** get the program version */public String getAppVersion (String packname) {try {PackageInfo packinfo = pm. getPackageInfo (packname, 0); if (null = packinfo. versionName) {return "";} else {return packinfo. versionName ;}} catch (NameNotFoundException e) {e. printStackTrace (); return "" ;}}/** get the program name */public String getAppName (String packname) {try {ApplicationInfo info = pm. getApplicationInfo (packname, 0); if (null = info. loadLabel (pm ). toString () {return packname;} else {return info. loadLabel (pm ). toString () ;}} catch (NameNotFoundException e) {// TODO Auto-generated catch block e. printStackTrace (); return packname ;}/ ** get program permissions */public String [] getAppPremission (String packname) {try {PackageInfo packinfo = pm. getPackageInfo (packname, PackageManager. GET_PERMISSIONS); // get all permissions return packinfo. requestedPermissions;} catch (NameNotFoundException e) {e. printStackTrace (); return null ;}/ ** obtain the program signature */public String getAppSignature (String packname) {try {PackageInfo packinfo = pm. getPackageInfo (packname, PackageManager. GET_SIGNATURES); // get all permissions return packinfo. signatures [0]. toCharsString ();} catch (NameNotFoundException e) {e. printStackTrace (); return null ;}}}
:
: Http://download.csdn.net/detail/super_spy/7177513