Java Code Examples for com.android.server.LocalServices#getService()

The following examples show how to use com.android.server.LocalServices#getService() . 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: LauncherAppsService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public ApplicationInfo getApplicationInfo(
        String callingPackage, String packageName, int flags, UserHandle user)
        throws RemoteException {
    if (!canAccessProfile(user.getIdentifier(), "Cannot check package")) {
        return null;
    }

    final int callingUid = injectBinderCallingUid();
    long ident = Binder.clearCallingIdentity();
    try {
        final PackageManagerInternal pmInt =
                LocalServices.getService(PackageManagerInternal.class);
        ApplicationInfo info = pmInt.getApplicationInfo(packageName, flags,
                callingUid, user.getIdentifier());
        return info;
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
}
 
Example 2
Source File: ContentService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@SyncExemption
private int getSyncExemptionAndCleanUpExtrasForCaller(int callingUid, Bundle extras) {
    if (extras != null) {
        final int exemption =
                extras.getInt(ContentResolver.SYNC_VIRTUAL_EXTRAS_EXEMPTION_FLAG, -1);

        // Need to remove the virtual extra.
        extras.remove(ContentResolver.SYNC_VIRTUAL_EXTRAS_EXEMPTION_FLAG);
        if (exemption != -1) {
            return exemption;
        }
    }
    final ActivityManagerInternal ami =
            LocalServices.getService(ActivityManagerInternal.class);
    final int procState = (ami != null)
            ? ami.getUidProcessState(callingUid)
            : ActivityManager.PROCESS_STATE_NONEXISTENT;

    if (procState <= ActivityManager.PROCESS_STATE_TOP) {
        return ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP;
    }
    if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND) {
        return ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET;
    }
    return ContentResolver.SYNC_EXEMPTION_NONE;
}
 
Example 3
Source File: SliceManagerService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
SliceManagerService(Context context, Looper looper) {
    mContext = context;
    mPackageManagerInternal = Preconditions.checkNotNull(
            LocalServices.getService(PackageManagerInternal.class));
    mAppOps = context.getSystemService(AppOpsManager.class);
    mAssistUtils = new AssistUtils(context);
    mHandler = new Handler(looper);

    mAppUsageStats = LocalServices.getService(UsageStatsManagerInternal.class);

    mPermissions = new SlicePermissionManager(mContext, looper);

    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
    filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
    filter.addDataScheme("package");
    mContext.registerReceiverAsUser(mReceiver, UserHandle.ALL, filter, null, mHandler);
}
 
Example 4
Source File: ShortcutPackageInfo.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
public int canRestoreTo(ShortcutService s, PackageInfo currentPackage, boolean anyVersionOkay) {
    PackageManagerInternal pmi = LocalServices.getService(PackageManagerInternal.class);
    if (!BackupUtils.signaturesMatch(mSigHashes, currentPackage, pmi)) {
        Slog.w(TAG, "Can't restore: Package signature mismatch");
        return ShortcutInfo.DISABLED_REASON_SIGNATURE_MISMATCH;
    }
    if (!ShortcutService.shouldBackupApp(currentPackage) || !mBackupSourceBackupAllowed) {
        // "allowBackup" was true when backed up, but now false.
        Slog.w(TAG, "Can't restore: package didn't or doesn't allow backup");
        return ShortcutInfo.DISABLED_REASON_BACKUP_NOT_SUPPORTED;
    }
    if (!anyVersionOkay && (currentPackage.getLongVersionCode() < mBackupSourceVersionCode)) {
        Slog.w(TAG, String.format(
                "Can't restore: package current version %d < backed up version %d",
                currentPackage.getLongVersionCode(), mBackupSourceVersionCode));
        return ShortcutInfo.DISABLED_REASON_VERSION_LOWER;
    }
    return ShortcutInfo.DISABLED_REASON_NOT_DISABLED;
}
 
Example 5
Source File: GlobalActions.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public GlobalActions(Context context, WindowManagerFuncs windowManagerFuncs) {
    mContext = context;
    mHandler = new Handler();
    mWindowManagerFuncs = windowManagerFuncs;

    mGlobalActionsProvider = LocalServices.getService(GlobalActionsProvider.class);
    if (mGlobalActionsProvider != null) {
        mGlobalActionsProvider.setGlobalActionsListener(this);
    } else {
        Slog.i(TAG, "No GlobalActionsProvider found, defaulting to LegacyGlobalActions");
    }
}
 
Example 6
Source File: JobSchedulerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
public static int standbyBucketForPackage(String packageName, int userId, long elapsedNow) {
    UsageStatsManagerInternal usageStats = LocalServices.getService(
            UsageStatsManagerInternal.class);
    int bucket = usageStats != null
            ? usageStats.getAppStandbyBucket(packageName, userId, elapsedNow)
            : 0;

    bucket = standbyBucketToBucketIndex(bucket);

    if (DEBUG_STANDBY) {
        Slog.v(TAG, packageName + "/" + userId + " standby bucket index: " + bucket);
    }
    return bucket;
}
 
Example 7
Source File: LauncherAppsService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public Bundle getSuspendedPackageLauncherExtras(String packageName,
        UserHandle user) {
    if (!canAccessProfile(user.getIdentifier(), "Cannot get launcher extras")) {
        return null;
    }
    final PackageManagerInternal pmi =
            LocalServices.getService(PackageManagerInternal.class);
    return pmi.getSuspendedPackageLauncherExtras(packageName, user.getIdentifier());
}
 
Example 8
Source File: PermissionManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Creates and returns an initialized, internal service for use by other components.
 * <p>
 * The object returned is identical to the one returned by the LocalServices class using:
 * {@code LocalServices.getService(PermissionManagerInternal.class);}
 * <p>
 * NOTE: The external lock is temporary and should be removed. This needs to be a
 * lock created by the permission manager itself.
 */
public static PermissionManagerInternal create(Context context,
        @Nullable DefaultPermissionGrantedCallback defaultGrantCallback,
        @NonNull Object externalLock) {
    final PermissionManagerInternal permMgrInt =
            LocalServices.getService(PermissionManagerInternal.class);
    if (permMgrInt != null) {
        return permMgrInt;
    }
    new PermissionManagerService(context, defaultGrantCallback, externalLock);
    return LocalServices.getService(PermissionManagerInternal.class);
}
 
Example 9
Source File: LockSettingsStorage.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Nullable
public PersistentDataBlockManagerInternal getPersistentDataBlock() {
    if (mPersistentDataBlockManagerInternal == null) {
        mPersistentDataBlockManagerInternal =
                LocalServices.getService(PersistentDataBlockManagerInternal.class);
    }
    return mPersistentDataBlockManagerInternal;
}
 
Example 10
Source File: Searchables.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private ArrayList<SearchableInfo> createFilterdSearchableInfoList(List<SearchableInfo> list) {
    if (list == null) {
        return null;
    }
    final ArrayList<SearchableInfo> resultList = new ArrayList<>(list.size());
    final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    final int callingUid = Binder.getCallingUid();
    final int callingUserId = UserHandle.getCallingUserId();
    for (SearchableInfo info : list) {
        if (pm.canAccessComponent(callingUid, info.getSearchActivity(), callingUserId)) {
            resultList.add(info);
        }
    }
    return resultList;
}
 
Example 11
Source File: Searchables.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the name of the web search activity.
 */
public synchronized ComponentName getWebSearchActivity() {
    final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    final int callingUid = Binder.getCallingUid();
    final int callingUserId = UserHandle.getCallingUserId();
    if (mWebSearchActivity != null
            && pm.canAccessComponent(callingUid, mWebSearchActivity, callingUserId)) {
        return mWebSearchActivity;
    }
    return null;
}
 
Example 12
Source File: Searchables.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Gets the name of the global search activity.
 */
public synchronized ComponentName getGlobalSearchActivity() {
    final PackageManagerInternal pm = LocalServices.getService(PackageManagerInternal.class);
    final int callingUid = Binder.getCallingUid();
    final int callingUserId = UserHandle.getCallingUserId();
    if (mCurrentGlobalSearchActivity != null
            && pm.canAccessComponent(callingUid, mCurrentGlobalSearchActivity, callingUserId)) {
        return mCurrentGlobalSearchActivity;
    }
    return null;
}
 
Example 13
Source File: DisplayManagerService.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private void setSaturationLevelInternal(float level) {
    if (level < 0 || level > 1) {
        throw new IllegalArgumentException("Saturation level must be between 0 and 1");
    }
    float[] matrix = (level == 1.0f ? null : computeSaturationMatrix(level));
    DisplayTransformManager dtm = LocalServices.getService(DisplayTransformManager.class);
    dtm.setColorMatrix(DisplayTransformManager.LEVEL_COLOR_MATRIX_SATURATION, matrix);
}
 
Example 14
Source File: BarController.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
protected StatusBarManagerInternal getStatusBarInternal() {
    synchronized (mServiceAquireLock) {
        if (mStatusBarInternal == null) {
            mStatusBarInternal = LocalServices.getService(StatusBarManagerInternal.class);
        }
        return mStatusBarInternal;
    }
}
 
Example 15
Source File: ContentService.java    From AndroidComponentPlugin with Apache License 2.0 5 votes vote down vote up
@SyncExemption
private int getSyncExemptionAndCleanUpExtrasForCaller(int callingUid, Bundle extras) {
    if (extras != null) {
        final int exemption =
                extras.getInt(ContentResolver.SYNC_VIRTUAL_EXTRAS_EXEMPTION_FLAG, -1);

        // Need to remove the virtual extra.
        extras.remove(ContentResolver.SYNC_VIRTUAL_EXTRAS_EXEMPTION_FLAG);
        if (exemption != -1) {
            return exemption;
        }
    }
    final ActivityManagerInternal ami =
            LocalServices.getService(ActivityManagerInternal.class);
    if (ami == null) {
        return ContentResolver.SYNC_EXEMPTION_NONE;
    }
    final int procState = ami.getUidProcessState(callingUid);
    final boolean isUidActive = ami.isUidActive(callingUid);

    // Providers bound by a TOP app will get PROCESS_STATE_BOUND_TOP, so include those as well
    if (procState <= ActivityManager.PROCESS_STATE_TOP
            || procState == ActivityManager.PROCESS_STATE_BOUND_TOP) {
        return ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET_WITH_TEMP;
    }
    if (procState <= ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND || isUidActive) {
        return ContentResolver.SYNC_EXEMPTION_PROMOTE_BUCKET;
    }
    return ContentResolver.SYNC_EXEMPTION_NONE;
}
 
Example 16
Source File: ColorFade.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
public ColorFade(int displayId) {
    mDisplayId = displayId;
    mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class);
}
 
Example 17
Source File: PackageInstallerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public void uninstall(VersionedPackage versionedPackage, String callerPackageName, int flags,
            IntentSender statusReceiver, int userId) throws RemoteException {
    final int callingUid = Binder.getCallingUid();
    mPermissionManager.enforceCrossUserPermission(callingUid, userId, true, true, "uninstall");
    if ((callingUid != Process.SHELL_UID) && (callingUid != Process.ROOT_UID)) {
        mAppOps.checkPackage(callingUid, callerPackageName);
    }

    // Check whether the caller is device owner or affiliated profile owner, in which case we do
    // it silently.
    final int callingUserId = UserHandle.getUserId(callingUid);
    DevicePolicyManagerInternal dpmi =
            LocalServices.getService(DevicePolicyManagerInternal.class);
    final boolean isDeviceOwnerOrAffiliatedProfileOwner =
            dpmi != null && dpmi.isActiveAdminWithPolicy(callingUid,
                    DeviceAdminInfo.USES_POLICY_PROFILE_OWNER)
                    && dpmi.isUserAffiliatedWithDevice(callingUserId);

    final PackageDeleteObserverAdapter adapter = new PackageDeleteObserverAdapter(mContext,
            statusReceiver, versionedPackage.getPackageName(),
            isDeviceOwnerOrAffiliatedProfileOwner, userId);
    if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DELETE_PACKAGES)
                == PackageManager.PERMISSION_GRANTED) {
        // Sweet, call straight through!
        mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
    } else if (isDeviceOwnerOrAffiliatedProfileOwner) {
        // Allow the device owner and affiliated profile owner to silently delete packages
        // Need to clear the calling identity to get DELETE_PACKAGES permission
        long ident = Binder.clearCallingIdentity();
        try {
            mPm.deletePackageVersioned(versionedPackage, adapter.getBinder(), userId, flags);
        } finally {
            Binder.restoreCallingIdentity(ident);
        }
    } else {
        ApplicationInfo appInfo = mPm.getApplicationInfo(callerPackageName, 0, userId);
        if (appInfo.targetSdkVersion >= Build.VERSION_CODES.P) {
            mContext.enforceCallingOrSelfPermission(Manifest.permission.REQUEST_DELETE_PACKAGES,
                    null);
        }

        // Take a short detour to confirm with user
        final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);
        intent.setData(Uri.fromParts("package", versionedPackage.getPackageName(), null));
        intent.putExtra(PackageInstaller.EXTRA_CALLBACK, adapter.getBinder().asBinder());
        adapter.onUserActionRequired(intent);
    }
}
 
Example 18
Source File: Vpn.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
/**
 * @return {@code true} if the service was started, the service was already connected, or there
 *         was no always-on VPN to start. {@code false} otherwise.
 */
public boolean startAlwaysOnVpn() {
    final String alwaysOnPackage;
    synchronized (this) {
        alwaysOnPackage = getAlwaysOnPackage();
        // Skip if there is no service to start.
        if (alwaysOnPackage == null) {
            return true;
        }
        // Remove always-on VPN if it's not supported.
        if (!isAlwaysOnPackageSupported(alwaysOnPackage)) {
            setAlwaysOnPackage(null, false);
            return false;
        }
        // Skip if the service is already established. This isn't bulletproof: it's not bound
        // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
        // which may restart the connection.
        if (getNetworkInfo().isConnected()) {
            return true;
        }
    }

    // Tell the OS that background services in this app need to be allowed for
    // a short time, so we can bootstrap the VPN service.
    final long oldId = Binder.clearCallingIdentity();
    try {
        DeviceIdleController.LocalService idleController =
                LocalServices.getService(DeviceIdleController.LocalService.class);
        idleController.addPowerSaveTempWhitelistApp(Process.myUid(), alwaysOnPackage,
                VPN_LAUNCH_IDLE_WHITELIST_DURATION_MS, mUserHandle, false, "vpn");

        // Start the VPN service declared in the app's manifest.
        Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
        serviceIntent.setPackage(alwaysOnPackage);
        try {
            return mContext.startServiceAsUser(serviceIntent, UserHandle.of(mUserHandle)) != null;
        } catch (RuntimeException e) {
            Log.e(TAG, "VpnService " + serviceIntent + " failed to start", e);
            return false;
        }
    } finally {
        Binder.restoreCallingIdentity(oldId);
    }
}
 
Example 19
Source File: JobSchedulerService.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public void onBootPhase(int phase) {
    if (PHASE_SYSTEM_SERVICES_READY == phase) {
        mConstantsObserver.start(getContext().getContentResolver());

        mAppStateTracker = Preconditions.checkNotNull(
                LocalServices.getService(AppStateTracker.class));
        setNextHeartbeatAlarm();

        // Register br for package removals and user removals.
        final IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
        filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);
        filter.addAction(Intent.ACTION_QUERY_PACKAGE_RESTART);
        filter.addDataScheme("package");
        getContext().registerReceiverAsUser(
                mBroadcastReceiver, UserHandle.ALL, filter, null, null);
        final IntentFilter userFilter = new IntentFilter(Intent.ACTION_USER_REMOVED);
        getContext().registerReceiverAsUser(
                mBroadcastReceiver, UserHandle.ALL, userFilter, null, null);
        try {
            ActivityManager.getService().registerUidObserver(mUidObserver,
                    ActivityManager.UID_OBSERVER_PROCSTATE | ActivityManager.UID_OBSERVER_GONE
                    | ActivityManager.UID_OBSERVER_IDLE | ActivityManager.UID_OBSERVER_ACTIVE,
                    ActivityManager.PROCESS_STATE_UNKNOWN, null);
        } catch (RemoteException e) {
            // ignored; both services live in system_server
        }
        // Remove any jobs that are not associated with any of the current users.
        cancelJobsForNonExistentUsers();
    } else if (phase == PHASE_THIRD_PARTY_APPS_CAN_START) {
        synchronized (mLock) {
            // Let's go!
            mReadyToRock = true;
            mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService(
                    BatteryStats.SERVICE_NAME));
            mLocalDeviceIdleController
                    = LocalServices.getService(DeviceIdleController.LocalService.class);
            // Create the "runners".
            for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) {
                mActiveServices.add(
                        new JobServiceContext(this, mBatteryStats, mJobPackageTracker,
                                getContext().getMainLooper()));
            }
            // Attach jobs to their controllers.
            mJobs.forEachJob((job) -> {
                for (int controller = 0; controller < mControllers.size(); controller++) {
                    final StateController sc = mControllers.get(controller);
                    sc.maybeStartTrackingJobLocked(job, null);
                }
            });
            // GO GO GO!
            mHandler.obtainMessage(MSG_CHECK_JOB).sendToTarget();
        }
    }
}
 
Example 20
Source File: SyncManager.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private boolean dispatchSyncOperation(SyncOperation op) {
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Slog.v(TAG, "dispatchSyncOperation: we are going to sync " + op);
        Slog.v(TAG, "num active syncs: " + mActiveSyncContexts.size());
        for (ActiveSyncContext syncContext : mActiveSyncContexts) {
            Slog.v(TAG, syncContext.toString());
        }
    }
    if (op.isAppStandbyExempted()) {
        final UsageStatsManagerInternal usmi = LocalServices.getService(
                UsageStatsManagerInternal.class);
        if (usmi != null) {
            usmi.reportExemptedSyncStart(op.owningPackage,
                    UserHandle.getUserId(op.owningUid));
        }
    }

    // Connect to the sync adapter.
    int targetUid;
    ComponentName targetComponent;
    final SyncStorageEngine.EndPoint info = op.target;
    SyncAdapterType syncAdapterType =
            SyncAdapterType.newKey(info.provider, info.account.type);
    final RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo;
    syncAdapterInfo = mSyncAdapters.getServiceInfo(syncAdapterType, info.userId);
    if (syncAdapterInfo == null) {
        mLogger.log("dispatchSyncOperation() failed: no sync adapter info for ",
                syncAdapterType);
        Log.d(TAG, "can't find a sync adapter for " + syncAdapterType
                + ", removing settings for it");
        mSyncStorageEngine.removeAuthority(info);
        return false;
    }
    targetUid = syncAdapterInfo.uid;
    targetComponent = syncAdapterInfo.componentName;
    ActiveSyncContext activeSyncContext =
            new ActiveSyncContext(op, insertStartSyncEvent(op), targetUid);
    if (Log.isLoggable(TAG, Log.VERBOSE)) {
        Slog.v(TAG, "dispatchSyncOperation: starting " + activeSyncContext);
    }

    activeSyncContext.mSyncInfo = mSyncStorageEngine.addActiveSync(activeSyncContext);
    mActiveSyncContexts.add(activeSyncContext);

    // Post message to begin monitoring this sync's progress.
    postMonitorSyncProgressMessage(activeSyncContext);

    if (!activeSyncContext.bindToSyncAdapter(targetComponent, info.userId)) {
        mLogger.log("dispatchSyncOperation() failed: bind failed. target: ",
                targetComponent);
        Slog.e(TAG, "Bind attempt failed - target: " + targetComponent);
        closeActiveSyncContext(activeSyncContext);
        return false;
    }

    return true;
}