下面列出了怎么用android.os.RemoteCallbackList的API类实例代码及写法,或者点击链接到github查看源代码。
void notifyWallpaperVisibilityChanged(DisplayContent displayContent) {
final int displayId = displayContent.getDisplayId();
final boolean visible = displayContent.mWallpaperController.isWallpaperVisible();
RemoteCallbackList<IWallpaperVisibilityListener> displayListeners =
mDisplayListeners.get(displayId);
// No listeners for this display.
if (displayListeners == null) {
return;
}
int i = displayListeners.beginBroadcast();
while (i > 0) {
i--;
IWallpaperVisibilityListener listener = displayListeners.getBroadcastItem(i);
try {
listener.onWallpaperVisibilityChanged(visible, displayId);
} catch (RemoteException e) {
// Nothing to do in here, RemoteCallbackListener will clean it up.
}
}
displayListeners.finishBroadcast();
}
@Override
public void registerNetworkScoreCache(int networkType,
INetworkScoreCache scoreCache,
int filterType) {
enforceSystemOnly();
final long token = Binder.clearCallingIdentity();
try {
synchronized (mScoreCaches) {
RemoteCallbackList<INetworkScoreCache> callbackList = mScoreCaches.get(networkType);
if (callbackList == null) {
callbackList = new RemoteCallbackList<>();
mScoreCaches.put(networkType, callbackList);
}
if (!callbackList.register(scoreCache, filterType)) {
if (callbackList.getRegisteredCallbackCount() == 0) {
mScoreCaches.remove(networkType);
}
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Unable to register NetworkScoreCache for type " + networkType);
}
}
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public void unregisterNetworkScoreCache(int networkType, INetworkScoreCache scoreCache) {
enforceSystemOnly();
final long token = Binder.clearCallingIdentity();
try {
synchronized (mScoreCaches) {
RemoteCallbackList<INetworkScoreCache> callbackList = mScoreCaches.get(networkType);
if (callbackList == null || !callbackList.unregister(scoreCache)) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "Unable to unregister NetworkScoreCache for type "
+ networkType);
}
} else if (callbackList.getRegisteredCallbackCount() == 0) {
mScoreCaches.remove(networkType);
}
}
} finally {
Binder.restoreCallingIdentity(token);
}
}
private void sendCacheUpdateCallback(BiConsumer<INetworkScoreCache, Object> consumer,
Collection<RemoteCallbackList<INetworkScoreCache>> remoteCallbackLists) {
for (RemoteCallbackList<INetworkScoreCache> callbackList : remoteCallbackLists) {
synchronized (callbackList) { // Ensure only one active broadcast per RemoteCallbackList
final int count = callbackList.beginBroadcast();
try {
for (int i = 0; i < count; i++) {
consumer.accept(callbackList.getBroadcastItem(i),
callbackList.getBroadcastCookie(i));
}
} finally {
callbackList.finishBroadcast();
}
}
}
}
public PlayControlImpl(Context context) {
this.context = context;
this.mSongChangeListeners = new RemoteCallbackList<>();
this.mStatusChangeListeners = new RemoteCallbackList<>();
this.mPlayListChangeListeners = new RemoteCallbackList<>();
this.mDataIsReadyListeners = new RemoteCallbackList<>();
this.sessionManager = new MediaSessionManager(context, this);
this.focusManager = new AudioFocusManager(context, this);
this.manager = PlayController.getMediaController(
context,
focusManager,
sessionManager,
new NotifyStatusChange(),
new NotifySongChange(),
new NotifyPlayListChange());
}
public ImConnectionAdapter(long providerId, long accountId, ImConnection connection, RemoteImService service) {
mProviderId = providerId;
mAccountId = accountId;
mConnection = connection;
mService = service;
mConnectionListener = new ConnectionListenerAdapter();
mConnection.addConnectionListener(mConnectionListener);
if ((connection.getCapability() & ImConnection.CAPABILITY_GROUP_CHAT) != 0) {
mGroupManager = mConnection.getChatGroupManager();
mInvitationListener = new InvitationListenerAdapter();
mGroupManager.setInvitationListener(mInvitationListener);
}
mChatSessionManager = new ChatSessionManagerAdapter(this);
mContactListManager = new ContactListManagerAdapter(this);
mRemoteConnListeners = new RemoteCallbackList<>();
}
@Override
public void handleMessage(Message msg) {
RemoteCallbackList<IOpenVPNStatusCallback> callbacks;
switch (msg.what) {
case SEND_TOALL:
if (service == null || service.get() == null)
return;
callbacks = service.get().mCallbacks;
// Broadcast to all clients the new value.
final int N = callbacks.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
sendUpdate(callbacks.getBroadcastItem(i), (UpdateMessage) msg.obj);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
callbacks.finishBroadcast();
break;
}
}
void registerWallpaperVisibilityListener(IWallpaperVisibilityListener listener,
int displayId) {
RemoteCallbackList<IWallpaperVisibilityListener> listeners =
mDisplayListeners.get(displayId);
if (listeners == null) {
listeners = new RemoteCallbackList<>();
mDisplayListeners.append(displayId, listeners);
}
listeners.register(listener);
}
void unregisterWallpaperVisibilityListener(IWallpaperVisibilityListener listener,
int displayId) {
RemoteCallbackList<IWallpaperVisibilityListener> listeners =
mDisplayListeners.get(displayId);
if (listeners == null) {
return;
}
listeners.unregister(listener);
}
private void notifyWallpaperColorsChanged(@NonNull WallpaperData wallpaper, int which) {
boolean needsExtraction;
synchronized (mLock) {
final RemoteCallbackList<IWallpaperManagerCallback> currentUserColorListeners =
mColorsChangedListeners.get(wallpaper.userId);
final RemoteCallbackList<IWallpaperManagerCallback> userAllColorListeners =
mColorsChangedListeners.get(UserHandle.USER_ALL);
// No-op until someone is listening to it.
if (emptyCallbackList(currentUserColorListeners) &&
emptyCallbackList(userAllColorListeners)) {
return;
}
if (DEBUG) {
Slog.v(TAG, "notifyWallpaperColorsChanged " + which);
}
needsExtraction = wallpaper.primaryColors == null;
}
// Let's notify the current values, it's fine if it's null, it just means
// that we don't know yet.
notifyColorListeners(wallpaper.primaryColors, which, wallpaper.userId);
if (needsExtraction) {
extractColors(wallpaper);
synchronized (mLock) {
// Don't need to notify if nothing changed.
if (wallpaper.primaryColors == null) {
return;
}
}
notifyColorListeners(wallpaper.primaryColors, which, wallpaper.userId);
}
}
@Override
public void registerWallpaperColorsCallback(IWallpaperManagerCallback cb, int userId) {
userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, true, true, "registerWallpaperColorsCallback", null);
synchronized (mLock) {
RemoteCallbackList<IWallpaperManagerCallback> userColorsChangedListeners =
mColorsChangedListeners.get(userId);
if (userColorsChangedListeners == null) {
userColorsChangedListeners = new RemoteCallbackList<>();
mColorsChangedListeners.put(userId, userColorsChangedListeners);
}
userColorsChangedListeners.register(cb);
}
}
@Override
public void unregisterWallpaperColorsCallback(IWallpaperManagerCallback cb, int userId) {
userId = ActivityManager.handleIncomingUser(Binder.getCallingPid(), Binder.getCallingUid(),
userId, true, true, "unregisterWallpaperColorsCallback", null);
synchronized (mLock) {
final RemoteCallbackList<IWallpaperManagerCallback> userColorsChangedListeners =
mColorsChangedListeners.get(userId);
if (userColorsChangedListeners != null) {
userColorsChangedListeners.unregister(cb);
}
}
}
@Override
public void onCreate() {
super.onCreate();
Log.v("AndroidRipperService", "onCreate()");
mCallbacks = new RemoteCallbackList<IAnrdoidRipperServiceCallback>();
ActivityManager activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE);
mBinder = new AndroidRipperServiceStub(this, activityManager);
server = new Server(this.mHandler);
server.startServer();
}
@Override
public void handleMessage(Message msg) {
RemoteCallbackList<IStatusCallbacks> callbacks;
if (service == null || service.get() == null)
return;
callbacks = service.get().mCallbacks;
// Broadcast to all clients the new value.
final int N = callbacks.beginBroadcast();
for (int i = 0; i < N; i++) {
try {
IStatusCallbacks broadcastItem = callbacks.getBroadcastItem(i);
switch (msg.what) {
case SEND_NEW_LOGITEM:
broadcastItem.newLogItem((LogItem) msg.obj);
break;
case SEND_NEW_BYTECOUNT:
Pair<Long, Long> inout = (Pair<Long, Long>) msg.obj;
broadcastItem.updateByteCount(inout.first, inout.second);
break;
case SEND_NEW_STATE:
sendUpdate(broadcastItem, (UpdateMessage) msg.obj);
break;
case SEND_NEW_CONNECTED_VPN:
broadcastItem.connectedVPN((String) msg.obj);
break;
}
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
callbacks.finishBroadcast();
}
BluetoothManagerService(Context context) {
mHandler = new BluetoothHandler(IoThread.get().getLooper());
mContext = context;
mPermissionReviewRequired = context.getResources()
.getBoolean(com.android.internal.R.bool.config_permissionReviewRequired);
mCrashes = 0;
mBluetooth = null;
mBluetoothBinder = null;
mBluetoothGatt = null;
mBinding = false;
mUnbinding = false;
mEnable = false;
mState = BluetoothAdapter.STATE_OFF;
mQuietEnableExternal = false;
mEnableExternal = false;
mAddress = null;
mName = null;
mErrorRecoveryRetryCounter = 0;
mContentResolver = context.getContentResolver();
// Observe BLE scan only mode settings change.
registerForBleScanModeChange();
mCallbacks = new RemoteCallbackList<IBluetoothManagerCallback>();
mStateChangeCallbacks = new RemoteCallbackList<IBluetoothStateChangeCallback>();
// TODO: We need a more generic way to initialize the persist keys of FeatureFlagUtils
boolean isHearingAidEnabled;
String value = SystemProperties.get(FeatureFlagUtils.PERSIST_PREFIX + FeatureFlagUtils.HEARING_AID_SETTINGS);
if (!TextUtils.isEmpty(value)) {
isHearingAidEnabled = Boolean.parseBoolean(value);
Log.v(TAG, "set feature flag HEARING_AID_SETTINGS to " + isHearingAidEnabled);
FeatureFlagUtils.setEnabled(context, FeatureFlagUtils.HEARING_AID_SETTINGS, isHearingAidEnabled);
}
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothAdapter.ACTION_LOCAL_NAME_CHANGED);
filter.addAction(BluetoothAdapter.ACTION_BLUETOOTH_ADDRESS_CHANGED);
filter.addAction(Intent.ACTION_SETTING_RESTORED);
filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
mContext.registerReceiver(mReceiver, filter);
loadStoredNameAndAddress();
if (isBluetoothPersistedStateOn()) {
if (DBG) {
Slog.d(TAG, "Startup: Bluetooth persisted state is ON.");
}
mEnableExternal = true;
}
String airplaneModeRadios =
Settings.Global.getString(mContentResolver, Settings.Global.AIRPLANE_MODE_RADIOS);
if (airplaneModeRadios == null || airplaneModeRadios.contains(
Settings.Global.RADIO_BLUETOOTH)) {
mContentResolver.registerContentObserver(
Settings.Global.getUriFor(Settings.Global.AIRPLANE_MODE_ON), true,
mAirplaneModeObserver);
}
int systemUiUid = -1;
try {
// Check if device is configured with no home screen, which implies no SystemUI.
boolean noHome = mContext.getResources().getBoolean(R.bool.config_noHomeScreen);
if (!noHome) {
systemUiUid = mContext.getPackageManager()
.getPackageUidAsUser("com.android.systemui", PackageManager.MATCH_SYSTEM_ONLY,
UserHandle.USER_SYSTEM);
}
Slog.d(TAG, "Detected SystemUiUid: " + Integer.toString(systemUiUid));
} catch (PackageManager.NameNotFoundException e) {
// Some platforms, such as wearables do not have a system ui.
Slog.w(TAG, "Unable to resolve SystemUI's UID.", e);
}
mSystemUiUid = systemUiUid;
}
private static <T extends IInterface> boolean emptyCallbackList(RemoteCallbackList<T> list) {
return (list == null || list.getRegisteredCallbackCount() == 0);
}
@Override
public boolean updateScores(ScoredNetwork[] networks) {
if (!isCallerActiveScorer(getCallingUid())) {
throw new SecurityException("Caller with UID " + getCallingUid() +
" is not the active scorer.");
}
final long token = Binder.clearCallingIdentity();
try {
// Separate networks by type.
Map<Integer, List<ScoredNetwork>> networksByType = new ArrayMap<>();
for (ScoredNetwork network : networks) {
List<ScoredNetwork> networkList = networksByType.get(network.networkKey.type);
if (networkList == null) {
networkList = new ArrayList<>();
networksByType.put(network.networkKey.type, networkList);
}
networkList.add(network);
}
// Pass the scores of each type down to the appropriate network scorer.
for (final Map.Entry<Integer, List<ScoredNetwork>> entry : networksByType.entrySet()) {
final RemoteCallbackList<INetworkScoreCache> callbackList;
final boolean isEmpty;
synchronized (mScoreCaches) {
callbackList = mScoreCaches.get(entry.getKey());
isEmpty = callbackList == null
|| callbackList.getRegisteredCallbackCount() == 0;
}
if (isEmpty) {
if (Log.isLoggable(TAG, Log.VERBOSE)) {
Log.v(TAG, "No scorer registered for type " + entry.getKey()
+ ", discarding");
}
continue;
}
final BiConsumer<INetworkScoreCache, Object> consumer =
FilteringCacheUpdatingConsumer.create(mContext, entry.getValue(),
entry.getKey());
sendCacheUpdateCallback(consumer, Collections.singleton(callbackList));
}
return true;
} finally {
Binder.restoreCallingIdentity(token);
}
}
public void registerCancelListenerLocked(IResultReceiver receiver) {
if (mCancelCallbacks == null) {
mCancelCallbacks = new RemoteCallbackList<>();
}
mCancelCallbacks.register(receiver);
}
public RemoteCallbackList<IResultReceiver> detachCancelListenersLocked() {
RemoteCallbackList<IResultReceiver> listeners = mCancelCallbacks;
mCancelCallbacks = null;
return listeners;
}
public BaseVpnService() {
callbacks = new RemoteCallbackList<>();
}
public BaseService() {
callbacks = new RemoteCallbackList<>();
}
public BaseVpnService() {
callbacks = new RemoteCallbackList<>();
}
public BaseService() {
callbacks = new RemoteCallbackList<>();
}
/**
* Returns a {@link Collection} of all {@link RemoteCallbackList}s that are currently active.
*
* <p>May be used to perform an action on all score caches without potentially strange behavior
* if a new scorer is registered during that action's execution.
*/
private Collection<RemoteCallbackList<INetworkScoreCache>> getScoreCacheLists() {
synchronized (mScoreCaches) {
return new ArrayList<>(mScoreCaches.values());
}
}
/**
* Unregister all CallBacks.
*
* @param cb
*/
synchronized public void unregisterAll() {
mCallbacks.kill();
mCallbacks = new RemoteCallbackList<IAnrdoidRipperServiceCallback>();
}