下面列出了android.view.ViewManager#android.util.Slog 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void cleanupUser(final int userHandle) {
Slog.i(TAG, "Calling onCleanupUser u" + userHandle);
final int serviceLen = mServices.size();
for (int i = 0; i < serviceLen; i++) {
final SystemService service = mServices.get(i);
Trace.traceBegin(Trace.TRACE_TAG_SYSTEM_SERVER, "onCleanupUser "
+ service.getClass().getName());
long time = SystemClock.elapsedRealtime();
try {
service.onCleanupUser(userHandle);
} catch (Exception ex) {
Slog.wtf(TAG, "Failure reporting cleanup of user " + userHandle
+ " to service " + service.getClass().getName(), ex);
}
warnIfTooLong(SystemClock.elapsedRealtime() - time, service, "onCleanupUser");
Trace.traceEnd(Trace.TRACE_TAG_SYSTEM_SERVER);
}
}
/**
* Removes a user and all data directories created for that user. This method should be called
* after the user's processes have been terminated.
* @param userHandle the user's id
*/
@Override
public boolean removeUser(int userHandle) {
Slog.i(LOG_TAG, "removeUser u" + userHandle);
checkManageOrCreateUsersPermission("Only the system can remove users");
final boolean isManagedProfile;
synchronized (mUsersLock) {
UserInfo userInfo = getUserInfoLU(userHandle);
isManagedProfile = userInfo != null && userInfo.isManagedProfile();
}
String restriction = isManagedProfile
? UserManager.DISALLOW_REMOVE_MANAGED_PROFILE : UserManager.DISALLOW_REMOVE_USER;
if (getUserRestrictions(UserHandle.getCallingUserId()).getBoolean(restriction, false)) {
Log.w(LOG_TAG, "Cannot remove user. " + restriction + " is enabled.");
return false;
}
return removeUserUnchecked(userHandle);
}
/**
* Positions the task stack at the given position in the task stack container.
*/
public void positionChildAt(StackWindowController child, int position) {
synchronized (mWindowMap) {
if (DEBUG_STACK) Slog.i(TAG_WM, "positionTaskStackAt: positioning stack=" + child
+ " at " + position);
if (mContainer == null) {
if (DEBUG_STACK) Slog.i(TAG_WM,
"positionTaskStackAt: could not find display=" + mContainer);
return;
}
if (child.mContainer == null) {
if (DEBUG_STACK) Slog.i(TAG_WM,
"positionTaskStackAt: could not find stack=" + this);
return;
}
mContainer.positionStackAt(position, child.mContainer);
}
}
/**
* We can easily change theme by modified colors hint. This function will check
* current theme mode and return the WallpaperColors fit current theme mode.
* If color need modified, it will return a copied WallpaperColors which
* its ColorsHint is modified to fit current theme mode.
*
* @param colors a wallpaper primary colors representation
*/
private WallpaperColors getThemeColorsLocked(WallpaperColors colors) {
if (colors == null) {
Slog.w(TAG, "Cannot get theme colors because WallpaperColors is null.");
return null;
}
int colorHints = colors.getColorHints();
boolean supportDarkTheme = (colorHints & WallpaperColors.HINT_SUPPORTS_DARK_THEME) != 0;
if (mThemeMode == Settings.Secure.THEME_MODE_WALLPAPER ||
(mThemeMode == Settings.Secure.THEME_MODE_LIGHT && !supportDarkTheme) ||
(mThemeMode == Settings.Secure.THEME_MODE_DARK && supportDarkTheme)) {
return colors;
}
WallpaperColors themeColors = new WallpaperColors(colors.getPrimaryColor(),
colors.getSecondaryColor(), colors.getTertiaryColor());
if (mThemeMode == Settings.Secure.THEME_MODE_LIGHT) {
colorHints &= ~WallpaperColors.HINT_SUPPORTS_DARK_THEME;
} else if (mThemeMode == Settings.Secure.THEME_MODE_DARK) {
colorHints |= WallpaperColors.HINT_SUPPORTS_DARK_THEME;
}
themeColors.setColorHints(colorHints);
return themeColors;
}
void restoreRoute(int uid) {
ClientRecord clientRecord = null;
synchronized (mLock) {
UserRecord userRecord = mUserRecords.get(UserHandle.getUserId(uid));
if (userRecord != null && userRecord.mClientRecords != null) {
for (ClientRecord cr : userRecord.mClientRecords) {
if (validatePackageName(uid, cr.mPackageName)) {
clientRecord = cr;
break;
}
}
}
}
if (clientRecord != null) {
try {
clientRecord.mClient.onRestoreRoute();
} catch (RemoteException e) {
Slog.w(TAG, "Failed to call onRestoreRoute. Client probably died.");
}
} else {
restoreBluetoothA2dp();
}
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_TIME_TICK)) {
if (DEBUG_BATCH) {
Slog.v(TAG, "Received TIME_TICK alarm; rescheduling");
}
synchronized (mLock) {
mLastTickReceived = System.currentTimeMillis();
}
scheduleTimeTickEvent();
} else if (intent.getAction().equals(Intent.ACTION_DATE_CHANGED)) {
// Since the kernel does not keep track of DST, we need to
// reset the TZ information at the beginning of each day
// based off of the current Zone gmt offset + userspace tracked
// daylight savings information.
TimeZone zone = TimeZone.getTimeZone(SystemProperties.get(TIMEZONE_PROPERTY));
int gmtOffset = zone.getOffset(System.currentTimeMillis());
setKernelTimezone(mNativeData, -(gmtOffset / 60000));
scheduleDateChangedEvent();
}
}
private void removeClient(ClientMonitor client) {
if (client != null) {
client.destroy();
if (client != mCurrentClient && mCurrentClient != null) {
Slog.w(TAG, "Unexpected client: " + client.getOwnerString() + "expected: "
+ mCurrentClient != null ? mCurrentClient.getOwnerString() : "null");
}
}
if (mCurrentClient != null) {
if (DEBUG) Slog.v(TAG, "Done with client: " + client.getOwnerString());
mCurrentClient = null;
}
if (mPendingClient == null) {
notifyClientActiveCallbacks(false);
}
}
int executeTimeoutCommand(PrintWriter pw, String pkgName, int userId,
boolean hasJobId, int jobId) {
if (DEBUG) {
Slog.v(TAG, "executeTimeoutCommand(): " + pkgName + "/" + userId + " " + jobId);
}
synchronized (mLock) {
boolean foundSome = false;
for (int i=0; i<mActiveServices.size(); i++) {
final JobServiceContext jc = mActiveServices.get(i);
final JobStatus js = jc.getRunningJobLocked();
if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) {
foundSome = true;
pw.print("Timing out: ");
js.printUniqueId(pw);
pw.print(" ");
pw.println(js.getServiceComponent().flattenToShortString());
}
}
if (!foundSome) {
pw.println("No matching executing jobs found.");
}
}
return 0;
}
final void logBroadcastReceiverDiscardLocked(BroadcastRecord r) {
final int logIndex = r.nextReceiver - 1;
if (logIndex >= 0 && logIndex < r.receivers.size()) {
Object curReceiver = r.receivers.get(logIndex);
if (curReceiver instanceof BroadcastFilter) {
BroadcastFilter bf = (BroadcastFilter) curReceiver;
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_FILTER,
bf.owningUserId, System.identityHashCode(r),
r.intent.getAction(), logIndex, System.identityHashCode(bf));
} else {
ResolveInfo ri = (ResolveInfo) curReceiver;
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
UserHandle.getUserId(ri.activityInfo.applicationInfo.uid),
System.identityHashCode(r), r.intent.getAction(), logIndex, ri.toString());
}
} else {
if (logIndex < 0) Slog.w(TAG,
"Discarding broadcast before first receiver is invoked: " + r);
EventLog.writeEvent(EventLogTags.AM_BROADCAST_DISCARD_APP,
-1, System.identityHashCode(r),
r.intent.getAction(),
r.nextReceiver,
"NONE");
}
}
private void stopServiceLocked(ServiceRecord service) {
if (service.delayed) {
// If service isn't actually running, but is 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;
}
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);
}
void setStandbyMode(boolean isStandbyModeOn) {
assertRunOnServiceThread();
if (isPowerOnOrTransient() && isStandbyModeOn) {
mPowerManager.goToSleep(SystemClock.uptimeMillis(),
PowerManager.GO_TO_SLEEP_REASON_HDMI, 0);
if (playback() != null) {
playback().sendStandby(0 /* unused */);
}
} else if (isPowerStandbyOrTransient() && !isStandbyModeOn) {
mPowerManager.wakeUp(SystemClock.uptimeMillis(), "android.server.hdmi:WAKE");
if (playback() != null) {
oneTouchPlay(new IHdmiControlCallback.Stub() {
@Override
public void onComplete(int result) {
if (result != HdmiControlManager.RESULT_SUCCESS) {
Slog.w(TAG, "Failed to complete 'one touch play'. result=" + result);
}
}
});
}
}
}
/**
* Stops the dream and detaches from the window.
* <p>
* When the dream ends, the system will be allowed to go to sleep fully unless there
* is a reason for it to be awake such as recent user activity or wake locks being held.
* </p>
*/
public final void finish() {
if (mDebug) Slog.v(TAG, "finish(): mFinished=" + mFinished);
if (!mFinished) {
mFinished = true;
if (mWindowToken == null) {
Slog.w(TAG, "Finish was called before the dream was attached.");
} else {
try {
mSandman.finishSelf(mWindowToken, true /*immediate*/);
} catch (RemoteException ex) {
// system server died
}
}
stopSelf(); // if launched via any other means
}
}
@GuardedBy("mCache")
private void invalidateCacheLocked(int userId, String providerPackageName, Uri uri) {
ArrayMap<String, ArrayMap<Pair<String, Uri>, Bundle>> userCache = mCache.get(userId);
if (userCache == null) return;
ArrayMap<Pair<String, Uri>, Bundle> packageCache = userCache.get(providerPackageName);
if (packageCache == null) return;
if (uri != null) {
for (int i = 0; i < packageCache.size();) {
final Pair<String, Uri> key = packageCache.keyAt(i);
if (key.second != null && key.second.toString().startsWith(uri.toString())) {
if (DEBUG) Slog.d(TAG, "Invalidating cache for key " + key);
packageCache.removeAt(i);
} else {
i++;
}
}
} else {
if (DEBUG) Slog.d(TAG, "Invalidating cache for package " + providerPackageName);
packageCache.clear();
}
}
@Override
public void onPackageUpdateFinished(String packageName, int uid) {
synchronized (mLock) {
if (mCurrentUserId != getChangingUserId()) {
return;
}
WallpaperData wallpaper = mWallpaperMap.get(mCurrentUserId);
if (wallpaper != null) {
final ComponentName wpService = wallpaper.wallpaperComponent;
if (wpService != null && wpService.getPackageName().equals(packageName)) {
if (DEBUG_LIVE) {
Slog.i(TAG, "Wallpaper " + wpService + " update has finished");
}
wallpaper.wallpaperUpdating = false;
clearWallpaperComponentLocked(wallpaper);
if (!bindWallpaperComponentLocked(wpService, false, false,
wallpaper, null)) {
Slog.w(TAG, "Wallpaper " + wpService
+ " no longer available; reverting to default");
clearWallpaperLocked(false, FLAG_SYSTEM, wallpaper.userId, null);
}
}
}
}
}
/**
* Open a pin metadata file in the zip if one is present.
*
* @param zipFile Zip file to search
* @return Open input stream or null on any error
*/
private static InputStream maybeOpenPinMetaInZip(ZipFile zipFile, String fileName) {
ZipEntry pinMetaEntry = zipFile.getEntry(PIN_META_FILENAME);
InputStream pinMetaStream = null;
if (pinMetaEntry != null) {
try {
pinMetaStream = zipFile.getInputStream(pinMetaEntry);
} catch (IOException ex) {
Slog.w(TAG,
String.format("error reading pin metadata \"%s\": pinning as blob",
fileName),
ex);
}
}
return pinMetaStream;
}
private void handleDestroyBackupAgent(CreateBackupAgentData data) {
if (DEBUG_BACKUP) Slog.v(TAG, "handleDestroyBackupAgent: " + data);
LoadedApk packageInfo = getPackageInfoNoCheck(data.appInfo, data.compatInfo);
String packageName = packageInfo.mPackageName;
BackupAgent agent = mBackupAgents.get(packageName);
if (agent != null) {
try {
agent.onDestroy();
} catch (Exception e) {
Slog.w(TAG, "Exception thrown in onDestroy by backup agent of " + data.appInfo);
e.printStackTrace();
}
mBackupAgents.remove(packageName);
} else {
Slog.w(TAG, "Attempt to destroy unknown backup agent " + data);
}
}
/**
* Removes a {@link DataUsageRequest} if the calling uid is authorized.
* Should only be called from the handler thread otherwise there will be a race condition
* on mDataUsageRequests.
*/
private void handleUnregister(DataUsageRequest request, int callingUid) {
RequestInfo requestInfo;
requestInfo = mDataUsageRequests.get(request.requestId);
if (requestInfo == null) {
if (LOGV) Slog.v(TAG, "Trying to unregister unknown request " + request);
return;
}
if (Process.SYSTEM_UID != callingUid && requestInfo.mCallingUid != callingUid) {
Slog.w(TAG, "Caller uid " + callingUid + " is not owner of " + request);
return;
}
if (LOGV) Slog.v(TAG, "Unregistering " + request);
mDataUsageRequests.remove(request.requestId);
requestInfo.unlinkDeathRecipient();
requestInfo.callCallback(NetworkStatsManager.CALLBACK_RELEASED);
}
@Override // Binder call
public String getCurrentKeyboardLayoutForInputDevice(InputDeviceIdentifier identifier) {
String key = getLayoutDescriptor(identifier);
synchronized (mDataStore) {
String layout = null;
// try loading it using the layout descriptor if we have it
layout = mDataStore.getCurrentKeyboardLayout(key);
if (layout == null && !key.equals(identifier.getDescriptor())) {
// if it doesn't exist fall back to the device descriptor
layout = mDataStore.getCurrentKeyboardLayout(identifier.getDescriptor());
}
if (DEBUG) {
Slog.d(TAG, "Loaded keyboard layout id for " + key + " and got "
+ layout);
}
return layout;
}
}
public static void diagnoseCheckers(final List<HandlerChecker> blockedCheckers) {
PrintWriter out = new PrintWriter(new LogWriter(Log.WARN, Watchdog.TAG, Log.LOG_ID_SYSTEM),
true);
for (int i=0; i<blockedCheckers.size(); i++) {
Thread blockedThread = blockedCheckers.get(i).getThread();
if (printAnnotatedStack(blockedThread, out)) {
continue;
}
// Fall back to "regular" stack trace, if necessary.
Slog.w(Watchdog.TAG, blockedThread.getName() + " stack trace:");
StackTraceElement[] stackTrace = blockedThread.getStackTrace();
for (StackTraceElement element : stackTrace) {
Slog.w(Watchdog.TAG, " at " + element);
}
}
}
@Override
public void onBootComplete() {
if (DEBUG) Slog.d(TAG, "onBootComplete");
if (mBootComplete) return;
mBootComplete = true;
final IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MANAGED_PROFILE_ADDED);
filter.addAction(Intent.ACTION_MANAGED_PROFILE_REMOVED);
mContext.registerReceiver(new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
reloadTrackers();
}
}, filter);
reloadTrackers();
}
public void immersiveModeChangedLw(String pkg, boolean isImmersiveMode,
boolean userSetupComplete, boolean navBarEmpty) {
mHandler.removeMessages(H.SHOW);
if (isImmersiveMode) {
final boolean disabled = PolicyControl.disableImmersiveConfirmation(pkg);
if (DEBUG) Slog.d(TAG, String.format("immersiveModeChanged() disabled=%s mConfirmed=%s",
disabled, mConfirmed));
if (!disabled
&& (DEBUG_SHOW_EVERY_TIME || !mConfirmed)
&& userSetupComplete
&& !mVrModeEnabled
&& !navBarEmpty
&& !UserManager.isDeviceInDemoMode(mContext)
&& (mLockTaskState != LOCK_TASK_MODE_LOCKED)) {
mHandler.sendEmptyMessageDelayed(H.SHOW, mShowDelayMs);
}
} else {
mHandler.sendEmptyMessage(H.HIDE);
}
}
/**
* Called when there has been user activity.
*/
public void onUserActivity(int event, int uid) {
if (DEBUG) {
Slog.d(TAG, "onUserActivity: event=" + event + ", uid=" + uid);
}
try {
mBatteryStats.noteUserActivity(uid, event);
} catch (RemoteException ex) {
// Ignore
}
synchronized (mLock) {
if (!mUserActivityPending) {
mUserActivityPending = true;
Message msg = mHandler.obtainMessage(MSG_USER_ACTIVITY);
msg.setAsynchronous(true);
mHandler.sendMessage(msg);
}
}
}
private void writeXmlToFile(List<CacheQuotaHint> processedRequests) {
FileOutputStream fileStream = null;
try {
XmlSerializer out = new FastXmlSerializer();
fileStream = mPreviousValuesFile.startWrite();
out.setOutput(fileStream, StandardCharsets.UTF_8.name());
saveToXml(out, processedRequests, 0);
mPreviousValuesFile.finishWrite(fileStream);
} catch (Exception e) {
Slog.e(TAG, "An error occurred while writing the cache quota file.", e);
mPreviousValuesFile.failWrite(fileStream);
}
}
private void dumpInternal(PrintWriter pw) {
JSONObject dump = new JSONObject();
try {
dump.put("service", "Fingerprint Manager");
JSONArray sets = new JSONArray();
for (UserInfo user : UserManager.get(getContext()).getUsers()) {
final int userId = user.getUserHandle().getIdentifier();
final int N = mFingerprintUtils.getFingerprintsForUser(mContext, userId).size();
PerformanceStats stats = mPerformanceMap.get(userId);
PerformanceStats cryptoStats = mCryptoPerformanceMap.get(userId);
JSONObject set = new JSONObject();
set.put("id", userId);
set.put("count", N);
set.put("accept", (stats != null) ? stats.accept : 0);
set.put("reject", (stats != null) ? stats.reject : 0);
set.put("acquire", (stats != null) ? stats.acquire : 0);
set.put("lockout", (stats != null) ? stats.lockout : 0);
set.put("permanentLockout", (stats != null) ? stats.permanentLockout : 0);
// cryptoStats measures statistics about secure fingerprint transactions
// (e.g. to unlock password storage, make secure purchases, etc.)
set.put("acceptCrypto", (cryptoStats != null) ? cryptoStats.accept : 0);
set.put("rejectCrypto", (cryptoStats != null) ? cryptoStats.reject : 0);
set.put("acquireCrypto", (cryptoStats != null) ? cryptoStats.acquire : 0);
set.put("lockoutCrypto", (cryptoStats != null) ? cryptoStats.lockout : 0);
set.put("permanentLockoutCrypto",
(cryptoStats != null) ? cryptoStats.permanentLockout : 0);
sets.put(set);
}
dump.put("prints", sets);
} catch (JSONException e) {
Slog.e(TAG, "dump formatting failure", e);
}
pw.println(dump);
}
@GuardedBy("mLock")
public final void bindInnerLocked(boolean resetBackoff) {
unscheduleRebindLocked();
if (mBound) {
return;
}
mBound = true;
if (resetBackoff) {
// Note this is the only place we reset the backoff time.
mNextBackoffMs = mRebindBackoffMs;
}
final Intent service = new Intent().setComponent(mComponentName);
if (DEBUG) {
Slog.d(mTag, "Attempting to connect to " + mComponentName);
}
final boolean success = mContext.bindServiceAsUser(service, mServiceConnection,
Context.BIND_AUTO_CREATE | Context.BIND_FOREGROUND_SERVICE,
mHandler, UserHandle.of(mUserId));
if (!success) {
Slog.e(mTag, "Binding: " + service.getComponent() + " u" + mUserId
+ " failed.");
}
}
/**
* Notifies that {@param appWindow} has finished resuming.
*/
void notifyAppResumedFinished(@NonNull AppWindowToken appWindow) {
if (mUnknownApps.containsKey(appWindow)
&& mUnknownApps.get(appWindow) == UNKNOWN_STATE_WAITING_RESUME) {
if (DEBUG_UNKNOWN_APP_VISIBILITY) {
Slog.d(TAG, "App resume finished appWindow=" + appWindow);
}
mUnknownApps.put(appWindow, UNKNOWN_STATE_WAITING_RELAYOUT);
}
}
private boolean parseAllMetaData(Resources res,
XmlPullParser parser, AttributeSet attrs, String tag,
Component outInfo, String[] outError)
throws XmlPullParserException, IOException {
int outerDepth = parser.getDepth();
int type;
while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
&& (type != XmlPullParser.END_TAG
|| parser.getDepth() > outerDepth)) {
if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) {
continue;
}
if (parser.getName().equals("meta-data")) {
if ((outInfo.metaData=parseMetaData(res, parser, attrs,
outInfo.metaData, outError)) == null) {
return false;
}
} else {
if (!RIGID_PARSER) {
Slog.w(TAG, "Unknown element under " + tag + ": "
+ parser.getName() + " at " + mArchiveSourcePath + " "
+ parser.getPositionDescription());
XmlUtils.skipCurrentTag(parser);
continue;
} else {
outError[0] = "Bad element under " + tag + ": " + parser.getName();
return false;
}
}
}
return true;
}
/**
* Called to set an application's persistent VR thread.
*
* <p>This will fail if the system does not have the persistent VR flag set. If this succeeds,
* any previous VR thread will be returned to a normal sheduling priority; if this fails,
* the scheduling for the previous thread will be unaffected.
*
* <p>Note: This must be called with the global ActivityManagerService lock and the
* mPidsSelfLocked object locks held.
*
* @param tid the tid of the thread to set, or 0 to unset the current thread.
* @param pid the pid of the process owning the thread to set.
* @param proc the ProcessRecord of the process owning the thread to set.
*/
public void setPersistentVrThreadLocked(int tid, int pid, ProcessRecord proc) {
if (!hasPersistentVrFlagSet()) {
Slog.w(TAG, "Persistent VR thread may only be set in persistent VR mode!");
return;
}
if (proc == null) {
Slog.w(TAG, "Persistent VR thread not set, calling process doesn't exist!");
return;
}
if (tid != 0) {
enforceThreadInProcess(tid, pid);
}
setPersistentVrRenderThreadLocked(tid, false);
}
private void setCallingPidForRemoteAnimationAdapter(ActivityOptions options, int callingPid) {
final RemoteAnimationAdapter adapter = options.getRemoteAnimationAdapter();
if (adapter == null) {
return;
}
if (callingPid == Process.myPid()) {
Slog.wtf(TAG, "Safe activity options constructed after clearing calling id");
return;
}
adapter.setCallingPid(callingPid);
}
private void setStandbyEnabled(boolean standby) {
synchronized(mLock) {
if (!mBootsToVr) {
Slog.e(TAG, "Attempting to set standby mode on a non-standalone device");
return;
}
mStandby = standby;
updateVrModeAllowedLocked();
}
}