下面列出了android.os.Binder#clearCallingIdentity ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
JobWorkItem doDequeueWork(JobCallback cb, int jobId) {
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
assertCallerLocked(cb);
if (mVerb == VERB_STOPPING || mVerb == VERB_FINISHED) {
// This job is either all done, or on its way out. Either way, it
// should not dispatch any more work. We will pick up any remaining
// work the next time we start the job again.
return null;
}
final JobWorkItem work = mRunningJob.dequeueWorkLocked();
if (work == null && !mRunningJob.hasExecutingWorkLocked()) {
// This will finish the job.
doCallbackLocked(false, "last work dequeued");
}
return work;
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void moveToFront() {
checkCaller();
// Will bring task to front if it already has a root activity.
final int callingPid = Binder.getCallingPid();
final int callingUid = Binder.getCallingUid();
final long origId = Binder.clearCallingIdentity();
try {
synchronized (mService) {
mService.mStackSupervisor.startActivityFromRecents(callingPid, callingUid, mTaskId,
null);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
@Override
public void clearTestProviderEnabled(String provider, String opPackageName) {
if (!canCallerAccessMockLocation(opPackageName)) {
return;
}
synchronized (mLock) {
MockProvider mockProvider = mMockProviders.get(provider);
if (mockProvider == null) {
throw new IllegalArgumentException("Provider \"" + provider + "\" unknown");
}
long identity = Binder.clearCallingIdentity();
mEnabledProviders.remove(provider);
mDisabledProviders.remove(provider);
updateProvidersLocked();
Binder.restoreCallingIdentity(identity);
}
}
public TextServicesManagerService(Context context) {
mContext = context;
mUserManager = mContext.getSystemService(UserManager.class);
mSpellCheckerOwnerUserIdMap = new LazyIntToIntMap(callingUserId -> {
if (DISABLE_PER_PROFILE_SPELL_CHECKER) {
final long token = Binder.clearCallingIdentity();
try {
final UserInfo parent = mUserManager.getProfileParent(callingUserId);
return (parent != null) ? parent.id : callingUserId;
} finally {
Binder.restoreCallingIdentity(token);
}
} else {
return callingUserId;
}
});
mMonitor = new TextServicesMonitor();
mMonitor.register(context, null, UserHandle.ALL, true);
}
/**
* Listener for binder death.
*
* <p> Handle binder death for ICameraDeviceUser. Trigger onError.</p>
*/
@Override
public void binderDied() {
Log.w(TAG, "CameraDevice " + mCameraId + " died unexpectedly");
if (mRemoteDevice == null) {
return; // Camera already closed
}
mInError = true;
Runnable r = new Runnable() {
@Override
public void run() {
if (!isClosed()) {
mDeviceCallback.onError(CameraDeviceImpl.this,
StateCallback.ERROR_CAMERA_SERVICE);
}
}
};
final long ident = Binder.clearCallingIdentity();
try {
CameraDeviceImpl.this.mDeviceExecutor.execute(r);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void disableCarMode(int flags) {
if (isUiModeLocked()) {
Slog.e(TAG, "disableCarMode while UI mode is locked");
return;
}
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
setCarModeLocked(false, 0);
if (mSystemReady) {
updateLocked(0, flags);
}
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public void relayoutOverlayView(IBinder sessionToken, Rect frame, int userId) {
final int callingUid = Binder.getCallingUid();
final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid,
userId, "relayoutOverlayView");
final long identity = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
try {
getSessionLocked(sessionToken, callingUid, resolvedUserId)
.relayoutOverlayView(frame);
} catch (RemoteException | SessionNotFoundException e) {
Slog.e(TAG, "error in relayoutOverlayView", e);
}
}
} finally {
Binder.restoreCallingIdentity(identity);
}
}
@Override
public DataUsageRequest registerUsageCallback(String callingPackage,
DataUsageRequest request, Messenger messenger, IBinder binder) {
checkNotNull(callingPackage, "calling package is null");
checkNotNull(request, "DataUsageRequest is null");
checkNotNull(request.template, "NetworkTemplate is null");
checkNotNull(messenger, "messenger is null");
checkNotNull(binder, "binder is null");
int callingUid = Binder.getCallingUid();
@NetworkStatsAccess.Level int accessLevel = checkAccessLevel(callingPackage);
DataUsageRequest normalizedRequest;
final long token = Binder.clearCallingIdentity();
try {
normalizedRequest = mStatsObservers.register(request, messenger, binder,
callingUid, accessLevel);
} finally {
Binder.restoreCallingIdentity(token);
}
// Create baseline stats
mHandler.sendMessage(mHandler.obtainMessage(MSG_PERFORM_POLL));
return normalizedRequest;
}
@Override
public void deleteDocument(String docId) throws FileNotFoundException {
final Uri target = getUriForDocumentId(docId);
// Delegate to real provider
final long token = Binder.clearCallingIdentity();
try {
getContext().getContentResolver().delete(target, null, null);
} finally {
Binder.restoreCallingIdentity(token);
}
}
/**
* @param userId
* @return true if this is a work profile
*/
private boolean isWorkProfile(int userId) {
UserInfo userInfo = null;
final long token = Binder.clearCallingIdentity();
try {
userInfo = mUserManager.getUserInfo(userId);
} finally {
Binder.restoreCallingIdentity(token);
}
return userInfo != null && userInfo.isManagedProfile();
}
@Override
public void onActive(CameraCaptureSession session) {
final long ident = Binder.clearCallingIdentity();
try {
mExecutor.execute(() -> mCallback.onActive(session));
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override
public Cursor queryRecentDocuments(String rootId, String[] projection)
throws FileNotFoundException {
final ContentResolver resolver = getContext().getContentResolver();
final MatrixCursor result = new MatrixCursor(resolveDocumentProjection(projection));
final long token = Binder.clearCallingIdentity();
Cursor cursor = null;
try {
if (TYPE_IMAGES_ROOT.equals(rootId)) {
// include all unique buckets
cursor = resolver.query(Images.Media.EXTERNAL_CONTENT_URI,
ImageQuery.PROJECTION, null, null, ImageColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, Images.Media.EXTERNAL_CONTENT_URI);
while (cursor.moveToNext() && result.getCount() < 64) {
includeImage(result, cursor);
}
} else if (TYPE_VIDEOS_ROOT.equals(rootId)) {
// include all unique buckets
cursor = resolver.query(Video.Media.EXTERNAL_CONTENT_URI,
VideoQuery.PROJECTION, null, null, VideoColumns.DATE_MODIFIED + " DESC");
copyNotificationUri(result, Video.Media.EXTERNAL_CONTENT_URI);
while (cursor.moveToNext() && result.getCount() < 64) {
includeVideo(result, cursor);
}
} else {
throw new UnsupportedOperationException("Unsupported root " + rootId);
}
} finally {
IoUtils.closeQuietly(cursor);
Binder.restoreCallingIdentity(token);
}
return result;
}
@Override // Binder call
public Curve getMinimumBrightnessCurve() {
final long token = Binder.clearCallingIdentity();
try {
return getMinimumBrightnessCurveInternal();
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public void setMediaButtonReceiver(PendingIntent pi) {
mMediaButtonReceiver = pi;
final long token = Binder.clearCallingIdentity();
try {
mService.onMediaButtonReceiverChanged(MediaSessionRecord.this);
} finally {
Binder.restoreCallingIdentity(token);
}
}
@Override
public void setNightMode(int mode) {
if (isNightModeLocked() && (getContext().checkCallingOrSelfPermission(
android.Manifest.permission.MODIFY_DAY_NIGHT_MODE)
!= PackageManager.PERMISSION_GRANTED)) {
Slog.e(TAG,
"Night mode locked, requires MODIFY_DAY_NIGHT_MODE permission");
return;
}
switch (mode) {
case UiModeManager.MODE_NIGHT_NO:
case UiModeManager.MODE_NIGHT_YES:
case UiModeManager.MODE_NIGHT_AUTO:
break;
default:
throw new IllegalArgumentException("Unknown mode: " + mode);
}
final long ident = Binder.clearCallingIdentity();
try {
synchronized (mLock) {
if (mNightMode != mode) {
Settings.Secure.putInt(getContext().getContentResolver(),
Settings.Secure.UI_NIGHT_MODE, mode);
mNightMode = mode;
updateLocked(0, 0);
}
}
} finally {
Binder.restoreCallingIdentity(ident);
}
}
@Override // Binder call
public void setAnomalyAlarm(long timestampMs) {
enforceCallingPermission();
if (DEBUG) Slog.d(TAG, "Setting anomaly alarm for " + timestampMs);
final long callingToken = Binder.clearCallingIdentity();
try {
// using ELAPSED_REALTIME, not ELAPSED_REALTIME_WAKEUP, so if device is asleep, will
// only fire when it awakens.
// This alarm is inexact, leaving its exactness completely up to the OS optimizations.
// AlarmManager will automatically cancel any previous mAnomalyAlarmIntent alarm.
mAlarmManager.setExact(AlarmManager.ELAPSED_REALTIME, timestampMs, mAnomalyAlarmIntent);
} finally {
Binder.restoreCallingIdentity(callingToken);
}
}
private void scheduleProvisioningRechecks(int type) {
Intent intent = new Intent();
intent.putExtra(EXTRA_ADD_TETHER_TYPE, type);
intent.putExtra(EXTRA_SET_ALARM, true);
intent.setComponent(TETHER_SERVICE);
final long ident = Binder.clearCallingIdentity();
try {
mContext.startServiceAsUser(intent, UserHandle.CURRENT);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
private int runGetPermissions(String authority) {
if (Binder.getCallingUid() != Process.SHELL_UID
&& Binder.getCallingUid() != Process.ROOT_UID) {
getOutPrintWriter().println("Only shell can get permissions");
return -1;
}
Context context = mService.getContext();
long ident = Binder.clearCallingIdentity();
try {
Uri uri = new Uri.Builder()
.scheme(ContentResolver.SCHEME_CONTENT)
.authority(authority)
.build();
if (!SliceProvider.SLICE_TYPE.equals(context.getContentResolver().getType(uri))) {
getOutPrintWriter().println(authority + " is not a slice provider");
return -1;
}
Bundle b = context.getContentResolver().call(uri, SliceProvider.METHOD_GET_PERMISSIONS,
null, null);
if (b == null) {
getOutPrintWriter().println("An error occurred getting permissions");
return -1;
}
String[] permissions = b.getStringArray(SliceProvider.EXTRA_RESULT);
final PrintWriter pw = getOutPrintWriter();
Set<String> listedPackages = new ArraySet<>();
if (permissions != null && permissions.length != 0) {
List<PackageInfo> apps =
context.getPackageManager().getPackagesHoldingPermissions(permissions, 0);
for (PackageInfo app : apps) {
pw.println(app.packageName);
listedPackages.add(app.packageName);
}
}
for (String pkg : mService.getAllPackagesGranted(authority)) {
if (!listedPackages.contains(pkg)) {
pw.println(pkg);
listedPackages.add(pkg);
}
}
} finally {
Binder.restoreCallingIdentity(ident);
}
return 0;
}
void unbindFinishedLocked(ServiceRecord r, Intent intent, boolean doRebind) {
final long origId = Binder.clearCallingIdentity();
try {
if (r != null) {
Intent.FilterComparison filter
= new Intent.FilterComparison(intent);
IntentBindRecord b = r.bindings.get(filter);
if (DEBUG_SERVICE) Slog.v(TAG_SERVICE, "unbindFinished in " + r
+ " at " + b + ": apps="
+ (b != null ? b.apps.size() : 0));
boolean inDestroying = mDestroyingServices.contains(r);
if (b != null) {
if (b.apps.size() > 0 && !inDestroying) {
// Applications have already bound since the last
// unbind, so just rebind right here.
boolean inFg = false;
for (int i=b.apps.size()-1; i>=0; i--) {
ProcessRecord client = b.apps.valueAt(i).client;
if (client != null && client.setSchedGroup
!= ProcessList.SCHED_GROUP_BACKGROUND) {
inFg = true;
break;
}
}
try {
requestServiceBindingLocked(r, b, inFg, true);
} catch (TransactionTooLargeException e) {
// Don't pass this back to ActivityThread, it's unrelated.
}
} else {
// Note to tell the service the next time there is
// a new client.
b.doRebind = true;
}
}
serviceDoneExecutingLocked(r, inDestroying, false);
}
} finally {
Binder.restoreCallingIdentity(origId);
}
}
@Override // Binder call
public void vibrate(int uid, String opPkg, VibrationEffect effect, int usageHint,
IBinder token) {
Trace.traceBegin(Trace.TRACE_TAG_VIBRATOR, "vibrate");
try {
if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.VIBRATE)
!= PackageManager.PERMISSION_GRANTED) {
throw new SecurityException("Requires VIBRATE permission");
}
if (token == null) {
Slog.e(TAG, "token must not be null");
return;
}
verifyIncomingUid(uid);
if (!verifyVibrationEffect(effect)) {
return;
}
// If our current vibration is longer than the new vibration and is the same amplitude,
// then just let the current one finish.
synchronized (mLock) {
if (effect instanceof VibrationEffect.OneShot
&& mCurrentVibration != null
&& mCurrentVibration.effect instanceof VibrationEffect.OneShot) {
VibrationEffect.OneShot newOneShot = (VibrationEffect.OneShot) effect;
VibrationEffect.OneShot currentOneShot =
(VibrationEffect.OneShot) mCurrentVibration.effect;
if (mCurrentVibration.hasTimeoutLongerThan(newOneShot.getDuration())
&& newOneShot.getAmplitude() == currentOneShot.getAmplitude()) {
if (DEBUG) {
Slog.d(TAG,
"Ignoring incoming vibration in favor of current vibration");
}
return;
}
}
// If the current vibration is repeating and the incoming one is non-repeating,
// then ignore the non-repeating vibration. This is so that we don't cancel
// vibrations that are meant to grab the attention of the user, like ringtones and
// alarms, in favor of one-shot vibrations that are likely quite short.
if (!isRepeatingVibration(effect)
&& mCurrentVibration != null
&& isRepeatingVibration(mCurrentVibration.effect)) {
if (DEBUG) {
Slog.d(TAG, "Ignoring incoming vibration in favor of alarm vibration");
}
return;
}
Vibration vib = new Vibration(token, effect, usageHint, uid, opPkg);
linkVibration(vib);
long ident = Binder.clearCallingIdentity();
try {
doCancelVibrateLocked();
startVibrationLocked(vib);
addToPreviousVibrationsLocked(vib);
} finally {
Binder.restoreCallingIdentity(ident);
}
}
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIBRATOR);
}
}