由于公司项目需要,需要增加内存管理的功能,于是写了这个简单例子,实现的功能很简单,就是获取系统中正在运行的所有进程,并获取到每个进程所占的内存大小,以及系统剩余内存大小,并展示出来,然后通过点击每个进程可以选择是否要关闭进程(系统进程无法关闭),右上角的加号可以实现刷新的功能!高手勿喷,请大家不吝赐教!不多说直接上源码,源码在最后!
主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<RunningAppProcessInfo> listProcess;
/**
* 存放每个正在运行的程序的名称
*/
private List<String> listName;
/**
* 存放每个正在运行的程勋的进程ID
*/
private int[] pIds;
/**
* 存放每个正在运行的程序的进程的内存占用详情
*/
private MemoryInfo[] pMemoryInfos;
private List<AppMemory> appList;
/**
* 获取程序信息的帮助类
*/
private TaskInfo taskInfo;
private MemoryHandler mHandler;
private MemoryThread mThread;
@Override
protected 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 stub
if(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数组pIds
if(listName != null){
listName.clear();
listName = null;
}
listName = getAllProcessName(listProcess);
if(pMemoryInfos != null){
pMemoryInfos = null;
}
pMemoryInfos = activityManager.getProcessMemoryInfo(pIds);//根据进程的pIds数组获取进程列表中的各进程的内存信息对象数组pMemoryInfos
if(appList != null){
appList.clear();
appList = null;
}
appList = new ArrayList<AppMemory>();
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() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
final 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() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ActivityManager am = (ActivityManager) MemoryManageActivity.this.getSystemService(Service.ACTIVITY_SERVICE);
am.killBackgroundProcesses(appMemory.getPackageName());
mThread = new MemoryThread();
mThread.start();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel() ; // 取消显示对话框
}
});
}else{
builder.setTitle("确定要彻底关闭程序" + appMemory.getName() + " 吗?") ;
builder.setPositiveButton("关闭", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
ActivityManager am = (ActivityManager) MemoryManageActivity.this.getSystemService(Service.ACTIVITY_SERVICE);
am.killBackgroundProcesses(appMemory.getPackageName());
mThread = new MemoryThread();
mThread.start();
}
}).setNegativeButton("取消", new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.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<RunningAppProcessInfo> 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<String> getAllProcessName(List<RunningAppProcessInfo> listProcess){
List<String> listName = new ArrayList<String>();
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+"时就看成低内存运行");
}
@Override
public 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{
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
initData();
Message msg = mHandler.obtainMessage();
msg.what = 1;
mHandler.sendMessage(msg);
}
}
class MemoryHandler extends Handler{
@Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what == 1){
refreshView();
}else{
Toast.makeText(MemoryManageActivity.this, "获取进程信息失败!", Toast.LENGTH_SHORT).show();
}
}
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(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;
}
}
}
}
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<String, SoftReference<Drawable>> imageCache;// 图片对象缓存,key:图片的ID
private Context context;
private List<AppMemory> appList;
private TaskInfo taskInfo;
public AppMemoryListAdapter(Context con, List<AppMemory> apps){
this.context = con;
this.appList = apps;
this.imageCache = new HashMap<String, SoftReference<Drawable>>();
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<Drawable> 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>(drawable));
}
}
}else{
drawable = taskInfo.getAppIcon(pName);
if(drawable != null){
imageCache.put(id, new SoftReference<Drawable>(drawable));
}
}
System.out.println("程序名: " + app.getName() + " 包名: " + pName);
System.out .println("图片: " + drawable);
return drawable;
}
public void refreshData(List<AppMemory> apps){
this.appList = apps;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return appList.size();
}
@Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return appList.get(position);
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
HolderView 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 block
e.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<ResolveInfo> 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;
}
}
}
截图:
完整Demo源码下载地址:http://download.youkuaiyun.com/detail/super_spy/7177513