下面列出了android.os.TransactionTooLargeException#android.app.AppGlobals 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Return true if all given permissions are signature-only perms.
*/
final boolean isSignaturePerm(String[] perms) {
if (perms == null) {
return false;
}
IPackageManager pm = AppGlobals.getPackageManager();
for (int i = perms.length-1; i >= 0; i--) {
try {
PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
| PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
!= PermissionInfo.PROTECTION_SIGNATURE) {
// If this a signature permission and NOT allowed for privileged apps, it
// is okay... otherwise, nope!
return false;
}
} catch (RemoteException e) {
return false;
}
}
return true;
}
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 enforceValidJobRequest(int uid, JobInfo job) {
final IPackageManager pm = AppGlobals.getPackageManager();
final ComponentName service = job.getService();
try {
ServiceInfo si = pm.getServiceInfo(service,
PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE,
UserHandle.getUserId(uid));
if (si == null) {
throw new IllegalArgumentException("No such service " + service);
}
if (si.applicationInfo.uid != uid) {
throw new IllegalArgumentException("uid " + uid +
" cannot schedule job in " + service.getPackageName());
}
if (!JobService.PERMISSION_BIND.equals(si.permission)) {
throw new IllegalArgumentException("Scheduled service " + service
+ " does not require android.permission.BIND_JOB_SERVICE permission");
}
} catch (RemoteException e) {
// Can't happen; the Package Manager is in this same process
}
}
@VisibleForTesting // We override it in unit tests
void verifyCallingPackage(String callingPackage) {
int packageUid = -1;
try {
packageUid = AppGlobals.getPackageManager().getPackageUid(callingPackage,
PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE
| PackageManager.MATCH_UNINSTALLED_PACKAGES,
UserHandle.getUserId(getCallingUid()));
} catch (RemoteException ignore) {
}
if (packageUid < 0) {
Log.e(TAG, "Package not found: " + callingPackage);
}
if (packageUid != injectBinderCallingUid()) {
throw new SecurityException("Calling package name mismatch");
}
}
@Override
public boolean matches(IntentFirewall ifw, ComponentName resolvedComponent, Intent intent,
int callerUid, int callerPid, String resolvedType, int receivingUid) {
IPackageManager pm = AppGlobals.getPackageManager();
int packageUid = -1;
try {
// USER_SYSTEM here is not important. Only app id is used and getPackageUid() will
// return a uid whether the app is installed for a user or not.
packageUid = pm.getPackageUid(mPackageName, PackageManager.MATCH_ANY_USER,
UserHandle.USER_SYSTEM);
} catch (RemoteException ex) {
// handled below
}
if (packageUid == -1) {
return false;
}
return UserHandle.isSameApp(packageUid, callerUid);
}
static boolean isPrivilegedApp(int callerUid, int callerPid) {
if (callerUid == Process.SYSTEM_UID || callerUid == 0 ||
callerPid == Process.myPid() || callerPid == 0) {
return true;
}
IPackageManager pm = AppGlobals.getPackageManager();
try {
return (pm.getPrivateFlagsForUid(callerUid) & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED)
!= 0;
} catch (RemoteException ex) {
Slog.e(IntentFirewall.TAG, "Remote exception while retrieving uid flags",
ex);
}
return false;
}
private boolean clipboardAccessAllowed(int op, String callingPackage, int callingUid) {
// Check the AppOp.
if (mAppOps.noteOp(op, callingUid, callingPackage) != AppOpsManager.MODE_ALLOWED) {
return false;
}
try {
// Installed apps can access the clipboard at any time.
if (!AppGlobals.getPackageManager().isInstantApp(callingPackage,
UserHandle.getUserId(callingUid))) {
return true;
}
// Instant apps can only access the clipboard if they are in the foreground.
return mAm.isAppForeground(callingUid);
} catch (RemoteException e) {
Slog.e("clipboard", "Failed to get Instant App status for package " + callingPackage,
e);
return false;
}
}
/**
* Return true if all given permissions are signature-only perms.
*/
final boolean isSignaturePerm(String[] perms) {
if (perms == null) {
return false;
}
IPackageManager pm = AppGlobals.getPackageManager();
for (int i = perms.length-1; i >= 0; i--) {
try {
PermissionInfo pi = pm.getPermissionInfo(perms[i], "android", 0);
if ((pi.protectionLevel & (PermissionInfo.PROTECTION_MASK_BASE
| PermissionInfo.PROTECTION_FLAG_PRIVILEGED))
!= PermissionInfo.PROTECTION_SIGNATURE) {
// If this a signature permission and NOT allowed for privileged apps, it
// is okay... otherwise, nope!
return false;
}
} catch (RemoteException e) {
return false;
}
}
return true;
}
public void handlePackageAddedLocked(String packageName, boolean updated) {
ApplicationInfo ai = null;
try {
ai = AppGlobals.getPackageManager().getApplicationInfo(packageName, 0, 0);
} catch (RemoteException e) {
}
if (ai == null) {
return;
}
CompatibilityInfo ci = compatibilityInfoForPackageLocked(ai);
final boolean mayCompat = !ci.alwaysSupportsScreen()
&& !ci.neverSupportsScreen();
if (updated) {
// Update -- if the app no longer can run in compat mode, clear
// any current settings for it.
if (!mayCompat && mPackages.containsKey(packageName)) {
mPackages.remove(packageName);
scheduleWrite();
}
}
}
/**
* Loads the static recents component. This is called after the system is ready, but before
* any dependent services (like SystemUI) is started.
*/
void loadRecentsComponent(Resources res) {
final String rawRecentsComponent = res.getString(
com.android.internal.R.string.config_recentsComponentName);
if (TextUtils.isEmpty(rawRecentsComponent)) {
return;
}
final ComponentName cn = ComponentName.unflattenFromString(rawRecentsComponent);
if (cn != null) {
try {
final ApplicationInfo appInfo = AppGlobals.getPackageManager()
.getApplicationInfo(cn.getPackageName(), 0, mService.mContext.getUserId());
if (appInfo != null) {
mRecentsUid = appInfo.uid;
mRecentsComponent = cn;
}
} catch (RemoteException e) {
Slog.w(TAG, "Could not load application info for recents component: " + cn);
}
}
}
/**
* @hide
*/
public static int onWebViewProviderChanged(PackageInfo packageInfo) {
int startedRelroProcesses = 0;
ApplicationInfo originalAppInfo = new ApplicationInfo(packageInfo.applicationInfo);
try {
fixupStubApplicationInfo(packageInfo.applicationInfo,
AppGlobals.getInitialApplication().getPackageManager());
startedRelroProcesses = WebViewLibraryLoader.prepareNativeLibraries(packageInfo);
} catch (Throwable t) {
// Log and discard errors at this stage as we must not crash the system server.
Log.e(LOGTAG, "error preparing webview native library", t);
}
WebViewZygote.onWebViewProviderChanged(packageInfo, originalAppInfo);
return startedRelroProcesses;
}
/**
* Formats name of trace log file for method tracing.
*/
private static String fixTracePath(String tracePath) {
if (tracePath == null || tracePath.charAt(0) != '/') {
final Context context = AppGlobals.getInitialApplication();
final File dir;
if (context != null) {
dir = context.getExternalFilesDir(null);
} else {
dir = Environment.getExternalStorageDirectory();
}
if (tracePath == null) {
tracePath = new File(dir, DEFAULT_TRACE_BODY).getAbsolutePath();
} else {
tracePath = new File(dir, tracePath).getAbsolutePath();
}
}
if (!tracePath.endsWith(DEFAULT_TRACE_EXTENSION)) {
tracePath += DEFAULT_TRACE_EXTENSION;
}
return tracePath;
}
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);
}
static ServiceInfo getServiceInfoOrThrow(ComponentName comp, int userHandle)
throws PackageManager.NameNotFoundException {
try {
ServiceInfo si = AppGlobals.getPackageManager().getServiceInfo(comp,
PackageManager.GET_META_DATA
| PackageManager.MATCH_DIRECT_BOOT_AWARE
| PackageManager.MATCH_DIRECT_BOOT_UNAWARE
| PackageManager.MATCH_DEBUG_TRIAGED_MISSING,
userHandle);
if (si != null) {
return si;
}
} catch (RemoteException e) {
}
throw new PackageManager.NameNotFoundException(comp.toString());
}
@Override
public boolean onCreate() {
Settings.setInSystemServer();
synchronized (mLock) {
mUserManager = UserManager.get(getContext());
mPackageManager = AppGlobals.getPackageManager();
mHandlerThread = new HandlerThread(LOG_TAG,
Process.THREAD_PRIORITY_BACKGROUND);
mHandlerThread.start();
mHandler = new Handler(mHandlerThread.getLooper());
mSettingsRegistry = new SettingsRegistry();
}
mHandler.post(() -> {
registerBroadcastReceivers();
startWatchingUserRestrictionChanges();
});
ServiceManager.addService("settings", new SettingsService(this));
return true;
}
public ObserverEntry(IContentObserver o, boolean n, Object observersLock,
int _uid, int _pid, int _userHandle, Uri uri) {
this.observersLock = observersLock;
observer = o;
uid = _uid;
pid = _pid;
userHandle = _userHandle;
notifyForDescendants = n;
final int entries = sObserverDeathDispatcher.linkToDeath(observer, this);
if (entries == -1) {
binderDied();
} else if (entries == TOO_MANY_OBSERVERS_THRESHOLD) {
boolean alreadyDetected;
synchronized (sObserverLeakDetectedUid) {
alreadyDetected = sObserverLeakDetectedUid.contains(uid);
if (!alreadyDetected) {
sObserverLeakDetectedUid.add(uid);
}
}
if (!alreadyDetected) {
String caller = null;
try {
caller = ArrayUtils.firstOrNull(AppGlobals.getPackageManager()
.getPackagesForUid(uid));
} catch (RemoteException ignore) {
}
Slog.wtf(TAG, "Observer registered too many times. Leak? cpid=" + pid
+ " cuid=" + uid
+ " cpkg=" + caller
+ " url=" + uri);
}
}
}
@Override
public void enablePackageForUser(String packageName, boolean enable, int userId) {
try {
AppGlobals.getPackageManager().setApplicationEnabledSetting(
packageName,
enable ? PackageManager.COMPONENT_ENABLED_STATE_DEFAULT :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER, 0,
userId, null);
} catch (RemoteException | IllegalArgumentException e) {
Log.w(TAG, "Tried to " + (enable ? "enable " : "disable ") + packageName
+ " for user " + userId + ": " + e);
}
}
/**
* Disables BluetoothOppLauncherActivity component, so the Bluetooth sharing option is not
* offered to the user if Bluetooth or sharing is disallowed. Puts the component to its default
* state if Bluetooth is not disallowed.
*
* @param userId user to disable bluetooth sharing for.
* @param bluetoothSharingDisallowed whether bluetooth sharing is disallowed.
*/
private void updateOppLauncherComponentState(int userId, boolean bluetoothSharingDisallowed) {
final ComponentName oppLauncherComponent = new ComponentName("com.android.bluetooth",
"com.android.bluetooth.opp.BluetoothOppLauncherActivity");
final int newState =
bluetoothSharingDisallowed ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED
: PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
try {
final IPackageManager imp = AppGlobals.getPackageManager();
imp.setComponentEnabledSetting(oppLauncherComponent, newState,
PackageManager.DONT_KILL_APP, userId);
} catch (Exception e) {
// The component was not found, do nothing.
}
}
int executeRunCommand(String pkgName, int userId, int jobId, boolean force) {
if (DEBUG) {
Slog.v(TAG, "executeRunCommand(): " + pkgName + "/" + userId
+ " " + jobId + " f=" + force);
}
try {
final int uid = AppGlobals.getPackageManager().getPackageUid(pkgName, 0,
userId != UserHandle.USER_ALL ? userId : UserHandle.USER_SYSTEM);
if (uid < 0) {
return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
}
synchronized (mLock) {
final JobStatus js = mJobs.getJobByUidAndJobId(uid, jobId);
if (js == null) {
return JobSchedulerShellCommand.CMD_ERR_NO_JOB;
}
js.overrideState = (force) ? JobStatus.OVERRIDE_FULL : JobStatus.OVERRIDE_SOFT;
if (!js.isConstraintsSatisfied()) {
js.overrideState = 0;
return JobSchedulerShellCommand.CMD_ERR_CONSTRAINTS;
}
queueReadyJobsForExecutionLocked();
maybeRunPendingJobsLocked();
}
} catch (RemoteException e) {
// can't happen
}
return 0;
}
int executeCancelCommand(PrintWriter pw, String pkgName, int userId,
boolean hasJobId, int jobId) {
if (DEBUG) {
Slog.v(TAG, "executeCancelCommand(): " + pkgName + "/" + userId + " " + jobId);
}
int pkgUid = -1;
try {
IPackageManager pm = AppGlobals.getPackageManager();
pkgUid = pm.getPackageUid(pkgName, 0, userId);
} catch (RemoteException e) { /* can't happen */ }
if (pkgUid < 0) {
pw.println("Package " + pkgName + " not found.");
return JobSchedulerShellCommand.CMD_ERR_NO_PACKAGE;
}
if (!hasJobId) {
pw.println("Canceling all jobs for " + pkgName + " in user " + userId);
if (!cancelJobsForUid(pkgUid, "cancel shell command for package")) {
pw.println("No matching jobs found.");
}
} else {
pw.println("Canceling job " + pkgName + "/#" + jobId + " in user " + userId);
if (!cancelJob(pkgUid, jobId, Process.SHELL_UID)) {
pw.println("No matching job found.");
}
}
return 0;
}
public WallpaperManagerService(Context context) {
if (DEBUG) Slog.v(TAG, "WallpaperService startup");
mContext = context;
mShuttingDown = false;
mImageWallpaper = ComponentName.unflattenFromString(
context.getResources().getString(R.string.image_wallpaper_component));
mDefaultWallpaperComponent = WallpaperManager.getDefaultWallpaperComponent(context);
mIWindowManager = IWindowManager.Stub.asInterface(
ServiceManager.getService(Context.WINDOW_SERVICE));
mIPackageManager = AppGlobals.getPackageManager();
mAppOpsManager = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE);
mMonitor = new MyPackageMonitor();
mColorsChangedListeners = new SparseArray<>();
}
private int getIsSyncable(Account account, int userId, String providerName) {
int isSyncable = mSyncStorageEngine.getIsSyncable(account, userId, providerName);
UserInfo userInfo = UserManager.get(mContext).getUserInfo(userId);
// If it's not a restricted user, return isSyncable.
if (userInfo == null || !userInfo.isRestricted()) return isSyncable;
// Else check if the sync adapter has opted-in or not.
RegisteredServicesCache.ServiceInfo<SyncAdapterType> syncAdapterInfo =
mSyncAdapters.getServiceInfo(
SyncAdapterType.newKey(providerName, account.type), userId);
if (syncAdapterInfo == null) return AuthorityInfo.NOT_SYNCABLE;
PackageInfo pInfo = null;
try {
pInfo = AppGlobals.getPackageManager().getPackageInfo(
syncAdapterInfo.componentName.getPackageName(), 0, userId);
if (pInfo == null) return AuthorityInfo.NOT_SYNCABLE;
} catch (RemoteException re) {
// Shouldn't happen.
return AuthorityInfo.NOT_SYNCABLE;
}
if (pInfo.restrictedAccountType != null
&& pInfo.restrictedAccountType.equals(account.type)) {
return isSyncable;
} else {
return AuthorityInfo.NOT_SYNCABLE;
}
}
/**
* Build a notification for package installation / deletion by device owners that is shown if
* the operation succeeds.
*/
private static Notification buildSuccessNotification(Context context, String contentText,
String basePackageName, int userId) {
PackageInfo packageInfo = null;
try {
packageInfo = AppGlobals.getPackageManager().getPackageInfo(
basePackageName, PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId);
} catch (RemoteException ignored) {
}
if (packageInfo == null || packageInfo.applicationInfo == null) {
Slog.w(TAG, "Notification not built for package: " + basePackageName);
return null;
}
PackageManager pm = context.getPackageManager();
Bitmap packageIcon = ImageUtils.buildScaledBitmap(
packageInfo.applicationInfo.loadIcon(pm),
context.getResources().getDimensionPixelSize(
android.R.dimen.notification_large_icon_width),
context.getResources().getDimensionPixelSize(
android.R.dimen.notification_large_icon_height));
CharSequence packageLabel = packageInfo.applicationInfo.loadLabel(pm);
return new Notification.Builder(context, SystemNotificationChannels.DEVICE_ADMIN)
.setSmallIcon(R.drawable.ic_check_circle_24px)
.setColor(context.getResources().getColor(
R.color.system_notification_accent_color))
.setContentTitle(packageLabel)
.setContentText(contentText)
.setStyle(new Notification.BigTextStyle().bigText(contentText))
.setLargeIcon(packageIcon)
.build();
}
private static ArraySet<String> getPackageNamesForIntent(Intent intent, int userId) {
List<ResolveInfo> ris = null;
try {
ris = AppGlobals.getPackageManager().queryIntentReceivers(intent, null, 0, userId)
.getList();
} catch (RemoteException e) {
}
ArraySet<String> pkgNames = new ArraySet<String>();
if (ris != null) {
for (ResolveInfo ri : ris) {
pkgNames.add(ri.activityInfo.packageName);
}
}
return pkgNames;
}
public MediaSessionService(Context context) {
super(context);
mSessionManagerImpl = new SessionManagerImpl();
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mMediaEventWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "handleMediaEvent");
mLongPressTimeout = ViewConfiguration.getLongPressTimeout();
mNotificationManager = INotificationManager.Stub.asInterface(
ServiceManager.getService(Context.NOTIFICATION_SERVICE));
mPackageManager = AppGlobals.getPackageManager();
}
private static void logIntent(int intentType, Intent intent, int callerUid,
String resolvedType) {
// The component shouldn't be null, but let's double check just to be safe
ComponentName cn = intent.getComponent();
String shortComponent = null;
if (cn != null) {
shortComponent = cn.flattenToShortString();
}
String callerPackages = null;
int callerPackageCount = 0;
IPackageManager pm = AppGlobals.getPackageManager();
if (pm != null) {
try {
String[] callerPackagesArray = pm.getPackagesForUid(callerUid);
if (callerPackagesArray != null) {
callerPackageCount = callerPackagesArray.length;
callerPackages = joinPackages(callerPackagesArray);
}
} catch (RemoteException ex) {
Slog.e(TAG, "Remote exception while retrieving packages", ex);
}
}
EventLogTags.writeIfwIntentMatched(intentType, shortComponent, callerUid,
callerPackageCount, callerPackages, intent.getAction(), resolvedType,
intent.getDataString(), intent.getFlags());
}
boolean signaturesMatch(int uid1, int uid2) {
try {
IPackageManager pm = AppGlobals.getPackageManager();
return pm.checkUidSignatures(uid1, uid2) == PackageManager.SIGNATURE_MATCH;
} catch (RemoteException ex) {
Slog.e(TAG, "Remote exception while checking signatures", ex);
return false;
}
}
private boolean isPackageSuspendedForUser(String pkg, int uid) {
try {
return AppGlobals.getPackageManager().isPackageSuspendedForUser(
pkg, UserHandle.getUserId(uid));
} catch (RemoteException re) {
throw new SecurityException("Could not talk to package manager service");
}
}
private static String[] getPackagesForUid(int uid) {
String[] packageNames = null;
try {
packageNames = AppGlobals.getPackageManager().getPackagesForUid(uid);
} catch (RemoteException e) {
/* ignore - local call */
}
if (packageNames == null) {
return EmptyArray.STRING;
}
return packageNames;
}