Java Code Examples for android.os.Binder#clearCallingIdentity()

The following examples show how to use android.os.Binder#clearCallingIdentity() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: JobServiceContext.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
    }
}
 
Example 2
Source File: NetworkStatsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 3
Source File: TvInputManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 4
Source File: UiModeManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 5
Source File: AppTaskImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 6
Source File: CameraDeviceImpl.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 7
Source File: TextServicesManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example 8
Source File: LocationManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@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);
    }
}
 
Example 9
Source File: Tethering.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 10
Source File: StatsCompanionService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 11
Source File: UiModeManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 12
Source File: MediaSessionRecord.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void setMediaButtonReceiver(PendingIntent pi) {
    mMediaButtonReceiver = pi;
    final long token = Binder.clearCallingIdentity();
    try {
        mService.onMediaButtonReceiverChanged(MediaSessionRecord.this);
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 13
Source File: DisplayManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override // Binder call
public Curve getMinimumBrightnessCurve() {
    final long token = Binder.clearCallingIdentity();
    try {
        return getMinimumBrightnessCurveInternal();
    } finally {
        Binder.restoreCallingIdentity(token);
    }
}
 
Example 14
Source File: MediaDocumentsProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 15
Source File: CallbackProxies.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void onActive(CameraCaptureSession session) {
    final long ident = Binder.clearCallingIdentity();
    try {
        mExecutor.execute(() -> mCallback.onActive(session));
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 16
Source File: FingerprintService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * @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();
}
 
Example 17
Source File: NonMediaDocumentsProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
@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);
    }
}
 
Example 18
Source File: VibratorService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@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);
    }
}
 
Example 19
Source File: ActiveServices.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
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);
    }
}
 
Example 20
Source File: SliceShellCommand.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
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;
}