下面列出了怎么用android.util.EventLog的API类实例代码及写法,或者点击链接到github查看源代码。
final void handleLowMemory() {
ArrayList<ComponentCallbacks2> callbacks;
synchronized (mPackages) {
callbacks = collectComponentCallbacksLocked(true, null);
}
final int N = callbacks.size();
for (int i=0; i<N; i++) {
callbacks.get(i).onLowMemory();
}
// Ask SQLite to free up as much memory as it can, mostly from its page caches.
if (Process.myUid() != Process.SYSTEM_UID) {
int sqliteReleased = SQLiteDatabase.releaseMemory();
EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
}
// Ask graphics to free up as much as possible (font/image caches)
Canvas.freeCaches();
// Ask text layout engine to free also as much as possible
Canvas.freeTextLayoutCaches();
BinderInternal.forceGc("mem");
}
final void handleLowMemory() {
ArrayList<ComponentCallbacks2> callbacks;
synchronized (mPackages) {
callbacks = collectComponentCallbacksLocked(true, null);
}
final int N = callbacks.size();
for (int i=0; i<N; i++) {
callbacks.get(i).onLowMemory();
}
// Ask SQLite to free up as much memory as it can, mostly from its page caches.
if (Process.myUid() != Process.SYSTEM_UID) {
int sqliteReleased = SQLiteDatabase.releaseMemory();
EventLog.writeEvent(SQLITE_MEM_RELEASED_EVENT_LOG_TAG, sqliteReleased);
}
// Ask graphics to free up as much as possible (font/image caches)
Canvas.freeCaches();
BinderInternal.forceGc("mem");
}
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 maybeLogUpdateToEventLog(
long durationMillis, Uri uri, String operation, String selection) {
if (!ENABLE_CONTENT_SAMPLE) return;
int samplePercent = samplePercentForDuration(durationMillis);
if (samplePercent < 100) {
synchronized (mRandom) {
if (mRandom.nextInt(100) >= samplePercent) {
return;
}
}
}
String blockingPackage = AppGlobals.getInitialPackage();
EventLog.writeEvent(
EventLogTags.CONTENT_UPDATE_SAMPLE,
uri.toString(),
operation,
selection != null ? selection : "",
durationMillis,
blockingPackage != null ? blockingPackage : "",
samplePercent);
}
private void maybeLogUpdateToEventLog(
long durationMillis, Uri uri, String operation, String selection) {
if (!ENABLE_CONTENT_SAMPLE) return;
int samplePercent = samplePercentForDuration(durationMillis);
if (samplePercent < 100) {
synchronized (mRandom) {
if (mRandom.nextInt(100) >= samplePercent) {
return;
}
}
}
String blockingPackage = AppGlobals.getInitialPackage();
EventLog.writeEvent(
EventLogTags.CONTENT_UPDATE_SAMPLE,
uri.toString(),
operation,
selection != null ? selection : "",
durationMillis,
blockingPackage != null ? blockingPackage : "",
samplePercent);
}
private void collectBrightnessAdjustmentSample() {
if (mBrightnessAdjustmentSamplePending) {
mBrightnessAdjustmentSamplePending = false;
if (mAmbientLuxValid && mScreenAutoBrightness >= 0) {
if (DEBUG) {
Slog.d(TAG, "Auto-brightness adjustment changed by user: " +
"lux=" + mAmbientLux + ", " +
"brightness=" + mScreenAutoBrightness + ", " +
"ring=" + mAmbientLightRingBuffer);
}
EventLog.writeEvent(EventLogTags.AUTO_BRIGHTNESS_ADJ,
mBrightnessAdjustmentSampleOldLux,
mBrightnessAdjustmentSampleOldBrightness,
mAmbientLux,
mScreenAutoBrightness);
}
}
}
@Override
void removeChild(AppWindowToken token) {
if (!mChildren.contains(token)) {
Slog.e(TAG, "removeChild: token=" + this + " not found.");
return;
}
super.removeChild(token);
if (mChildren.isEmpty()) {
EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "removeAppToken: last token");
if (mDeferRemoval) {
removeIfPossible();
}
}
}
public TaskWindowContainerController(int taskId, TaskWindowContainerListener listener,
StackWindowController stackController, int userId, Rect bounds, int resizeMode,
boolean supportsPictureInPicture, boolean toTop, boolean showForAllUsers,
TaskDescription taskDescription, WindowManagerService service) {
super(listener, service);
mTaskId = taskId;
mHandler = new H(new WeakReference<>(this), service.mH.getLooper());
synchronized(mWindowMap) {
if (DEBUG_STACK) Slog.i(TAG_WM, "TaskWindowContainerController: taskId=" + taskId
+ " stack=" + stackController + " bounds=" + bounds);
final TaskStack stack = stackController.mContainer;
if (stack == null) {
throw new IllegalArgumentException("TaskWindowContainerController: invalid stack="
+ stackController);
}
EventLog.writeEvent(WM_TASK_CREATED, taskId, stack.mStackId);
final Task task = createTask(taskId, stack, userId, resizeMode,
supportsPictureInPicture, taskDescription);
final int position = toTop ? POSITION_TOP : POSITION_BOTTOM;
// We only want to move the parents to the parents if we are creating this task at the
// top of its stack.
stack.addTask(task, position, showForAllUsers, toTop /* moveParents */);
}
}
WindowState computeFocusedWindow() {
// While the keyguard is showing, we must focus anything besides the main display.
// Otherwise we risk input not going to the keyguard when the user expects it to.
final boolean forceDefaultDisplay = mService.isKeyguardShowingAndNotOccluded();
for (int i = mChildren.size() - 1; i >= 0; i--) {
final DisplayContent dc = mChildren.get(i);
final WindowState win = dc.findFocusedWindow();
if (win != null) {
if (forceDefaultDisplay && !dc.isDefaultDisplay) {
EventLog.writeEvent(0x534e4554, "71786287", win.mOwnerUid, "");
continue;
}
return win;
}
}
return null;
}
@Override
void onParentSet() {
super.onParentSet();
if (getParent() != null || mDisplayContent == null) {
return;
}
EventLog.writeEvent(EventLogTags.WM_STACK_REMOVED, mStackId);
if (mAnimationBackgroundSurface != null) {
mAnimationBackgroundSurface.destroy();
mAnimationBackgroundSurface = null;
}
mDisplayContent = null;
mService.mWindowPlacerLocked.requestTraversal();
}
private void logAppDisplayed(WindowingModeTransitionInfoSnapshot info) {
if (info.type != TYPE_TRANSITION_WARM_LAUNCH && info.type != TYPE_TRANSITION_COLD_LAUNCH) {
return;
}
EventLog.writeEvent(AM_ACTIVITY_LAUNCH_TIME,
info.userId, info.activityRecordIdHashCode, info.launchedActivityShortComponentName,
info.windowsDrawnDelayMs);
StringBuilder sb = mStringBuilder;
sb.setLength(0);
sb.append("Displayed ");
sb.append(info.launchedActivityShortComponentName);
sb.append(": ");
TimeUtils.formatDuration(info.windowsDrawnDelayMs, sb);
Log.i(TAG, sb.toString());
}
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");
}
}
void kill(String reason, boolean noisy) {
if (!killedByAm) {
Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "kill");
if (mService != null && (noisy || info.uid == mService.mCurOomAdjUid)) {
mService.reportUidInfoMessageLocked(TAG,
"Killing " + toShortString() + " (adj " + setAdj + "): " + reason,
info.uid);
}
if (pid > 0) {
EventLog.writeEvent(EventLogTags.AM_KILL, userId, pid, processName, setAdj, reason);
Process.killProcessQuiet(pid);
ActivityManagerService.killProcessGroup(uid, pid);
} else {
pendingStart = false;
}
if (!persistent) {
killed = true;
killedByAm = true;
}
Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
}
}
private void maybeLogUpdateToEventLog(
long durationMillis, Uri uri, String operation, String selection) {
if (!ENABLE_CONTENT_SAMPLE) return;
int samplePercent = samplePercentForDuration(durationMillis);
if (samplePercent < 100) {
synchronized (mRandom) {
if (mRandom.nextInt(100) >= samplePercent) {
return;
}
}
}
String blockingPackage = AppGlobals.getInitialPackage();
EventLog.writeEvent(
EventLogTags.CONTENT_UPDATE_SAMPLE,
uri.toString(),
operation,
selection != null ? selection : "",
durationMillis,
blockingPackage != null ? blockingPackage : "",
samplePercent);
}
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
ActivityClientRecord r = mActivities.get(token);
if (localLOGV) Slog.v(TAG, "Performing resume of " + r
+ " finished=" + r.activity.mFinished);
if (r != null && !r.activity.mFinished) {
if (clearHide) {
r.hideForNow = false;
r.activity.mStartedActivity = false;
}
try {
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults);
r.pendingResults = null;
}
r.activity.performResume();
EventLog.writeEvent(LOG_ON_RESUME_CALLED,
r.activity.getComponentName().getClassName());
r.paused = false;
r.stopped = false;
r.state = null;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to resume activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
}
return r;
}
public final ActivityClientRecord performResumeActivity(IBinder token,
boolean clearHide) {
ActivityClientRecord r = mActivities.get(token);
if (localLOGV) Slog.v(TAG, "Performing resume of " + r
+ " finished=" + r.activity.mFinished);
if (r != null && !r.activity.mFinished) {
if (clearHide) {
r.hideForNow = false;
r.activity.mStartedActivity = false;
}
try {
if (r.pendingIntents != null) {
deliverNewIntents(r, r.pendingIntents);
r.pendingIntents = null;
}
if (r.pendingResults != null) {
deliverResults(r, r.pendingResults);
r.pendingResults = null;
}
r.activity.performResume();
EventLog.writeEvent(LOG_ON_RESUME_CALLED,
r.activity.getComponentName().getClassName());
r.paused = false;
r.stopped = false;
r.state = null;
} catch (Exception e) {
if (!mInstrumentation.onException(r.activity, e)) {
throw new RuntimeException(
"Unable to resume activity "
+ r.intent.getComponent().toShortString()
+ ": " + e.toString(), e);
}
}
}
return r;
}
@Override
public void onReceive(final Context context, final Intent intent) {
new Thread() {
@Override
public void run() {
try {
// get the content path from the extras
byte[] altContent = getAltContent(context, intent);
// get the version from the extras
int altVersion = getVersionFromIntent(intent);
// get the previous value from the extras
String altRequiredHash = getRequiredHashFromIntent(intent);
// get the version currently being used
int currentVersion = getCurrentVersion();
// get the hash of the currently used value
String currentHash = getCurrentHash(getCurrentContent());
if (!verifyVersion(currentVersion, altVersion)) {
Slog.i(TAG, "Not installing, new version is <= current version");
} else if (!verifyPreviousHash(currentHash, altRequiredHash)) {
EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED,
"Current hash did not match required value");
} else {
// install the new content
Slog.i(TAG, "Found new update, installing...");
install(altContent, altVersion);
Slog.i(TAG, "Installation successful");
postInstall(context, intent);
}
} catch (Exception e) {
Slog.e(TAG, "Could not update content!", e);
// keep the error message <= 100 chars
String errMsg = e.toString();
if (errMsg.length() > 100) {
errMsg = errMsg.substring(0, 99);
}
EventLog.writeEvent(EventLogTags.CONFIG_INSTALL_FAILED, errMsg);
}
}
}.start();
}
@Override
void removeImmediately() {
if (DEBUG_STACK) Slog.i(TAG, "removeTask: removing taskId=" + mTaskId);
EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "removeTask");
mDeferRemoval = false;
super.removeImmediately();
}
void reparent(TaskStack stack, int position, boolean moveParents) {
if (stack == mStack) {
throw new IllegalArgumentException(
"task=" + this + " already child of stack=" + mStack);
}
if (DEBUG_STACK) Slog.i(TAG, "reParentTask: removing taskId=" + mTaskId
+ " from stack=" + mStack);
EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "reParentTask");
final DisplayContent prevDisplayContent = getDisplayContent();
// If we are moving from the fullscreen stack to the pinned stack
// then we want to preserve our insets so that there will not
// be a jump in the area covered by system decorations. We rely
// on the pinned animation to later unset this value.
if (stack.inPinnedWindowingMode()) {
mPreserveNonFloatingState = true;
} else {
mPreserveNonFloatingState = false;
}
getParent().removeChild(this);
stack.addTask(this, position, showForAllUsers(), moveParents);
// Relayout display(s).
final DisplayContent displayContent = stack.getDisplayContent();
displayContent.setLayoutNeeded();
if (prevDisplayContent != displayContent) {
onDisplayChanged(displayContent);
prevDisplayContent.setLayoutNeeded();
}
}
TaskStack(WindowManagerService service, int stackId, StackWindowController controller) {
super(service);
mStackId = stackId;
setController(controller);
mDockedStackMinimizeThickness = service.mContext.getResources().getDimensionPixelSize(
com.android.internal.R.dimen.docked_stack_minimize_thickness);
EventLog.writeEvent(EventLogTags.WM_STACK_CREATED, stackId);
}
/**
* Overridden version of {@link TaskStack#positionChildAt(int, Task, boolean)}. Used in
* {@link TaskStack#addTask(Task, int, boolean showForAllUsers, boolean)}, as it can receive
* showForAllUsers param from {@link AppWindowToken} instead of {@link Task#showForAllUsers()}.
*/
private void positionChildAt(int position, Task child, boolean includingParents,
boolean showForAllUsers) {
final int targetPosition = findPositionForTask(child, position, showForAllUsers,
false /* addingNew */);
super.positionChildAt(targetPosition, child, includingParents);
// Log positioning.
if (DEBUG_TASK_MOVEMENT)
Slog.d(TAG_WM, "positionTask: task=" + this + " position=" + position);
final int toTop = targetPosition == mChildren.size() - 1 ? 1 : 0;
EventLog.writeEvent(EventLogTags.WM_TASK_MOVED, child.mTaskId, toTop, targetPosition);
}
private void sendWakeUpBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending wake up broadcast.");
}
if (mActivityManagerInternal.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOnIntent, UserHandle.ALL, null,
mWakeUpBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 2, 1);
sendNextBroadcast();
}
}
private void sendGoToSleepBroadcast() {
if (DEBUG) {
Slog.d(TAG, "Sending go to sleep broadcast.");
}
if (mActivityManagerInternal.isSystemReady()) {
mContext.sendOrderedBroadcastAsUser(mScreenOffIntent, UserHandle.ALL, null,
mGoToSleepBroadcastDone, mHandler, 0, null, null);
} else {
EventLog.writeEvent(EventLogTags.POWER_SCREEN_BROADCAST_STOP, 3, 1);
sendNextBroadcast();
}
}
public void stopSyncEvent(long rowId, SyncOperation syncOperation, String resultMessage,
int upstreamActivity, int downstreamActivity, long elapsedTime) {
EventLog.writeEvent(2720,
syncOperation.toEventLog(SyncStorageEngine.EVENT_STOP));
mSyncStorageEngine.stopSyncEvent(rowId, elapsedTime,
resultMessage, downstreamActivity, upstreamActivity);
}
@Override
public void setTestProviderLocation(String provider, Location loc, String opPackageName) {
if (!canCallerAccessMockLocation(opPackageName)) {
return;
}
synchronized (mLock) {
MockProvider mockProvider = mMockProviders.get(provider);
if (mockProvider == null) {
throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
}
// Ensure that the location is marked as being mock. There's some logic to do this in
// handleLocationChanged(), but it fails if loc has the wrong provider (bug 33091107).
Location mock = new Location(loc);
mock.setIsFromMockProvider(true);
if (!TextUtils.isEmpty(loc.getProvider()) && !provider.equals(loc.getProvider())) {
// The location has an explicit provider that is different from the mock provider
// name. The caller may be trying to fool us via bug 33091107.
EventLog.writeEvent(0x534e4554, "33091107", Binder.getCallingUid(),
provider + "!=" + loc.getProvider());
}
// clear calling identity so INSTALL_LOCATION_PROVIDER permission is not required
long identity = Binder.clearCallingIdentity();
mockProvider.setLocation(mock);
Binder.restoreCallingIdentity(identity);
}
}
Event(EventLog.Event nativeEvent) {
mTimeMillis = TimeUnit.MILLISECONDS.convert(
nativeEvent.getTimeNanos(), TimeUnit.NANOSECONDS);
mPid = nativeEvent.getProcessId();
mUid = nativeEvent.getUid();
mData = nativeEvent.getData();
}
public void readEvents(int[] tags, long horizonMs, Collection<Event> events)
throws IOException {
// Testing in Android: the Static Final Class Strikes Back!
ArrayList<EventLog.Event> nativeEvents = new ArrayList<>();
long horizonNs = TimeUnit.NANOSECONDS.convert(horizonMs, TimeUnit.MILLISECONDS);
EventLog.readEventsOnWrapping(tags, horizonNs, nativeEvents);
for (EventLog.Event nativeEvent : nativeEvents) {
Event event = new Event(nativeEvent);
events.add(event);
}
}
/**
* Create a BluetoothHidDeviceAppSdpSettings object for the Bluetooth SDP record.
*
* @param name Name of this Bluetooth HID device. Maximum length is 50 bytes.
* @param description Description for this Bluetooth HID device. Maximum length is 50 bytes.
* @param provider Provider of this Bluetooth HID device. Maximum length is 50 bytes.
* @param subclass Subclass of this Bluetooth HID device. See <a
* href="www.usb.org/developers/hidpage/HID1_11.pdf">
* www.usb.org/developers/hidpage/HID1_11.pdf Section 4.2</a>
* @param descriptors Descriptors of this Bluetooth HID device. See <a
* href="www.usb.org/developers/hidpage/HID1_11.pdf">
* www.usb.org/developers/hidpage/HID1_11.pdf Chapter 6</a> Maximum length is 2048 bytes.
*/
public BluetoothHidDeviceAppSdpSettings(
String name, String description, String provider, byte subclass, byte[] descriptors) {
mName = name;
mDescription = description;
mProvider = provider;
mSubclass = subclass;
if (descriptors == null || descriptors.length > MAX_DESCRIPTOR_SIZE) {
EventLog.writeEvent(0x534e4554, "119819889", -1, "");
throw new IllegalArgumentException("descriptors must be not null and shorter than "
+ MAX_DESCRIPTOR_SIZE);
}
mDescriptors = descriptors.clone();
}
private void log(final String tag, final CondomEvent event, final String... args) {
final Object[] event_args = new Object[2 + args.length];
event_args[0] = mBase.getPackageName(); event_args[1] = tag; // Package name and tag are shared parameters for all events.
System.arraycopy(args, 0, event_args, 2, args.length);
EventLog.writeEvent(EVENT_TAG + event.ordinal(), event_args);
if (DEBUG) Log.d(asLogTag(tag), event.name() + " " + Arrays.toString(args));
}
private static List<EventLog.Event> readNewEvents(final CondomCore.CondomEvent type) throws IOException {
final List<EventLog.Event> events = new ArrayList<>();
EventLog.readEvents(new int[] { EVENT_TAG_MARK, "Condom".hashCode() + type.ordinal() }, events);
if (events.isEmpty()) return Collections.emptyList();
for (int i = events.size() - 1; i >= 0; i --) {
final EventLog.Event event = events.get(i);
if (event.getTag() == EVENT_TAG_MARK) {
EventLog.writeEvent(EVENT_TAG_MARK);
return events.subList(i + 1, events.size());
}
}
EventLog.writeEvent(EVENT_TAG_MARK);
return events;
}