Run garbage collector - Android java.lang

Android examples for java.lang:Runtime

Description

Run garbage collector

Demo Code

import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.Context;

public class Main {

  public static int gc(Context cxt) {
    // long i = getDeviceUsableMemory(cxt);
    int count = 0;
    ActivityManager am = (ActivityManager) cxt.getSystemService(Context.ACTIVITY_SERVICE);
    List<RunningServiceInfo> serviceList = am.getRunningServices(100);
    if (serviceList != null)
      for (RunningServiceInfo service : serviceList) {
        if (service.pid == android.os.Process.myPid())
          continue;
        try {// ww w  .ja  v  a  2 s.c  o m
          android.os.Process.killProcess(service.pid);
          count++;
        } catch (Exception e) {
          e.getStackTrace();
          continue;
        }
      }

    List<RunningAppProcessInfo> processList = am.getRunningAppProcesses();
    if (processList != null)
      for (RunningAppProcessInfo process : processList) {
        if (process.importance > RunningAppProcessInfo.IMPORTANCE_VISIBLE) {
          String[] pkgList = process.pkgList;
          for (String pkgName : pkgList) {
            try {
              am.killBackgroundProcesses(pkgName);
              count++;
            } catch (Exception e) {
              e.getStackTrace();
              continue;
            }
          }
        }
      }
    return count;
  }

}

Related Tutorials