Android M Launcher3监听packages变化实
前言
android L开始launcher3对于package变化的监听发生了改变,M之前都是通过PackageChangedReceiver(PackageChangedReceiver.java)这个广播接收器来监听的。但是从L开始我们发现LauncherAppsCompat的实现类有两个:LauncherAppsCompatV16和LauncherAppsCompatVL。在LauncherAppsCompatV16中还是通过广播(PackageMonitor extends BroadcastReceiver)来监听packages变化。而在 LauncherAppsCompatVL并没有发现有广播接收器,那么它到底是如何实现packages的监听的呢?
LauncherApps的初始化
我们看到在LauncherAppsCompatVL初始化时,通过getSystemService("launcherapps")得到一个mLauncherApps的系统服务。代码如下:
LauncherAppsCompatVL(Context context) {
super();
mLauncherApps = (LauncherApps) context.getSystemService("launcherapps");
}
看到getSystemService我们可以知道mLauncherApps是一个系统服务,那这个系统服务到底是何方神圣呢?
LauncherApps.java位于frameworks/base/core/java/android/content/pm目录下,我们首先看下它的初始化。
public LauncherApps(Context context, ILauncherApps service) {
mContext = context;
mService = service;
mPm = context.getPackageManager();
}
在LauncherApps的构造方法中重要做三个初始化:上下文mContext、ILauncherApps及获取PackageManager对象。我们重点关注mService是如何实现的,它是如何做到package的监听的呢?
ILauncherApps的实现
从上文我们可以知道LauncherApps是作为客户端通过ILauncherApps获取服务端package变化状态,那么ILauncherApps这个接口定义了些什么呢,它又是如何实现对package的监听呢?我们继续往下分析,首先看下ILauncherApps定义了什么方法:
interface ILauncherApps {
void addOnAppsChangedListener(in IOnAppsChangedListener listener);
void removeOnAppsChangedListener(in IOnAppsChangedListener listener);
List<ResolveInfo> getLauncherActivities(String packageName, in UserHandle user);
ResolveInfo resolveActivity(in Intent intent, in UserHandle user);
void startActivityAsUser(in ComponentName component, in Rect sourceBounds,
in Bundle opts, in UserHandle user);
void showAppDetailsAsUser(in ComponentName component, in Rect sourceBounds,
in Bundle opts, in UserHandle user);
boolean isPackageEnabled(String packageName, in UserHandle user);
boolean isActivityEnabled(in ComponentName component, in UserHandle user);
}
我们看到在这个接口中有addOnAppsChangedListener和removeOnAppsChangedListener这两个方法及其他一些方法(我们暂时不关心),我们只关心addOnAppsChangedListener和removeOnAppsChangedListener这两个方法,通过名字我们可以猜测这应该就是我们要找的package监听器的添加和删除方法
。那么接下来我们来看下ILauncherApps接口的实现。其实现类LauncherAppsImpl是在LauncherAppsService的内部类,代码路径是frameworks/base/services/core/java/com/android/server/pm/,LauncherAppsService是继承自SystemService,主要用来处理适配到当前配置文件(管理不同的user)的launcher发出的请求及回调。
class LauncherAppsImpl extends ILauncherApps.Stub {
...//省略不必要的代码
public void addOnAppsChangedListener(IOnAppsChangedListener listener) throws RemoteException {
synchronized (mListeners) {
if (DEBUG) {
Log.d(TAG, "Adding listener from " + Binder.getCallingUserHandle());
}
if (mListeners.getRegisteredCallbackCount() == 0) {
if (DEBUG) {
Log.d(TAG, "Starting package monitoring");
}
startWatchingPackageBroadcasts();
}
mListeners.unregister(listener);
mListeners.register(listener, Binder.getCallingUserHandle());
}
}
public void removeOnAppsChangedListener(IOnAppsChangedListener listener)
throws RemoteException {
synchronized (mListeners) {
if (DEBUG) {
Log.d(TAG, "Removing listener from " + Binder.getCallingUserHandle());
}
mListeners.unregister(listener);
if (mListeners.getRegisteredCallbackCount() == 0) {
stopWatchingPackageBroadcasts();
}
}
}
...//省略不必要的代码
}
在addOnAppsChangedListener方法中,当当前注册的Callback个数为0时,会调用startWatchingPackageBroadcasts()方法,也就是启动一个广播监听,我们来看下这个广播监听是如何实现的。
广播监听
startWatchingPackageBroadcasts方法的具体实现:
private void startWatchingPackageBroadcasts() {
mPackageMonitor.register(mContext, null, UserHandle.ALL, true);
}
在startWatchingPackageBroadcasts方法中使用了成员变量mPackageMonitor的register方法来实现广播注册。mPackageMonitor是LauncherAppsService的一个私有内部类,继承自PackageMonitor,mPackageMonitor的register方法来自父类PackageMonitor。
//广播的intent过滤
static {
sPackageFilt.addAction(Intent.ACTION_PACKAGE_ADDED);
sPackageFilt.addAction(Intent.ACTION_PACKAGE_REMOVED);
sPackageFilt.addAction(Intent.ACTION_PACKAGE_CHANGED);
sPackageFilt.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
sPackageFilt.addAction(Intent.ACTION_PACKAGE_RESTARTED);
sPackageFilt.addDataScheme("package");
sNonDataFilt.addAction(Intent.ACTION_UID_REMOVED);
sNonDataFilt.addAction(Intent.ACTION_USER_STOPPED);
sExternalFilt.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE);
sExternalFilt.addAction(Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE);
}
//PackageMonitor的register方法实现
public void register(Context context, Looper thread, UserHandle user,
boolean externalStorage) {
if (mRegisteredContext != null) {
throw new IllegalStateException("Already registered");
}
mRegisteredContext = context;
if (thread == null) {
mRegisteredHandler = BackgroundThread.getHandler();
} else {
mRegisteredHandler = new Handler(thread);
}
if (user != null) {
context.registerReceiverAsUser(this, user, sPackageFilt, null, mRegisteredHandler);
context.registerReceiverAsUser(this, user, sNonDataFilt, null, mRegisteredHandler);
if (externalStorage) {
context.registerReceiverAsUser(this, user, sExternalFilt, null,
mRegisteredHandler);
}
} else {
context.registerReceiver(this, sPackageFilt, null, mRegisteredHandler);
context.registerReceiver(this, sNonDataFilt, null, mRegisteredHandler);
if (externalStorage) {
context.registerReceiver(this, sExternalFilt, null, mRegisteredHandler);
}
}
}
至此我们已经明白了L及以上版本的launcher3其实也是通过广播监听来实现监听package的变化的。那么这样做的优势是什么呢?在我看来主要是添加对不同用户的监听, 从上边的代码我们就可已看出在注册监听的时候是有参数user的。而L之前的广播监听是没有这样做,也就无法达到对不同user的精确监听。
当我们监听到有package变化的时候,Launcher是如何实现图标的添加、删除等操作的呢?我们继续回到LauncherAppsImpl的addOnAppsChangedListener和removeOnAppsChangedListener方法,我们可以看到这两个方法的参数IOnAppsChangedListener也是一个AIDL定义的一个接口,那么这个接口到底干了什么呢?
IOnAppsChangedListener接口的实现
首先我们先看下这个接口中定义了哪些方法:
oneway interface IOnAppsChangedListener {
void onPackageRemoved(in UserHandle user, String packageName);
void onPackageAdded(in UserHandle user, String packageName);
void onPackageChanged(in UserHandle user, String packageName);
void onPackagesAvailable(in UserHandle user, in String[] packageNames, boolean replacing);
void onPackagesUnavailable(in UserHandle user, in String[] packageNames, boolean replacing);
}
我们看到它是使用oneway关键字定义的接口,这就表明它的所有方法都采用非阻塞式方式。在这个监听接口中我们找到了监听package变化的五个方法。那这些监听时如何实现的呢?我们接下来看下IOnAppsChangedListener的实现方法。
IOnAppsChangedListener的实现是在frameworks/base/core/java/android/content/pm/LauncherApps.java
private IOnAppsChangedListener.Stub mAppsChangedListener = new IOnAppsChangedListener.Stub() {
public void onPackageRemoved(UserHandle user, String packageName)
throws RemoteException {
if (DEBUG) {
Log.d(TAG, "onPackageRemoved " + user.getIdentifier() + "," + packageName);
}
synchronized (LauncherApps.this) {
for (CallbackMessageHandler callback : mCallbacks) {
callback.postOnPackageRemoved(packageName, user);
}
}
}
...//省略其他方法
}
在这个方法中我们看到它是通过CallbackMessageHandler来处理package变化的消息,CallbackMessageHandler是LauncherApps的一个内部类,继承自Handler。具体实现如下所示:
private static class CallbackMessageHandler extends Handler {
...//省略其他代码
private static final int MSG_REMOVED = 2;
private LauncherApps.Callback mCallback;
private static class CallbackInfo {
String[] packageNames;
String packageName;
boolean replacing;
UserHandle user;
}
public CallbackMessageHandler(Looper looper, LauncherApps.Callback callback) {
super(looper, null, true);
mCallback = callback;
}
@Override
public void handleMessage(Message msg) {
if (mCallback == null || !(msg.obj instanceof CallbackInfo)) {
return;
}
CallbackInfo info = (CallbackInfo) msg.obj;
switch (msg.what) {
...//省略其他选择
case MSG_REMOVED:
mCallback.onPackageRemoved(info.packageName, info.user);
break;
}
}
public void postOnPackageRemoved(String packageName, UserHandle user) {
CallbackInfo info = new CallbackInfo();
info.packageName = packageName;
info.user = user;
obtainMessage(MSG_REMOVED, info).sendToTarget();
}
...//省略其他代码
在handleMessage方法中,是通过回调的方式来调用onPackageRemoved方法的。CallbackMessageHandler的构造方法中传进来的是LauncherApps.Callback,也就是我们的mCallback,那么这个callback到底是在什么地方实现的呢?
pacakge变化的回调实现
我们回到Launcher3的源码,在类LauncherAppsCompatVL中有方法addOnAppsChangedCallback,在这个方法中LauncherApps调用registerCallback,将回调注册到CallbackMessageHandler。
public void registerCallback(Callback callback, Handler handler) {
synchronized (this) {
if (callback != null && findCallbackLocked(callback) < 0) {
boolean addedFirstCallback = mCallbacks.size() == 0;
addCallbackLocked(callback, handler);
if (addedFirstCallback) {
try {
mService.addOnAppsChangedListener(mAppsChangedListener);
} catch (RemoteException re) {
}
}
}
}
}
那么LauncherAppsCompatVL的addOnAppsChangedCallback是在什么时候调用的呢?在LauncherAppState的构造方法中有调用addOnAppsChangedCallback,参数是LauncherModel。
//LauncherAppsState构造方法中调用addOnAppsChangedCallback
LauncherAppsCompat.getInstance(sContext).addOnAppsChangedCallback(mModel);
LauncherModel实现了LauncherAppsCompat.OnAppsChangedCallbackCompat的接口。
//LauncherAppsCompat.OnAppsChangedCallbackCompat的接口
public interface OnAppsChangedCallbackCompat {
void onPackageRemoved(String packageName, UserHandleCompat user);
void onPackageAdded(String packageName, UserHandleCompat user);
void onPackageChanged(String packageName, UserHandleCompat user);
void onPackagesAvailable(String[] packageNames, UserHandleCompat user, boolean replacing);
void onPackagesUnavailable(String[] packageNames, UserHandleCompat user, boolean replacing);
}
通过上面的分析我们可以看到,当package变化最终调用到的是LauncherModel中实现的以上接口,我们以onPackageRemoved为例来看下LauncherModel中的实现。
Callback.pngLauncherModel对package变化的处理
我们首先来看下LauncherModel中onPackageRemoved的实现。
public void onPackageRemoved(String packageName, UserHandleCompat user) {
int op = PackageUpdatedTask.OP_REMOVE;
enqueuePackageUpdated(new PackageUpdatedTask(op, new String[] { packageName },
user));
}
在该方法中会初始化一个PackageUpdatedTask,这是LauncherModel中一个继承自Runnable接口的内部类,然后通过Handler.post(Runnable)来执行。根据传进来变量PackageUpdatedTask.OP_REMOVE,PackageUpdatedTask会对当前user的配置文件、IconCache、桌面图标等进行清除操作。后边我们会针对这一过程专门讨论。
总结
launcherapps监听.pngAndroid L及以上版本,Launcher3通过获取launcherapps系统服务,监听package变化。而在系统服务launcherapps也是通PackageMonitor注册广播来进行package的监听,和之前版本最大的变化其实是针对不同用户的不同package进行监听。