Android 簡單的記憶體管理器

來源:互聯網
上載者:User

由於公司項目需要,需要增加記憶體管理的功能,於是寫了這個簡單例子,實現的功能很簡單,就是擷取系統中正在啟動並執行所有進程,並擷取到每個進程所佔的記憶體大小,以及系統剩餘記憶體大小,並展示出來,然後通過點擊每個進程可以選擇是否要關閉進程(系統進程無法關閉),右上方的加號可以實現重新整理的功能!高手勿噴,請大家不吝賜教!不多說直接上源碼,源碼在最後!

主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{/** * 顯示程式列表的listView */private ListView mListView;/** * listView的適配器 */private AppMemoryListAdapter appAdapter;/** * 頂欄 */private View title;private ImageButton titleBack, titleRefresh;private TextView titleName;/** * 底欄 */private TextView freeMemory;private ActivityManager activityManager;/** * 存放每個正在啟動並執行程式的進程的資訊 */private List listProcess;/** * 存放每個正在啟動並執行程式的名稱 */private List listName;/** * 存放每個正在啟動並執行程勳的進程ID */private int[] pIds;/** * 存放每個正在啟動並執行程式的進程的記憶體佔用詳情 */private MemoryInfo[] pMemoryInfos;private List appList;/** * 擷取程式資訊的協助類 */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();//擷取裝置中所有啟動並執行進程列表if(pIds != null){pIds = null;;}pIds = getAllProcessId(listProcess);//更具進程列表獲得進程的id數組pIdsif(listName != null){listName.clear();listName = null;}listName = getAllProcessName(listProcess);if(pMemoryInfos != null){pMemoryInfos = null;}pMemoryInfos = activityManager.getProcessMemoryInfo(pIds);//根據進程的pIds數組擷取進程列表中的各進程的記憶體資訊對象數組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("記憶體管理");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() + "是系統程式,徹底關閉可能造成系統不穩定?") ;builder.setPositiveButton("關閉", 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("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog.cancel() ;  // 取消顯示對話方塊}});}else{builder.setTitle("確定要徹底關閉程式" + appMemory.getName() + " 嗎?") ;builder.setPositiveButton("關閉", 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("取消", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// TODO Auto-generated method stubdialog.cancel() ;  // 取消顯示對話方塊}});}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;}/** * 擷取所有進程的軟體名稱 * @author zhangshuo * @date 2013-8-19 上午10:13:32 * @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;}/** * 擷取系統的記憶體資訊 * @author zhangshuo * @date 2013-8-15 上午11:08:35 * @version */private void displayBriefMemory() { activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE); ActivityManager.MemoryInfo info = new ActivityManager.MemoryInfo(); activityManager.getMemoryInfo(info); freeMemory.setText(Math.round((info.availMem/1024/1024f) * 100)/100f + "MB");Log.i("Tag","系統剩餘記憶體:"+(info.availMem >> 10)+"k"); Log.i("Tag","系統是否處於低記憶體運行:"+info.lowMemory);Log.i("Tag","當系統剩餘記憶體低於"+info.threshold+"時就看成低記憶體運行");} @Overridepublic boolean onCreateOptionsMenu(Menu menu) {// Inflate the menu; this 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, "擷取進程資訊失敗!", 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代碼:

package com.zs.memorymanager;import android.os.Debug.MemoryInfo;/** * 每個程式的實體物件 *@author zhangshuo *@date 2013-8-16 下午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代碼:

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 2013-8-16 下午4:35:51 *@version * description: */public class AppMemoryListAdapter extends BaseAdapter{private HashMap> imageCache;// 圖片對象緩衝,key:圖片的IDprivate Context context;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("程式名: " + app.getName() + " 包名: " + pName);System.out .println("圖片: " + 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("系統進程");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("使用者進程");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工具類代碼:

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;/** * 擷取程式的各種資訊的工具類 *@author zhangshuo *@date 2013-8-16 下午5:39:50 *@version * description: */public class TaskInfo {      Context context ;      PackageManager pm ;      public TaskInfo(Context context) {          this.context = context;          pm = context.getPackageManager();      }         /**     * 根據包名判斷程式是否是系統程式     * 是系統程式返回true,使用者程式返回false     * @author zhangshuo     * @date 2013-8-19 下午3:33:38     * @version       *@param packName     *@return     */    public boolean checkAppType(String packName){    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;    }        /*      * 根據包名 查詢 表徵圖      */      public Drawable getAppIcon(String packname){        try {               ApplicationInfo info = 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("什麼情況Start?");    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);// 通過查詢,獲得所有ResolveInfo對象.List resolveInfos = pm.queryIntentActivities(mainIntent, 0);System.out.println("什麼情況?");for (ResolveInfo reInfo : resolveInfos) {System.out.println("包名對比:reInfo packName:" + reInfo.activityInfo.packageName + " packName: " + packName);if(reInfo.activityInfo.packageName == packName){System.out.println("獲得圖片: " + reInfo.loadIcon(pm));return reInfo.loadIcon(pm);}}return null;    }        /*      *擷取程式的版本號碼        */      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 "";              }      }              /*      * 擷取程式的名字       */      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;              }      }      /*      * 擷取程式的許可權      */      public String[] getAppPremission(String packname){            try {                PackageInfo packinfo =    pm.getPackageInfo(packname, PackageManager.GET_PERMISSIONS);                //擷取到所有的許可權                  return packinfo.requestedPermissions;                } catch (NameNotFoundException e) {                  e.printStackTrace();                  return null;              }      }                  /*      * 擷取程式的簽名       */      public String getAppSignature(String packname){            try {                PackageInfo packinfo =    pm.getPackageInfo(packname, PackageManager.GET_SIGNATURES);                //擷取到所有的許可權                  return packinfo.signatures[0].toCharsString();                } catch (NameNotFoundException e) {                  e.printStackTrace();                  return null;              }      }  }  

:http://download.csdn.net/detail/super_spy/7177513

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.