Service的startForeground用于将服务设置为前台服务,代码如下:
//frameworks/base/core/java/android/app/Service.java
public abstract class Service extends ContextWrapper implements ComponentCallbacks2,
ContentCaptureManager.ContentCaptureClient {
private IActivityManager mActivityManager = null;
public final void startForeground(int id, Notification notification) {
try {
mActivityManager.setServiceForeground(
new ComponentName(this, mClassName), mToken, id,
notification, 0, FOREGROUND_SERVICE_TYPE_MANIFEST);
clearStartForegroundServiceStackTrace();
} catch (RemoteException ex) {
}
}
}
上面方法主要处理如下:
1、调用IActivityManager的setServiceForeground方法。
2、调用clearStartForegroundServiceStackTrace方法。
下面分别进行分析:
ActivityManagerService setServiceForeground
调用IActivityManager的setServiceForeground方法,IActivityManager是一个接口,ActivityManagerService实现了这个接口。
待补充
clearStartForegroundServiceStackTrace
调用clearStartForegroundServiceStackTrace方法:
//frameworks/base/core/java/android/app/Service.java
public abstract class Service extends ContextWrapper implements ComponentCallbacks2,
ContentCaptureManager.ContentCaptureClient {
private static final ArrayMap<String, StackTrace> sStartForegroundServiceStackTraces =
new ArrayMap<>();
private void clearStartForegroundServiceStackTrace() {
synchronized (sStartForegroundServiceStackTraces) {
sStartForegroundServiceStackTraces.remove(this.getClassName()); //删除启动前台服务堆栈跟踪
}
}
}