首页 > 代码库 > Android清理设备内存详细完整示例

Android清理设备内存详细完整示例

MainActivity如下:
package cc.c;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
/**
 * Demo描述:
 * 清理手机内存
 * 
 * 参考资料:
 * 1 http://blog.30c.org/1816.html
 * 2 http://www.cnblogs.com/helloandroid/archive/2011/10/14/2212334.html
 *   Thank you very much
 * 
 * 注意权限:
 * <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" />
 * 
 */
public class MainActivity extends Activity {
	private TextView mTotalMemoryTextView;
	private TextView mAvailMemoryTextView;
	private Button mCleanButton;
	private TextView mCleanInfoTextView;
	private ActivityManager mActivityManager;
	private StringBuffer mCleanInfoStringBuffer;
	private long availMemory;
	private long totalMemory;
	private List<RunningAppProcessInfo> mRunningAppProcessInfoList;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		init();
	}

	private void init() {
		
		mCleanInfoStringBuffer = new StringBuffer();
		mActivityManager=(ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
		
		mTotalMemoryTextView = (TextView) findViewById(R.id.totalMemoryTextView);
		mAvailMemoryTextView = (TextView) findViewById(R.id.availMemoryTextView);
		mCleanInfoTextView = (TextView) findViewById(R.id.cleanInfoTextView);
		mCleanButton = (Button) findViewById(R.id.cleanButton);
		
		totalMemory = getTotalMemory();
		availMemory = getAvailMemory();
		mTotalMemoryTextView.setText(totalMemory + "MB");
		mAvailMemoryTextView.setText(availMemory + "MB");
	
		mCleanButton.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				RunningAppProcessInfo runningAppProcessInfo=null;
				mRunningAppProcessInfoList= mActivityManager.getRunningAppProcesses();
				//List<ActivityManager.RunningServiceInfo> serviceInfos = mActivityManager.getRunningServices(100);

				if (mRunningAppProcessInfoList != null) {
					for (int i = 0; i < mRunningAppProcessInfoList.size(); ++i) {
						runningAppProcessInfo= mRunningAppProcessInfoList.get(i);
						// 一般数值大于RunningAppProcessInfo.IMPORTANCE_SERVICE
						// 的进程即为长时间未使用进程或者空进程
						// 一般数值大于RunningAppProcessInfo.IMPORTANCE_VISIBLE
						// 的进程都是非可见进程,即在后台运行
						if (runningAppProcessInfo.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
							String[] pkgList = runningAppProcessInfo.pkgList;
							for (int j = 0; j < pkgList.length; ++j) {
								mActivityManager.killBackgroundProcesses(pkgList[j]);
								mCleanInfoStringBuffer.append(pkgList[j] + " is killed...\n");
								mCleanInfoTextView.setText(mCleanInfoStringBuffer.toString());
							}
						}

					}
				}
                //再次获得剩余内存以计算清理值
				mCleanInfoStringBuffer.append("共清理:"+(getAvailMemory() - availMemory) + "MB");
				mCleanInfoTextView.setText(mCleanInfoStringBuffer.toString());
				mAvailMemoryTextView.setText(getAvailMemory() + "MB");
			}
		});
	}

	

	private long getTotalMemory() {
		//系统的内存信息文件
		String filePath = "/proc/meminfo";
		String lineString;
		String[] stringArray;
		long totalMemory = 0;
		try {
			FileReader fileReader = new FileReader(filePath);
			BufferedReader bufferedReader = new BufferedReader(fileReader,1024 * 8);
			//读取meminfo第一行,获取系统总内存大小
			lineString = bufferedReader.readLine();
			//按照空格拆分
			stringArray = lineString.split("\\s+");
			//获得系统总内存,单位KB
			totalMemory = Integer.valueOf(stringArray[1]).intValue();
			bufferedReader.close();
			System.out.println("------> lineString=" + lineString+ ",stringArray[0]=" + stringArray[0] + 
					           ",stringArray[1]="+ stringArray[1] + ",stringArray[2]=" + stringArray[2]);
		} catch (IOException e) {
		}
		return totalMemory / 1024;
	}
	
	

	private long getAvailMemory() {
		MemoryInfo memoryInfo = new MemoryInfo();
		mActivityManager.getMemoryInfo(memoryInfo);
		return memoryInfo.availMem / (1024 * 1024);
	}


}

main.xml如下:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/totalTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="系统内存:"
        android:textSize="25sp"
        android:textColor="#1cf109" />

    <TextView
        android:id="@+id/totalMemoryTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@id/totalTextView"
        android:textSize="25sp"
        android:textColor="#1cf109" />

    <TextView
        android:id="@+id/availTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/totalTextView"
        android:text="可用内存:"
        android:textSize="25sp"
        android:textColor="#5c0169" />

    <TextView
        android:id="@+id/availMemoryTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/totalTextView"
        android:layout_toRightOf="@id/availTextView"
        android:textSize="25sp"
        android:textColor="#5c0169" />

    <Button
        android:id="@+id/cleanButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/availMemoryTextView"
        android:textSize="25sp"
        android:text="清理内存" />

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/cleanButton" >

        <TextView
            android:id="@+id/cleanInfoTextView"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content" />
    </ScrollView>

</RelativeLayout>