下面列出了android.util.Slog#w ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public static Condition readConditionXml(XmlPullParser parser) {
final Uri id = safeUri(parser, CONDITION_ATT_ID);
if (id == null) return null;
final String summary = parser.getAttributeValue(null, CONDITION_ATT_SUMMARY);
final String line1 = parser.getAttributeValue(null, CONDITION_ATT_LINE1);
final String line2 = parser.getAttributeValue(null, CONDITION_ATT_LINE2);
final int icon = safeInt(parser, CONDITION_ATT_ICON, -1);
final int state = safeInt(parser, CONDITION_ATT_STATE, -1);
final int flags = safeInt(parser, CONDITION_ATT_FLAGS, -1);
try {
return new Condition(id, summary, line1, line2, icon, state, flags);
} catch (IllegalArgumentException e) {
Slog.w(TAG, "Unable to read condition xml", e);
return null;
}
}
/**
* Gets the name of the app associated with owner
*/
public static String getOwnerCaption(Context context, String owner) {
final PackageManager pm = context.getPackageManager();
try {
final ApplicationInfo info = pm.getApplicationInfo(owner, 0);
if (info != null) {
final CharSequence seq = info.loadLabel(pm);
if (seq != null) {
final String str = seq.toString().trim();
if (str.length() > 0) {
return str;
}
}
}
} catch (Throwable e) {
Slog.w(TAG, "Error loading owner caption", e);
}
return "";
}
@Override
public void handleMessage(Message msg) {
try {
switch (msg.what) {
case MSG_ON_DISPLAY_PAUSED:
mCallback.onPaused();
break;
case MSG_ON_DISPLAY_RESUMED:
mCallback.onResumed();
break;
case MSG_ON_DISPLAY_STOPPED:
mCallback.onStopped();
break;
}
} catch (RemoteException e) {
Slog.w(TAG, "Failed to notify listener of virtual display event.", e);
}
}
@Override
public void updateSystemUpdateInfo(PersistableBundle infoBundle) {
mContext.enforceCallingOrSelfPermission(Manifest.permission.RECOVERY, TAG);
int status = infoBundle.getInt(KEY_STATUS, STATUS_UNKNOWN);
if (status == STATUS_UNKNOWN) {
Slog.w(TAG, "Invalid status info. Ignored");
return;
}
// There could be multiple updater apps running on a device. But only one at most should
// be active (i.e. with a pending update), with the rest reporting idle status. We will
// only accept the reported status if any of the following conditions holds:
// a) none has been reported before;
// b) the current on-file status was last reported by the same caller;
// c) an active update is being reported.
int uid = Binder.getCallingUid();
if (mLastUid == UID_UNKNOWN || mLastUid == uid || status != STATUS_IDLE) {
synchronized (mLock) {
saveSystemUpdateInfoLocked(infoBundle, uid);
}
} else {
Slog.i(TAG, "Inactive updater reporting IDLE status. Ignored");
}
}
private void dumpOpenDescriptors() {
try {
File dumpFile = File.createTempFile("anr_fd_", "", mDumpDir);
java.lang.Process proc = new ProcessBuilder()
.command("/system/bin/lsof", "-p", String.valueOf(Process.myPid()))
.redirectErrorStream(true)
.redirectOutput(dumpFile)
.start();
int returnCode = proc.waitFor();
if (returnCode != 0) {
Slog.w(TAG, "Unable to dump open descriptors, lsof return code: "
+ returnCode);
dumpFile.delete();
}
} catch (IOException | InterruptedException ex) {
Slog.w(TAG, "Unable to dump open descriptors: " + ex);
}
}
/**
* @return if this threshold has been triggered
*/
public boolean incrementAndTest() {
final long now = SystemClock.elapsedRealtime();
final long window = now - getStart();
if (window > triggerWindow) {
setCount(1);
setStart(now);
return false;
} else {
int count = getCount() + 1;
setCount(count);
EventLogTags.writeRescueNote(uid, count, window);
Slog.w(TAG, "Noticed " + count + " events for UID " + uid + " in last "
+ (window / 1000) + " sec");
return (count >= triggerCount);
}
}
void setSleeping(boolean _sleeping, boolean force) {
if (!force && sleeping == _sleeping) {
return;
}
if (app != null && app.thread != null) {
try {
app.thread.scheduleSleeping(appToken, _sleeping);
if (_sleeping && !mStackSupervisor.mGoingToSleepActivities.contains(this)) {
mStackSupervisor.mGoingToSleepActivities.add(this);
}
sleeping = _sleeping;
} catch (RemoteException e) {
Slog.w(TAG, "Exception thrown when sleeping: " + intent.getComponent(), e);
}
}
}
public void notifyAppStopping() {
synchronized(mWindowMap) {
if (mContainer == null) {
Slog.w(TAG_WM, "Attempted to notify stopping on non-existing app token: "
+ mToken);
return;
}
mContainer.detachChildren();
}
}
private String[] getPackageNamesFromPid(int pid) {
try {
for (ActivityManager.RunningAppProcessInfo proc :
ActivityManager.getService().getRunningAppProcesses()) {
if (proc.pid == pid) {
return proc.pkgList;
}
}
} catch (RemoteException e) {
Slog.w(TAG, "ActivityManager.getRunningAppProcesses() failed");
}
return null;
}
@Override
public boolean isMuted() {
if (!mWithAudio) {
Slog.w(TAG, "Tuner did not request audio, pretending it was muted");
return true;
}
synchronized (mLock) {
checkNotClosedLocked();
return mIsMuted;
}
}
@Override
@ServiceThreadOnly
protected boolean handleGetMenuLanguage(HdmiCecMessage message) {
assertRunOnServiceThread();
if (!broadcastMenuLanguage(mService.getLanguage())) {
Slog.w(TAG, "Failed to respond to <Get Menu Language>: " + message.toString());
}
return true;
}
private void addSystemAudioModeChangeListner(IHdmiSystemAudioModeChangeListener listener) {
SystemAudioModeChangeListenerRecord record = new SystemAudioModeChangeListenerRecord(
listener);
try {
listener.asBinder().linkToDeath(record, 0);
} catch (RemoteException e) {
Slog.w(TAG, "Listener already died");
return;
}
synchronized (mLock) {
mSystemAudioModeChangeListenerRecords.add(record);
}
}
@Override
public boolean onEnrollResult(int fingerId, int groupId, int remaining) {
if (groupId != getGroupId()) {
Slog.w(TAG, "groupId != getGroupId(), groupId: " + groupId +
" getGroupId():" + getGroupId());
}
if (remaining == 0) {
FingerprintUtils.getInstance().addFingerprintForUser(getContext(), fingerId,
getTargetUserId());
}
return sendEnrollResult(fingerId, groupId, remaining);
}
@ServiceThreadOnly
int startOneTouchRecord(int recorderAddress, byte[] recordSource) {
assertRunOnServiceThread();
if (!mService.isControlEnabled()) {
Slog.w(TAG, "Can not start one touch record. CEC control is disabled.");
announceOneTouchRecordResult(recorderAddress, ONE_TOUCH_RECORD_CEC_DISABLED);
return Constants.ABORT_NOT_IN_CORRECT_MODE;
}
if (!checkRecorder(recorderAddress)) {
Slog.w(TAG, "Invalid recorder address:" + recorderAddress);
announceOneTouchRecordResult(recorderAddress,
ONE_TOUCH_RECORD_CHECK_RECORDER_CONNECTION);
return Constants.ABORT_NOT_IN_CORRECT_MODE;
}
if (!checkRecordSource(recordSource)) {
Slog.w(TAG, "Invalid record source." + Arrays.toString(recordSource));
announceOneTouchRecordResult(recorderAddress,
ONE_TOUCH_RECORD_FAIL_TO_RECORD_DISPLAYED_SCREEN);
return Constants.ABORT_CANNOT_PROVIDE_SOURCE;
}
addAndStartAction(new OneTouchRecordAction(this, recorderAddress, recordSource));
Slog.i(TAG, "Start new [One Touch Record]-Target:" + recorderAddress + ", recordSource:"
+ Arrays.toString(recordSource));
return Constants.ABORT_NO_ERROR;
}
@Override
public int requestInstall(ParcelFileDescriptor distroParcelFileDescriptor,
byte[] checkTokenBytes, ICallback callback) {
boolean closeParcelFileDescriptorOnExit = true;
try {
mPermissionHelper.enforceCallerHasPermission(REQUIRED_UPDATER_PERMISSION);
CheckToken checkToken = null;
if (checkTokenBytes != null) {
checkToken = createCheckTokenOrThrow(checkTokenBytes);
}
EventLogTags.writeTimezoneRequestInstall(toStringOrNull(checkToken));
synchronized (this) {
if (distroParcelFileDescriptor == null) {
throw new NullPointerException("distroParcelFileDescriptor == null");
}
if (callback == null) {
throw new NullPointerException("observer == null");
}
if (mOperationInProgress.get()) {
return RulesManager.ERROR_OPERATION_IN_PROGRESS;
}
mOperationInProgress.set(true);
// Execute the install asynchronously.
mExecutor.execute(
new InstallRunnable(distroParcelFileDescriptor, checkToken, callback));
// The InstallRunnable now owns the ParcelFileDescriptor, so it will close it after
// it executes (and we do not have to).
closeParcelFileDescriptorOnExit = false;
return RulesManager.SUCCESS;
}
} finally {
// We should close() the local ParcelFileDescriptor we were passed if it hasn't been
// passed to another thread to handle.
if (distroParcelFileDescriptor != null && closeParcelFileDescriptorOnExit) {
try {
distroParcelFileDescriptor.close();
} catch (IOException e) {
Slog.w(TAG, "Failed to close distroParcelFileDescriptor", e);
}
}
}
}
static void warnForInvalidTag(int depth, String tag) throws IOException {
Slog.w(TAG, String.format("Invalid tag '%s' found at depth %d", tag, depth));
}
public int scheduleAsPackage(JobInfo job, JobWorkItem work, int uId, String packageName,
int userId, String tag) {
try {
if (ActivityManager.getService().isAppStartModeDisabled(uId,
job.getService().getPackageName())) {
Slog.w(TAG, "Not scheduling job " + uId + ":" + job.toString()
+ " -- package not allowed to start");
return JobScheduler.RESULT_FAILURE;
}
} catch (RemoteException e) {
}
synchronized (mLock) {
final JobStatus toCancel = mJobs.getJobByUidAndJobId(uId, job.getId());
if (work != null && toCancel != null) {
// Fast path: we are adding work to an existing job, and the JobInfo is not
// changing. We can just directly enqueue this work in to the job.
if (toCancel.getJob().equals(job)) {
toCancel.enqueueWorkLocked(ActivityManager.getService(), work);
// If any of work item is enqueued when the source is in the foreground,
// exempt the entire job.
toCancel.maybeAddForegroundExemption(mIsUidActivePredicate);
return JobScheduler.RESULT_SUCCESS;
}
}
JobStatus jobStatus = JobStatus.createFromJobInfo(job, uId, packageName, userId, tag);
// Give exemption if the source is in the foreground just now.
// Note if it's a sync job, this method is called on the handler so it's not exactly
// the state when requestSync() was called, but that should be fine because of the
// 1 minute foreground grace period.
jobStatus.maybeAddForegroundExemption(mIsUidActivePredicate);
if (DEBUG) Slog.d(TAG, "SCHEDULE: " + jobStatus.toShortString());
// Jobs on behalf of others don't apply to the per-app job cap
if (ENFORCE_MAX_JOBS && packageName == null) {
if (mJobs.countJobsForUid(uId) > MAX_JOBS_PER_APP) {
Slog.w(TAG, "Too many jobs for uid " + uId);
throw new IllegalStateException("Apps may not schedule more than "
+ MAX_JOBS_PER_APP + " distinct jobs");
}
}
// This may throw a SecurityException.
jobStatus.prepareLocked(ActivityManager.getService());
if (work != null) {
// If work has been supplied, enqueue it into the new job.
jobStatus.enqueueWorkLocked(ActivityManager.getService(), work);
}
if (toCancel != null) {
// Implicitly replaces the existing job record with the new instance
cancelJobImplLocked(toCancel, jobStatus, "job rescheduled by app");
} else {
startTrackingJobLocked(jobStatus, null);
}
StatsLog.write_non_chained(StatsLog.SCHEDULED_JOB_STATE_CHANGED,
uId, null, jobStatus.getBatteryName(),
StatsLog.SCHEDULED_JOB_STATE_CHANGED__STATE__SCHEDULED,
JobProtoEnums.STOP_REASON_CANCELLED);
// If the job is immediately ready to run, then we can just immediately
// put it in the pending list and try to schedule it. This is especially
// important for jobs with a 0 deadline constraint, since they will happen a fair
// amount, we want to handle them as quickly as possible, and semantically we want to
// make sure we have started holding the wake lock for the job before returning to
// the caller.
// If the job is not yet ready to run, there is nothing more to do -- we are
// now just waiting for one of its controllers to change state and schedule
// the job appropriately.
if (isReadyToBeExecutedLocked(jobStatus)) {
// This is a new job, we can just immediately put it on the pending
// list and try to run it.
mJobPackageTracker.notePending(jobStatus);
addOrderedItem(mPendingJobs, jobStatus, mEnqueueTimeComparator);
maybeRunPendingJobsLocked();
}
}
return JobScheduler.RESULT_SUCCESS;
}
@Override
public byte[] getBackupPayload(@UserIdInt int userId) {
enforceSystem();
if (DEBUG) {
Slog.d(TAG, "Backing up user " + userId);
}
synchronized (mLock) {
if (!isUserUnlockedL(userId)) {
wtf("Can't backup: user " + userId + " is locked or not running");
return null;
}
final ShortcutUser user = getUserShortcutsLocked(userId);
if (user == null) {
wtf("Can't backup: user not found: id=" + userId);
return null;
}
// Update the signatures for all packages.
user.forAllPackageItems(spi -> spi.refreshPackageSignatureAndSave());
// Rescan all apps; this will also update the version codes and "allow-backup".
user.forAllPackages(pkg -> pkg.rescanPackageIfNeeded(
/*isNewApp=*/ false, /*forceRescan=*/ true));
// Set the version code for the launchers.
user.forAllLaunchers(launcher -> launcher.ensurePackageInfo());
// Save to the filesystem.
scheduleSaveUser(userId);
saveDirtyInfo();
// Note, in case of backup, we don't have to wait on bitmap saving, because we don't
// back up bitmaps anyway.
// Then create the backup payload.
final ByteArrayOutputStream os = new ByteArrayOutputStream(32 * 1024);
try {
saveUserInternalLocked(userId, os, /* forBackup */ true);
} catch (XmlPullParserException | IOException e) {
// Shouldn't happen.
Slog.w(TAG, "Backup failed.", e);
return null;
}
byte[] payload = os.toByteArray();
mShortcutDumpFiles.save("backup-1-payload.txt", payload);
return payload;
}
}
/**
* Start lock task mode on the given task.
* @param lockTaskModeState whether fully locked or pinned mode.
* @param andResume whether the task should be brought to foreground as part of the operation.
*/
private void setLockTaskMode(@NonNull TaskRecord task, int lockTaskModeState,
String reason, boolean andResume) {
// Should have already been checked, but do it again.
if (task.mLockTaskAuth == LOCK_TASK_AUTH_DONT_LOCK) {
if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK,
"setLockTaskMode: Can't lock due to auth");
return;
}
if (isLockTaskModeViolation(task)) {
Slog.e(TAG_LOCKTASK, "setLockTaskMode: Attempt to start an unauthorized lock task.");
return;
}
final Intent taskIntent = task.intent;
if (mLockTaskModeTasks.isEmpty() && taskIntent != null) {
mSupervisor.mRecentTasks.onLockTaskModeStateChanged(lockTaskModeState, task.userId);
// Start lock task on the handler thread
mHandler.post(() -> performStartLockTask(
taskIntent.getComponent().getPackageName(),
task.userId,
lockTaskModeState));
}
if (DEBUG_LOCKTASK) Slog.w(TAG_LOCKTASK, "setLockTaskMode: Locking to " + task +
" Callers=" + Debug.getCallers(4));
if (!mLockTaskModeTasks.contains(task)) {
mLockTaskModeTasks.add(task);
}
if (task.mLockTaskUid == -1) {
task.mLockTaskUid = task.effectiveUid;
}
if (andResume) {
mSupervisor.findTaskToMoveToFront(task, 0, null, reason,
lockTaskModeState != LOCK_TASK_MODE_NONE);
mSupervisor.resumeFocusedStackTopActivityLocked();
mWindowManager.executeAppTransition();
} else if (lockTaskModeState != LOCK_TASK_MODE_NONE) {
mSupervisor.handleNonResizableTaskIfNeeded(task, WINDOWING_MODE_UNDEFINED,
DEFAULT_DISPLAY, task.getStack(), true /* forceNonResizable */);
}
}
private boolean checkConfiguredLocked() {
if (mTunerCallback.isInitialConfigurationDone()) return true;
Slog.w(TAG, "Initial configuration is still pending, skipping the operation");
return false;
}