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

简介: MainActivity如下: package cc.c;import java.io.BufferedReader;import java.

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>


PS:更好的方式请参见Android清理设备内存详细完整示例(一)

相关文章
|
9天前
|
Java 测试技术 Android开发
Android性能测试——发现和定位内存泄露和卡顿
本文详细介绍了Android应用性能测试中的内存泄漏与卡顿问题及其解决方案。首先,文章描述了使用MAT工具定位内存泄漏的具体步骤,并通过实例展示了如何分析Histogram图表和Dominator Tree。接着,针对卡顿问题,文章探讨了其产生原因,并提供了多种测试方法,包括GPU呈现模式分析、FPS Meter软件测试、绘制圆点计数法及Android Studio自带的GPU监控功能。最后,文章给出了排查卡顿问题的四个方向,帮助开发者优化应用性能。
36 4
Android性能测试——发现和定位内存泄露和卡顿
|
7天前
|
监控 算法 数据可视化
深入解析Android应用开发中的高效内存管理策略在移动应用开发领域,Android平台因其开放性和灵活性备受开发者青睐。然而,随之而来的是内存管理的复杂性,这对开发者提出了更高的要求。高效的内存管理不仅能够提升应用的性能,还能有效避免因内存泄漏导致的应用崩溃。本文将探讨Android应用开发中的内存管理问题,并提供一系列实用的优化策略,帮助开发者打造更稳定、更高效的应用。
在Android开发中,内存管理是一个绕不开的话题。良好的内存管理机制不仅可以提高应用的运行效率,还能有效预防内存泄漏和过度消耗,从而延长电池寿命并提升用户体验。本文从Android内存管理的基本原理出发,详细讨论了几种常见的内存管理技巧,包括内存泄漏的检测与修复、内存分配与回收的优化方法,以及如何通过合理的编程习惯减少内存开销。通过对这些内容的阐述,旨在为Android开发者提供一套系统化的内存优化指南,助力开发出更加流畅稳定的应用。
19 0
|
26天前
|
缓存 监控 Android开发
构建高效的Android应用:从内存优化到用户体验
【7月更文挑战第57天】 在竞争激烈的移动市场中,一个高效、流畅且具有优秀用户体验的Android应用是成功的关键。本文将深入探讨如何通过内存管理和界面优化来提升应用性能,包括实用的编程技巧和策略,以及如何利用Android系统提供的工具进行调试和性能监控。读者将学习到如何识别和解决常见的性能瓶颈,以及如何设计出既美观又实用的用户界面。
|
API 网络安全 Android开发
Android 设备唯一标识(适配Android版本)
Android 设备唯一标识(适配Android版本)
928 0
Android 设备唯一标识(适配Android版本)
|
存储 安全 搜索推荐
2022Android设备唯一标识(AndroidID,OAID等 )
2022Android设备唯一标识(AndroidID,OAID等 )
3409 0
2022Android设备唯一标识(AndroidID,OAID等 )
|
存储 API Android开发
Android设备唯一标识的获取和构造
设备唯一标识对于app开发是很重要的一个点,主要应用于统计,有时也应用于业务。 Android平台提供了很多获取唯一标识的API,但都不是很稳定。 一、获取唯一标识 Android开发者网站上的一篇文章Identifying App Installations给出了几种获取方式; 中文博文也有很多,这是其中一篇 Android获取设备唯一ID的几种方式。
1816 0
|
算法 Android开发 数据安全/隐私保护
Android设备的唯一标识
Android设备的唯一标识 IMEI 权限 获取IMEI /** * 获取IMEI * * @return IMEI */ private String ...
986 0
|
6天前
|
Android开发 开发者 Kotlin
探索安卓开发中的新特性
【9月更文挑战第14天】本文将引导你深入理解安卓开发领域的一些最新特性,并为你提供实用的代码示例。无论你是初学者还是经验丰富的开发者,这篇文章都会给你带来新的启示和灵感。让我们一起探索吧!
|
1天前
|
Android开发 开发者
安卓开发中的自定义视图:从入门到精通
【9月更文挑战第19天】在安卓开发的广阔天地中,自定义视图是一块充满魔力的土地。它不仅仅是代码的堆砌,更是艺术与科技的完美结合。通过掌握自定义视图,开发者能够打破常规,创造出独一无二的用户界面。本文将带你走进自定义视图的世界,从基础概念到实战应用,一步步展示如何用代码绘出心中的蓝图。无论你是初学者还是有经验的开发者,这篇文章都将为你打开一扇通往创意和效率的大门。让我们一起探索自定义视图的秘密,将你的应用打造成一件艺术品吧!
18 10