欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 一键清理、内存清理功能实现

程序员文章站 2024-02-19 21:41:58
360桌面、金山清理大师等都提供了一键清理、一键加速等功能,其实就是杀一些后台进程来达到释放内存的目的。 基本思路就是列出所有运行的进程,查看其重要值(running...

360桌面、金山清理大师等都提供了一键清理、一键加速等功能,其实就是杀一些后台进程来达到释放内存的目的。

基本思路就是列出所有运行的进程,查看其重要值(runningappprocessinfo.importance,值越大说明进程重要程度越低),可以设定一个阈值,如果该进程的重要值大于该阈值,就可以杀掉该进程。

进程的重要值有以下几个等级:

/**  
       * constant for {@link #importance}: this is a persistent process.  
       * only used when reporting to process observers.  
       * @hide  
       */  
      public static final int importance_persistent = 50;  
    
      /**  
       * constant for {@link #importance}: this process is running the  
       * foreground ui.  
       */  
      public static final int importance_foreground = 100;  
        
      /**  
       * constant for {@link #importance}: this process is running something  
       * that is actively visible to the user, though not in the immediate  
       * foreground.  
       */  
      public static final int importance_visible = 200;  
        
      /**  
       * constant for {@link #importance}: this process is running something  
       * that is considered to be actively perceptible to the user. an  
       * example would be an application performing background music playback.  
       */  
      public static final int importance_perceptible = 130;  
        
      /**  
       * constant for {@link #importance}: this process is running an  
       * application that can not save its state, and thus can't be killed  
       * while in the background.  
       * @hide  
       */  
      public static final int importance_cant_save_state = 170;  
        
      /**  
       * constant for {@link #importance}: this process is contains services  
       * that should remain running.  
       */  
      public static final int importance_service = 300;  
        
      /**  
       * constant for {@link #importance}: this process process contains  
       * background code that is expendable.  
       */  
      public static final int importance_background = 400;  
        
      /**  
       * constant for {@link #importance}: this process is empty of any  
       * actively running code.  
       */  
      public static final int importance_empty = 500;  

需要权限:

<uses-permission android:name="android.permission.kill_background_processes"/> 

具体操作代码如下:

package com.example.demo; 
 
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.content.pm.packagemanager; 
import android.content.pm.packagemanager.namenotfoundexception; 
import android.os.bundle; 
import android.util.log; 
import android.view.menu; 
import android.view.menuitem; 
import android.view.view; 
import android.widget.toast; 
 
public class cleanprocessactivity extends activity { 
 
  private static final string tag = "clean"; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_clean_process); 
  } 
  public void clean(view v){ 
    //to change body of implemented methods use file | settings | file templates.  
    activitymanager am = (activitymanager) getsystemservice(context.activity_service);  
    list<runningappprocessinfo> infolist = am.getrunningappprocesses();  
    list<activitymanager.runningserviceinfo> serviceinfos = am.getrunningservices(100);  
 
    long beforemem = getavailmemory(this);  
    log.d(tag, "-----------before memory info : " + beforemem);  
    int count = 0;  
    packagemanager pm = getpackagemanager(); 
     
    if (infolist != null) {  
      for (int i = 0; i < infolist.size(); ++i) {  
        runningappprocessinfo appprocessinfo = infolist.get(i);  
        log.d(tag, "process name : " + appprocessinfo.processname);  
        //importance 该进程的重要程度 分为几个级别,数值越低就越重要。  
        log.d(tag, "importance : " + appprocessinfo.importance);  
         
          
 
        // 一般数值大于runningappprocessinfo.importance_service的进程都长时间没用或者空进程了  
        // 一般数值大于runningappprocessinfo.importance_visible的进程都是非可见进程,也就是在后台运行着  
        if (appprocessinfo.importance > runningappprocessinfo.importance_visible) {  
          string[] pkglist = appprocessinfo.pkglist;  
          for (int j = 0; j < pkglist.length; ++j) {//pkglist 得到该进程下运行的包名  
            string appname = null; 
            try { 
              appname = (string) pm.getapplicationlabel(pm.getapplicationinfo(pkglist[j], 0));  
            } catch (namenotfoundexception e) { 
              // todo auto-generated catch block 
              e.printstacktrace(); 
            } 
            log.d(tag, "it will be killed, package name : " + pkglist[j]+" -- "+appname );  
            am.killbackgroundprocesses(pkglist[j]);  
            count++;  
          }  
        }  
 
      }  
    }  
 
    long aftermem = getavailmemory(this);  
    log.d(tag, "----------- after memory info : " + aftermem);  
    toast.maketext(this, "clear " + count + " process, "  
          + (aftermem - beforemem) + "m", toast.length_long).show();  
  } 
  private long getavailmemory(cleanprocessactivity cleanprocessactivity) { 
    // 获取android当前可用内存大小  
    activitymanager am = (activitymanager) getsystemservice(context.activity_service);  
    memoryinfo mi = new memoryinfo();  
    am.getmemoryinfo(mi);  
    //mi.availmem; 当前系统的可用内存  
    //return formatter.formatfilesize(context, mi.availmem);// 将获取的内存大小规格化  
    log.d(tag, "可用内存---->>>" + mi.availmem / (1024 * 1024));  
    return mi.availmem / (1024 * 1024);  
  }  
} 

注意:

我这里选择阈值是importance_visible级别的,也就是非可见的后台进程和服务会被杀掉(一些系统进程肯定除外)。
清理的效果跟金山清理大师和360桌面的一键清理效果差不多。

如果不想杀的太凶,可以选择importance_service级别,杀掉那些长时间没用或者空进程了,这个级别的清理力度不够大,达不到金山清理大师的效果。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。