源码解释: 让系统立即终止与给定程序包关联的所有后台进程。这与内核杀死那些进程以回收内存的过程相同。系统会在将来根据需要重新启动这些过程。
后台自动清理实现
通过自定义一个服务或者悬浮窗在后台运行,获取当前运行前台运行的包名,用一个集合recentList进行存储,当数量达到多少时执行清理任务
List recentList = new ArrayList<>(10); //后台包名缓存列表
/**
-
执行桌面后台启动任务清理
-
@author lhw
*/
private synchronized void clearRecentTask() {
Log.w(TAG, “clearRecnetTask recentList==” + recentList.toString());
final ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
long beforeMem = getAvailMemory(am);
Log.w(TAG, "-----------before memory info : " + beforeMem);
if (recentList != null && recentList.size() >= 5) {
TaskScheduler.ioHandler().post(new Runnable() {
@Override
public void run() {
int count = 0;
for (int i = 0; i < recentList.size() - 1; i++) {
if (!recentList.get(i).equals(“com.android.systemui”)) {
try {
am.killBackgroundProcesses(recentList.get(i));
recentList.remove(i);
Log.w(TAG, "It will be killed, package name : " + recentList.get(i));
} catch (Exception e) {
Log.e(TAG, "Exception clearMemory killBackgroundProcesses " + e.getMessage());
}
}
count++;
}
Log.w(TAG, "----------- after memory count : " + count);
}
});
}
long afterMem = getAvailMemory(am);
Log.w(TAG, "----------- after memory info : " + afterMem);
}
//获取可用内存大小
private long getAvailMemory(ActivityManager am) {
// 获取android当前可用内存大小
ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
am.getMemoryInfo(mi);
Log.d(TAG, “可用内存---->>>” + mi.availMem / (1024 * 1024));
return mi.availMem / (1024 * 1024);
}
-
当前运行App包名获取方式
-
第一种通过定义一个辅助服务 AccessibilityService 中 AccessibilityEvent 的getPackageName 获取
-
第二种通过 UsageStatsManager获取当前运行包名,要跳转设置去申请android.permission.PACKAGE_USAGE_STATS权限
public static String getTopPackageName(Context context) {
String topActivityPackageName;
ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
final UsageStatsManager mUsageStatsManager = (UsageStatsManager) context.getSystemService(Service.USAGE_STATS_SERVICE);
long endTime = System.currentTimeMillis();
long beginTime = endTime - 60301000; // 1000 * 3;// * 60 * 2;
UsageEvents usageEvents = mUsageStatsManager.queryEvents(beginTime, endTime);
if (usageEvents == null || !usageEvents.hasNextEvent()) {
Log.w(“usageEvents==null”);
return null;
}
ComponentName comp = null;
String pkgName = null;
String clsName = null;
UsageEvents.Event event = new UsageEvents.Event();
long prevTime = 0;
while(usageEvents.getNextEvent(event)) {
if (event.getEventType() == event.MOVE_TO_FOREGROUND) {
if (prevTime == 0 || Long.compare(event.getTimeStamp(), prevTime) > 0) {
pkgName = event.getPackageName();
clsName = event.getClassName();
prevTime = event.getTimeStamp();
}
} else if(event.getEventType() == event.MOVE_TO_BACKGROUND && prevTime != 0) {
pkgName = null;
clsName = null;
}
}
return pkgName;
} else {
List<ActivityManager.RunningTaskInfo> taskInfos = manager.getRunningTasks(1);
if (taskInfos.size() > 0)
topActivityPackageName = taskInfos.get(0).topActivity.getPackageName();
else
return null;
return topActivityPackageName;
}
}
- forceStopPackage
次方法是系统隐藏的,而且还需要 android.Manifest.permission#FORCE_STOP_PACKAGES 权限
/**
-
Have the system perform a force stop of everything associated with
-
the given application package. All processes that share its uid
-
will be killed, all services it has running stopped, all activities
-
removed, etc. In addition, a {@link Intent#ACTION_PACKAGE_RESTARTED}
-
broadcast will be sent, so that any of its registered alarms can
-
be stopped, notifications removed, etc.
-
You must hold the permission
-
{@link android.Manifest.permission#FORCE_STOP_PACKAGES} to be able to
-
call this method.
-
@param packageName The name of the package to be stopped.
-
@param userId The user for which the running package is to be stopped.
-
@hide This is not available to third party applications due to
-
it allowing them to break other applications by stopping their
-
services, removing their alarms, etc.
*/
public void forceStopPackageAsUser(String packageName, int userId) {
try {
getService().forceStopPackage(packageName, userId);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
/**
-
@see #forceStopPackageAsUser(String, int)
-
@hide
*/
@SystemApi
@RequiresPermission(Manifest.permission.FORCE_STOP_PACKAGES)
public void forceStopPackage(String packageName) {
forceStopPackageAsUser(packageName, mContext.getUserId());
}
当我们执行反射调用的时候,系统会提示错误,App需要是platform系统平台签名,AndroidManifest添加 android:sharedUserId=“android.uid.system” 才可以使用forceStopPackage方法
<permission android:name=“android.permission.FORCE_STOP_PACKAGES”
android:permissionGroup=“android.permission-group.SYSTEM_TOOLS”
android:protectionLevel=“signature”