前言
壁纸可以说是移动设备最常见的功能之一,壁纸应用为了实现绘制壁纸的功能,都需要创建一个继承自WallpaperService的服务,这个服务运行在系统后台,并在一个类型为TYPE_WALLPAPER的窗口上绘制壁纸内容。Android系统WallpaperManagerService类是专门负责管理各种壁纸应用的壁纸服务的,本期我们将会结合Android12的系统源码来具体梳理一下壁纸服务管理者WallpaperManagerService的启动流程。
一、SystemServer启动WallpaperManagerService的服务
1、系统启动后会启动JVM虚拟机,SystemServer 是虚拟机的第一个进程,由init 进程fork 产生。主要用来启动frameworks层中的服务。SystemServer进程里面有个main()方法:
frameworks/base/service/java/com/android/server/SystemServer.java
public final class SystemServer {
public static void main(String[] args) {
new SystemServer().run();
}
}
2、main 方法里启动了 run() 方法,而在 run 方法中调用了startOtherServices() 方法:
public final class SystemServer {
private void run() {
...
// Start services.
try {
traceBeginAndSlog("StartServices");
startBootstrapServices();//启动引导服务
startCoreServices();//启动核心服务
startOtherServices();//启动其他服务
SystemServerInitThreadPool.shutdown();
} catch (Throwable ex) {
...
} finally {
traceEnd();
}
...
}
}
3、startOtherServices方法和WallpaperManagerService服务启动相关的代码如下所示。
public final class SystemServer implements Dumpable {
private static final String WALLPAPER_SERVICE_CLASS =
"com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
...代码省略...
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
t.traceBegin("StartWallpaperManagerService");
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.i(TAG, "Wallpaper service disabled by config");
}
...代码省略...
}
}
在开启壁纸管理服务之前会先获取config_enableWallpaperService字段的数值来确认是否打开壁纸管理服务。
frameworks/base/core/res/res/values/config.xml
<bool name="config_enableWallpaperService">true</bool>
只有此数值为true,才会调用SystemServiceManager的startService方法启动WallpaperManagerService服务。
4、SystemServiceManager的startService方法如下所示。
frameworks/base/services/core/java/com/android/server/SystemServiceManager.java
public class SystemServiceManager {
//存储了SystemServiceManager负责启动的各种服务
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
public SystemService startService(String className) {
final Class<SystemService> serviceClass = loadClassFromLoader(className,this.getClass().getClassLoader());
return startService(serviceClass);
}
@SuppressWarnings("unchecked")
public <T extends SystemService> T startService(Class<T> serviceClass) {
try {
final String name = serviceClass.getName();
...代码省略...
final T service;
try {
Constructor<T> constructor = serviceClass.getConstructor(Context.class);
service = constructor.newInstance(mContext);
}
...代码省略...
startService(service);
return service;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
public void startService(@NonNull final SystemService service) {
// Register it.
mServices.add(service);
// Start it.
long time = SystemClock.elapsedRealtime();
try {
service.onStart();
} catch (RuntimeException ex) {
throw new RuntimeException("Failed to start service " + service.getClass().getName()
+ ": onStart threw an exception", ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onStart");
}
}
因为前面我们传入的参数为Lifecycle,所以这里startService方法首先会通过反射创建Lifecycle对象实例,然后将其存储在类型ArrayList的mServices中,紧接着会调用Lifecycle的onStart方法。
5、继续来看下作为方法参数的Lifecycle类的关键方法。
frameworks/base/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
public static class Lifecycle extends SystemService {
private IWallpaperManagerService mService;
public Lifecycle(Context context) {
super(context);
}
@Override
public void onStart() {
try {
//在这里通过反射创建了WallpaperManagerService对象实例
final Class<? extends IWallpaperManagerService> klass =
(Class<? extends IWallpaperManagerService>)Class.forName(
getContext().getResources().getString(
R.string.config_wallpaperManagerServiceName));
//赋值给属性变量mService
mService = klass.getConstructor(Context.class).newInstance(getContext());
publishBinderService(Context.WALLPAPER_SERVICE, mService);
} catch (Exception exp) {
Slog.wtf(TAG, "Failed to instantiate WallpaperManagerService", exp);
}
}
@Override
public void onBootPhase(int phase) {
//启动阶段触发WallpaperManagerService的onBootPhase方法。
if (mService != null) {
mService.onBootPhase(phase);
}
}
@Override
public void onUserUnlocking(@NonNull TargetUser user) {
if (mService != null) {
mService.onUnlockUser(user.getUserIdentifier());
}
}
}
}
frameworks/base/core/res/res/values/config.xml
<string name="config_wallpaperManagerServiceName" translatable="false">com.android.server.wallpaper.WallpaperManagerService</string>
Lifecycle作为WallpaperManagerService的内部类,继承自SystemService,他的onStart方法会通过config_wallpaperManagerServiceName字段获取WallpaperManagerService类的路径,并通过反射创建WallpaperManagerService对象实例并赋值给属性变量mService。
6、重新回到SystemServer的startOtherServices方法中,在mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS)方法执行之后,代码继续往下执行。
public final class SystemServer implements Dumpable {
/**
* 在接收到这个启动阶段之后,服务可以广播意图了
*/
public static final int PHASE_ACTIVITY_MANAGER_READY = 550;
/**
* 在接收到这个启动阶段之后,服务才可以启动、绑定第三方应用,应用将会被允许使用Binder和服务进行通讯。
*/
public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600;
private static final String WALLPAPER_SERVICE_CLASS =
"com.android.server.wallpaper.WallpaperManagerService$Lifecycle";
private void startOtherServices(@NonNull TimingsTraceAndSlog t) {
...代码省略...
if (context.getResources().getBoolean(R.bool.config_enableWallpaperService)) {
t.traceBegin("StartWallpaperManagerService");
mSystemServiceManager.startService(WALLPAPER_SERVICE_CLASS);
t.traceEnd();
} else {
Slog.i(TAG, "Wallpaper service disabled by config");
}
...代码省略...
mActivityManagerService.systemReady(() -> {
Slog.i(TAG, "Making services ready");
t.traceBegin("StartActivityManagerReadyPhase");
//第一次执行startBootPhase方法,传递SystemService.PHASE_ACTIVITY_MANAGER_READY,此时服务可以广播意图了
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_ACTIVITY_MANAGER_READY);
t.traceEnd();
t.traceBegin("StartObservingNativeCrashes");
...代码省略...
//第二次执行startBootPhase方法,传递SystemService.PHASE_THIRD_PARTY_APPS_CAN_START,
//服务才可以启动、绑定第三方应用,应用将会被允许使用Binder和服务进行通讯。
mSystemServiceManager.startBootPhase(t, SystemService.PHASE_THIRD_PARTY_APPS_CAN_START);
...代码省略...
}
}
}
startOtherServices方法继续往下执行,在ActivityManagerService的systemReady回调方法中,会调用SystemServiceManager的startBootPhase方法。
7、SystemServiceManager的startBootPhase方法如下所示。
public class SystemServiceManager {
//存储了SystemServiceManager负责启动的各种服务
private final ArrayList<SystemService> mServices = new ArrayList<SystemService>();
/**
* 初始化所有存储在mServices变量中的服务
*/
public void startBootPhase(@NonNull TimingsTraceAndSlog t, int phase) {
if (phase <= mCurrentPhase) {
throw new IllegalArgumentException("Next phase must be larger than previous");
}
mCurrentPhase = phase;
Slog.i(TAG, "Starting phase " + mCurrentPhase);
try {
t.traceBegin("OnBootPhase_" + phase);
final int serviceLen = mServices.size();
for (int i = 0; i < serviceLen; i++) {
final SystemService service = mServices.get(i);
long time = SystemClock.elapsedRealtime();
t.traceBegin("OnBootPhase_" + phase + "_" + service.getClass().getName());
try {
service.onBootPhase(mCurrentPhase);
} catch (Exception ex) {
throw new RuntimeException("Failed to boot service "
+ service.getClass().getName()
+ ": onBootPhase threw an exception during phase "
+ mCurrentPhase, ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onBootPhase");
t.traceEnd();
}
} finally {
t.traceEnd();
}
if (phase == SystemService.PHASE_BOOT_COMPLETED) {
final long totalBootTime = SystemClock.uptimeMillis() - mRuntimeStartUptime;
t.logDuration("TotalBootTime", totalBootTime);
SystemServerInitThreadPool.shutdown();
}
}
}
这里会触发WallpaperManagerService$Lifecycle的onBootPhase方法,而Lifecycle的onBootPhase方法又会进一步调用自己WallpaperManagerService的onBootPhase方法。
二、WallpaperManagerService的构造方法
第一节有提到在Lifecycle的onStart方法中通过反射创建WallpaperManagerService对象实例,WallpaperManagerService的构造方法如下所示。
frameworks/base/services/core/java/com/android/server/wallpaper/WallpaperManagerService.java
public class WallpaperManagerService extends IWallpaperManager.Stub
private final ComponentName mImageWallpaper;//静态壁纸组件
private final ComponentName mDefaultWallpaperComponent; //默认动态壁纸服务组件
public WallpaperManagerService(Context context) {
if (DEBUG) Slog.v(TAG, "WallpaperService startup");
mContext = context;
mShuttingDown = false;
//1)获取静态壁纸服务,默认为com.android.systemui/com.android.systemui.ImageWallpaper
mImageWallpaper = ComponentName.unflattenFromString(
context.getResources().getString(R.string.image_wallpaper_component));
//2)获取默认的动态壁纸服务
mDefaultWallpaperComponent = WallpaperManager.getDefaultWallpaperComponent(context);
mWindowManagerInternal = LocalServices.getService(WindowManagerInternal.class);
mIPackageManager = AppGlobals.getPackageManager();
mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
mDisplayManager = mContext.getSystemService(DisplayManager.class);
mDisplayManager.registerDisplayListener(mDisplayListener, null /* handler */);
mActivityManager = mContext.getSystemService(ActivityManager.class);
mMonitor = new MyPackageMonitor();
mColorsChangedListeners = new SparseArray<>();
LocalServices.addService(WallpaperManagerInternal.class, new LocalService());
}
}
构造方法我们关注以下两点:
1)获取系统默认的静态壁纸服务组件,对应的字符串为R.string.image_wallpaper_component,这个值默认为SystemUI模块的静态壁纸服务类路径。
frameworks/base/core/res/res/values/config.xml
<!-- Component name of the built in wallpaper used to display bitmap wallpapers. This must not be null. -->
<string name="image_wallpaper_component" translatable="false">com.android.systemui/com.android.systemui.ImageWallpaper</string>
2)调用WallpaperManager的getDefaultWallpaperComponent方法获取默认的动态壁纸服务组件。
frameworks/base/core/java/android/app/WallpaperManager.java
public class WallpaperManager {
public static ComponentName getDefaultWallpaperComponent(Context context) {
ComponentName cn = null;
String flat = SystemProperties.get(PROP_WALLPAPER_COMPONENT);
if (!TextUtils.isEmpty(flat)) {
cn = ComponentName.unflattenFromString(flat);
}
if (cn == null) {
//获取默认的动态壁纸服务,这个值默认为null
flat = context.getString(com.android.internal.R.string.default_wallpaper_component);
if (!TextUtils.isEmpty(flat)) {
cn = ComponentName.unflattenFromString(flat);
}
}
//检测动态壁纸服务的包名是否存在
if (cn != null) {
try {
final PackageManager packageManager = context.getPackageManager();
packageManager.getPackageInfo(cn.getPackageName(),
PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
} catch (PackageManager.NameNotFoundException e) {
cn = null;
}
}
return cn;
}
}
对应的字符串为R.string.default_wallpaper_component,这个值默认为null。
frameworks/base/core/res/res/values/config.xml
<!-- Component name of the default wallpaper. This will be ImageWallpaper if not
specified -->
<string name="default_wallpaper_component" translatable="false">@null</string>
三、WallpaperManagerService的onBootPhase方法
1、在创建WallpaperManagerService对象实例触发构造方法之后,Lifecycle的onBootPhase方法会再次回调WallpaperManagerService的onBootPhase方法。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
@Override
public void onBootPhase(int phase) {
errorCheck(UserHandle.USER_SYSTEM);
//此阶段可以广播意图了
if (phase == SystemService.PHASE_ACTIVITY_MANAGER_READY) {
systemReady();
}
//此阶段可以启动、绑定第三方应用,应用将会被允许使用Binder和服务进行通讯
else if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
switchUser(UserHandle.USER_SYSTEM, null);//切换用户
}
}
}
2、根据传入的不同参数类型,所触发的方法也不同,这里我们主要关注systemReady方法。。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
void systemReady() {
//初始化
initialize();
...代码省略...
}
}
3、systemReady方法首先调用了initialize方法。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
void initialize() {
mMonitor.register(mContext, null, UserHandle.ALL, true);
//1)获取系统当前用户的壁纸目录
getWallpaperDir(UserHandle.USER_SYSTEM).mkdirs();
//2)加载系统当前用户的相关设置
loadSettingsLocked(UserHandle.USER_SYSTEM, false);
//3)获取系统当前用户的壁纸数据
getWallpaperSafeLocked(UserHandle.USER_SYSTEM, FLAG_SYSTEM);
}
}
4、 initializes方法首先调用getWallpaperDir方法获取系统当前用户的壁纸目录。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
File getWallpaperDir(int userId) {
return Environment.getUserSystemDirectory(userId);
}
}
这里返回的结果是**/data/system/users/0**,所以getWallpaperDir(UserHandle.USER_OWNER).mkdirs()方法其实就是创建了**/data/system/users/0/**这个目录。
5、 initializes方法继续往下执行,调用loadSettingsLocked方法加载系统当前用户的相关配置。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
static final String WALLPAPER = "wallpaper_orig";//设置的壁纸图片,一般为jpeg格式
static final String WALLPAPER_CROP = "wallpaper";
private void loadSettingsLocked(int userId, boolean keepDimensionHints) {
//1)调用获取makeJournaledFile方法获取JournaledFile对象
JournaledFile journal = makeJournaledFile(userId);
FileInputStream stream = null;
//2)调用JournaledFile的chooseForRead方法获取接下来需要解析的文件,其实就是data/system/users/0/wallpaper_info.xml文件
File file = journal.chooseForRead();
//3)获取当前用户的壁纸数据
WallpaperData wallpaper = mWallpaperMap.get(userId);
if (wallpaper == null) {
migrateFromOld();
//如果为空则创建
wallpaper = new WallpaperData(userId, getWallpaperDir(userId), WALLPAPER, WALLPAPER_CROP);
wallpaper.allowBackup = true;
mWallpaperMap.put(userId, wallpaper);
if (!wallpaper.cropExists()) {
if (wallpaper.sourceExists()) {
generateCrop(wallpaper);
} else {
Slog.i(TAG, "No static wallpaper imagery; defaults will be shown");
}
}
initializeFallbackWallpaper();
}
boolean success = false;
final DisplayData wpdData = getDisplayDataOrCreate(DEFAULT_DISPLAY);
try {
//4)开始解析wallpaper_info.xml文件
stream = new FileInputStream(file);
TypedXmlPullParser parser = Xml.resolvePullParser(stream);
int type;
do {
type = parser.next();
if (type == XmlPullParser.START_TAG) {
String tag = parser.getName();
if ("wp".equals(tag)) {
// Common to system + lock wallpapers
parseWallpaperAttributes(parser, wallpaper, keepDimensionHints);
// A system wallpaper might also be a live wallpaper
String comp = parser.getAttributeValue(null, "component");
wallpaper.nextWallpaperComponent = comp != null
? ComponentName.unflattenFromString(comp)
: null;
if (wallpaper.nextWallpaperComponent == null
|| "android".equals(wallpaper.nextWallpaperComponent
.getPackageName())) {
wallpaper.nextWallpaperComponent = mImageWallpaper;
}
} else if ("kwp".equals(tag)) {
// keyguard-specific wallpaper for this user
WallpaperData lockWallpaper = mLockWallpaperMap.get(userId);
if (lockWallpaper == null) {
lockWallpaper = new WallpaperData(userId, getWallpaperDir(userId),
WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP);
mLockWallpaperMap.put(userId, lockWallpaper);
}
parseWallpaperAttributes(parser, lockWallpaper, false);
}
}
} while (type != XmlPullParser.END_DOCUMENT);
success = true;
} catch (FileNotFoundException e) {
Slog.w(TAG, "no current wallpaper -- first boot?");
} catch (NullPointerException e) {
Slog.w(TAG, "failed parsing " + file + " " + e);
} catch (NumberFormatException e) {
Slog.w(TAG, "failed parsing " + file + " " + e);
} catch (XmlPullParserException e) {
Slog.w(TAG, "failed parsing " + file + " " + e);
} catch (IOException e) {
Slog.w(TAG, "failed parsing " + file + " " + e);
} catch (IndexOutOfBoundsException e) {
Slog.w(TAG, "failed parsing " + file + " " + e);
}
IoUtils.closeQuietly(stream);
if (!success) {
wallpaper.cropHint.set(0, 0, 0, 0);
wpdData.mPadding.set(0, 0, 0, 0);
wallpaper.name = "";
mLockWallpaperMap.remove(userId);
} else {
if (wallpaper.wallpaperId <= 0) {
wallpaper.wallpaperId = makeWallpaperIdLocked();
if (DEBUG) {
Slog.w(TAG, "Didn't set wallpaper id in loadSettingsLocked(" + userId
+ "); now " + wallpaper.wallpaperId);
}
}
}
ensureSaneWallpaperDisplaySize(wpdData, DEFAULT_DISPLAY);
ensureSaneWallpaperData(wallpaper);
WallpaperData lockWallpaper = mLockWallpaperMap.get(userId);
if (lockWallpaper != null) {
ensureSaneWallpaperData(lockWallpaper);
}
}
}
以上方法我们主要关注以下几点:
1)首先调用获取makeJournaledFile方法获取JournaledFile对象,makeJournaledFile方法如下所示。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
static final String WALLPAPER_INFO = "wallpaper_info.xml";//包含墙纸的规格信息:高、宽
private JournaledFile makeJournaledFile(int userId) {
//初次获得的文件路径为data/system/users/0/wallpaper_info.xml
final String base = new File(getWallpaperDir(userId), WALLPAPER_INFO).getAbsolutePath();
return new JournaledFile(new File(base), new File(base + ".tmp"));
}
}
2)调用JournaledFile的chooseForRead方法获取接下来需要解析的文件。
JournaledFile对象如下所示。
frameworks/base/core/java/com/android/internal/util/JournaledFile.java
public class JournaledFile {
File mReal;
File mTemp;
boolean mWriting;
@UnsupportedAppUsage
public JournaledFile(File real, File temp) {
mReal = real;
mTemp = temp;
}
public File chooseForRead() {
File result;
if (mReal.exists()) {
result = mReal;
if (mTemp.exists()) {
mTemp.delete();//删除临时文件
}
} else if (mTemp.exists()) {
result = mTemp;
mTemp.renameTo(mReal);//将临时文件改名为正式文件
} else {
return mReal;
}
return result;
}
}
JournaledFile这个对象封装了/data/system/users/0/wallpaper_info.xml文件。这个对象内部包含两个文件,一个是wallpaper_info.xml正式文件,另一个是wallpaper_info.xml.tmp临时文件,他的chooseForRead方法在返回文件的时候会做判断,如果正式文件存在就选出正式文件,并删除临时文件;如果正式文件不存在就将临时文件重名为正式文件。
3)获取系统当前用户的WallpaperData对象并判断是否为空 ,为空则创建WallpaperData对象实例。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
static final String WALLPAPER = "wallpaper_orig";//设置的壁纸图片,一般为jpeg格式
static final String WALLPAPER_CROP = "wallpaper";
static class WallpaperData {
int userId;//用户id
final File wallpaperFile; // source image
final File cropFile; // eventual destination
...代码省略...
WallpaperData(int userId, File wallpaperDir, String inputFileName, String cropFileName) {
this.userId = userId;//初次为0
wallpaperFile = new File(wallpaperDir, inputFileName);//初次为/data/system/users/0/wallpaper_orig
cropFile = new File(wallpaperDir, cropFileName);初次为/data/system/users/0/wallpaper
}
}
}
4)解析前面通过JournaledFile的chooseForRead方法所获取的文件,其实就是/data/system/users/0/wallpaper_info.xml文件,不过由于第一次启动时,wallpaer_info.xml并不存在,也就不采用其里面的值。
6、 loadSettingsLocked方法执行之后,initializes方法继续往下执行,调用getWallpaperSafeLocked方法获取系统当前用户的壁纸数据。
WallpaperData getWallpaperSafeLocked(int userId, int which) {
final SparseArray<WallpaperData> whichSet =
(which == FLAG_LOCK) ? mLockWallpaperMap : mWallpaperMap;
WallpaperData wallpaper = whichSet.get(userId);
if (wallpaper == null) {
loadSettingsLocked(userId, false);
wallpaper = whichSet.get(userId);
if (wallpaper == null) {
if (which == FLAG_LOCK) {
wallpaper = new WallpaperData(userId, getWallpaperDir(userId),
WALLPAPER_LOCK_ORIG, WALLPAPER_LOCK_CROP);
mLockWallpaperMap.put(userId, wallpaper);
ensureSaneWallpaperData(wallpaper);
} else {
Slog.wtf(TAG, "Didn't find wallpaper in non-lock case!");
wallpaper = new WallpaperData(userId, getWallpaperDir(userId),
WALLPAPER, WALLPAPER_CROP);
//存储到mWallpaperMap中
mWallpaperMap.put(userId, wallpaper);
ensureSaneWallpaperData(wallpaper);
}
}
}
return wallpaper;
}
7、分析完systemReady方法所调用的initialize方法之后,让我们重新回到第2步,继续往下看systemReady方法。
public class WallpaperManagerService extends IWallpaperManager.Stub
implements IWallpaperManagerService {
void systemReady() {
if (DEBUG) Slog.v(TAG, "systemReady");
//初始化
initialize();
//获取系统当前用户的壁纸数据
WallpaperData wallpaper = mWallpaperMap.get(UserHandle.USER_SYSTEM);
if (mImageWallpaper.equals(wallpaper.nextWallpaperComponent)) {
// No crop file? Make sure we've finished the processing sequence if necessary
if (!wallpaper.cropExists()) {
if (DEBUG) {
Slog.i(TAG, "No crop; regenerating from source");
}
generateCrop(wallpaper);
}
// Still nothing? Fall back to default.
if (!wallpaper.cropExists()) {
if (DEBUG) {
Slog.i(TAG, "Unable to regenerate crop; resetting");
}
clearWallpaperLocked(false, FLAG_SYSTEM, UserHandle.USER_SYSTEM, null);
}
} else {
if (DEBUG) {
Slog.i(TAG, "Nondefault wallpaper component; gracefully ignoring");
}
}
//注册广播接收者,监听用户移除事件
IntentFilter userFilter = new IntentFilter();
userFilter.addAction(Intent.ACTION_USER_REMOVED);
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (Intent.ACTION_USER_REMOVED.equals(action)) {
onRemoveUser(intent.getIntExtra(Intent.EXTRA_USER_HANDLE,
UserHandle.USER_NULL));
}
}
}, userFilter);
//注册广播接收者,监听关机广播
final IntentFilter shutdownFilter = new IntentFilter(Intent.ACTION_SHUTDOWN);
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_SHUTDOWN.equals(intent.getAction())) {
if (DEBUG) {
Slog.i(TAG, "Shutting down");
}
synchronized (mLock) {
mShuttingDown = true;
}
}
}
}, shutdownFilter);
//为ActivityManagerService注册回调方法,监听用户切换事件
try {
ActivityManager.getService().registerUserSwitchObserver(
new UserSwitchObserver() {
@Override
public void onUserSwitching(int newUserId, IRemoteCallback reply) {
errorCheck(newUserId);
switchUser(newUserId, reply);
}
}, TAG);
} catch (RemoteException e) {
e.rethrowAsRuntimeException();
}
}
}
四、总结
参考文章:https://www.zybuluo.com/guhuizaifeiyang/note/866798