app服务保活 (android 11 源码)
frameworks/base/services/core/java/com/android/server/am/ActiveServices.java
stop后台service的逻辑:
AMS的doStopUidLocked方法会先stop 后台service,再去更新uid并分发uid的change
stopInBackgroundLocked回调后,service不一定会真被stop
void stopInBackgroundLocked(int uid) {
// Stop all services associated with this uid due to it going to the background
// stopped state.
// 获取该uid下的所有service
ServiceMap services = mServiceMap.get(UserHandle.getUserId(uid));
ArrayList<ServiceRecord> stopping = null;
if (services != null) {
for (int i = services.mServicesByInstanceName.size() - 1; i >= 0; i--) {
ServiceRecord service = services.mServicesByInstanceName.valueAt(i);
// start方式启动的service
if (service.appInfo.uid == uid && service.startRequested) {
if (mAm.getAppStartModeLocked(service.appInfo.uid, service.packageName,
service.appInfo.targetSdkVersion, -1, false, false, false)
!= ActivityManager.APP_START_MODE_NORMAL) {
if (stopping == null) {
stopping = new ArrayList<>();
}
String compName = service.shortInstanceName;
//add 包名过滤防止它被杀
if(compName.contains("com.google.wangyiyun"))
continue;
//end
......
// 將当前service添加进stoppping列表
stopping.add(service);
// If the app is under bg restrictions, also make sure that
// any notification is dismissed
if (appRestrictedAnyInBackground(
service.appInfo.uid, service.packageName)) {
cancelForegroundNotificationLocked(service);
}
}
}
}
if (stopping != null) {
for (int i=stopping.size()-1; i>=0; i--) {
ServiceRecord service = stopping.get(i);
service.delayed = false;
services.ensureNotStartingBackgroundLocked(service);
// stop service
stopServiceLocked(service);
}
}
}
}
//这个函数用停止app的服务
private void stopServiceLocked(ServiceRecord service) {
if (service.delayed) {
// If service isn't actually running, but is being held in the
// delayed list, then we need to keep it started but note that it
// should be stopped once no longer delayed.
if (DEBUG_DELAYED_STARTS) Slog.v(TAG_SERVICE, "Delaying stop of pending: " + service);
service.delayedStop = true;
return;
}
StatsLog.write(StatsLog.SERVICE_STATE_CHANGED, service.appInfo.uid,
service.name.getPackageName(), service.name.getClassName(),
StatsLog.SERVICE_STATE_CHANGED__STATE__STOP);
synchronized (service.stats.getBatteryStats()) {
service.stats.stopRunningLocked();
}
service.startRequested = false;
if (service.tracker != null) {
service.tracker.setStarted(false, mAm.mProcessStats.getMemFactorLocked(),
SystemClock.uptimeMillis());
}
service.callStart = false;
bringDownServiceIfNeededLocked(service, false, false);
}
bringDownServiceIfNeededLocked(...)
private final void bringDownServiceIfNeededLocked(ServiceRecord r, boolean knowConn,
boolean hasConn) {
if (isServiceNeededLocked(r, knowConn, hasConn)) {
return;
}
// 如果有新拉起service的需求,本次不会stop该service
if (mPendingServices.contains(r)) {
return;
}
bringDownServiceLocked(r);
}
(android-12)app进入后台,关掉杀死serivce
参考一