diff options
171 files changed, 4556 insertions, 1739 deletions
diff --git a/Android.bp b/Android.bp index 753cefc38ed6..edaa11e3dc73 100644 --- a/Android.bp +++ b/Android.bp @@ -97,6 +97,7 @@ filegroup { ":platform-compat-native-aidl", // AIDL sources from external directories + ":android.hardware.gnss-V2-java-source", ":android.hardware.graphics.common-V3-java-source", ":android.hardware.security.keymint-V2-java-source", ":android.hardware.security.secureclock-V1-java-source", diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java index 18f63b7ad902..23056b5670b9 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobConcurrencyManager.java @@ -17,6 +17,7 @@ package com.android.server.job; import static com.android.server.job.JobSchedulerService.MAX_JOB_CONTEXTS_COUNT; +import static com.android.server.job.JobSchedulerService.RESTRICTED_INDEX; import static com.android.server.job.JobSchedulerService.sElapsedRealtimeClock; import android.annotation.IntDef; @@ -32,9 +33,11 @@ import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.pm.UserInfo; +import android.os.BatteryStats; import android.os.Handler; import android.os.PowerManager; import android.os.RemoteException; +import android.os.ServiceManager; import android.os.UserHandle; import android.provider.DeviceConfig; import android.util.ArraySet; @@ -51,19 +54,24 @@ import android.util.proto.ProtoOutputStream; import com.android.internal.R; import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; +import com.android.internal.app.IBatteryStats; import com.android.internal.app.procstats.ProcessStats; import com.android.internal.util.StatLogger; import com.android.server.JobSchedulerBackgroundThread; import com.android.server.LocalServices; import com.android.server.job.controllers.JobStatus; import com.android.server.job.controllers.StateController; +import com.android.server.job.restrictions.JobRestriction; import com.android.server.pm.UserManagerInternal; +import java.io.PrintWriter; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; +import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; +import java.util.function.Predicate; /** * This class decides, given the various configuration and the system status, which jobs can start @@ -278,6 +286,11 @@ class JobConcurrencyManager { String[] mRecycledShouldStopJobReason = new String[MAX_JOB_CONTEXTS_COUNT]; + /** + * Set of JobServiceContexts that we use to run jobs. + */ + final List<JobServiceContext> mActiveServices = new ArrayList<>(); + private final ArraySet<JobStatus> mRunningJobs = new ArraySet<>(); private final WorkCountTracker mWorkCountTracker = new WorkCountTracker(); @@ -358,6 +371,20 @@ class JobConcurrencyManager { onInteractiveStateChanged(mPowerManager.isInteractive()); } + /** + * Called when the boot phase reaches + * {@link com.android.server.SystemService#PHASE_THIRD_PARTY_APPS_CAN_START}. + */ + void onThirdPartyAppsCanStart() { + final IBatteryStats batteryStats = IBatteryStats.Stub.asInterface( + ServiceManager.getService(BatteryStats.SERVICE_NAME)); + for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) { + mActiveServices.add( + new JobServiceContext(mService, this, batteryStats, + mService.mJobPackageTracker, mContext.getMainLooper())); + } + } + @GuardedBy("mLock") void onAppRemovedLocked(String pkgName, int uid) { final PackageStats packageStats = mActivePkgStats.get(UserHandle.getUserId(uid), pkgName); @@ -390,6 +417,7 @@ class JobConcurrencyManager { case PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED: if (mPowerManager != null && mPowerManager.isDeviceIdleMode()) { synchronized (mLock) { + stopUnexemptedJobsForDoze(); stopLongRunningJobsLocked("deep doze"); } } @@ -471,6 +499,11 @@ class JobConcurrencyManager { } @GuardedBy("mLock") + ArraySet<JobStatus> getRunningJobsLocked() { + return mRunningJobs; + } + + @GuardedBy("mLock") boolean isJobRunningLocked(JobStatus job) { return mRunningJobs.contains(job); } @@ -546,7 +579,7 @@ class JobConcurrencyManager { } final List<JobStatus> pendingJobs = mService.mPendingJobs; - final List<JobServiceContext> activeServices = mService.mActiveServices; + final List<JobServiceContext> activeServices = mActiveServices; // To avoid GC churn, we recycle the arrays. JobStatus[] contextIdToJobMap = mRecycledAssignContextIdToJobMap; @@ -719,9 +752,44 @@ class JobConcurrencyManager { } @GuardedBy("mLock") + boolean stopJobOnServiceContextLocked(JobStatus job, + @JobParameters.StopReason int reason, int internalReasonCode, String debugReason) { + if (!mRunningJobs.contains(job)) { + return false; + } + + for (int i = 0; i < mActiveServices.size(); i++) { + JobServiceContext jsc = mActiveServices.get(i); + final JobStatus executing = jsc.getRunningJobLocked(); + if (executing != null && executing.matches(job.getUid(), job.getJobId())) { + jsc.cancelExecutingJobLocked(reason, internalReasonCode, debugReason); + return true; + } + } + Slog.wtf(TAG, "Couldn't find running job on a context"); + mRunningJobs.remove(job); + return false; + } + + @GuardedBy("mLock") + private void stopUnexemptedJobsForDoze() { + // When becoming idle, make sure no jobs are actively running, + // except those using the idle exemption flag. + for (int i = 0; i < mActiveServices.size(); i++) { + JobServiceContext jsc = mActiveServices.get(i); + final JobStatus executing = jsc.getRunningJobLocked(); + if (executing != null && !executing.canRunInDoze()) { + jsc.cancelExecutingJobLocked(JobParameters.STOP_REASON_DEVICE_STATE, + JobParameters.INTERNAL_STOP_REASON_DEVICE_IDLE, + "cancelled due to doze"); + } + } + } + + @GuardedBy("mLock") private void stopLongRunningJobsLocked(@NonNull String debugReason) { for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; ++i) { - final JobServiceContext jsc = mService.mActiveServices.get(i); + final JobServiceContext jsc = mActiveServices.get(i); final JobStatus jobStatus = jsc.getRunningJobLocked(); if (jobStatus != null && !jsc.isWithinExecutionGuaranteeTime()) { @@ -731,6 +799,41 @@ class JobConcurrencyManager { } } + @GuardedBy("mLock") + void stopNonReadyActiveJobsLocked() { + for (int i = 0; i < mActiveServices.size(); i++) { + JobServiceContext serviceContext = mActiveServices.get(i); + final JobStatus running = serviceContext.getRunningJobLocked(); + if (running == null) { + continue; + } + if (!running.isReady()) { + if (running.getEffectiveStandbyBucket() == RESTRICTED_INDEX + && running.getStopReason() == JobParameters.STOP_REASON_APP_STANDBY) { + serviceContext.cancelExecutingJobLocked( + running.getStopReason(), + JobParameters.INTERNAL_STOP_REASON_RESTRICTED_BUCKET, + "cancelled due to restricted bucket"); + } else { + serviceContext.cancelExecutingJobLocked( + running.getStopReason(), + JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED, + "cancelled due to unsatisfied constraints"); + } + } else { + final JobRestriction restriction = mService.checkIfRestricted(running); + if (restriction != null) { + final int internalReasonCode = restriction.getInternalReason(); + serviceContext.cancelExecutingJobLocked(restriction.getReason(), + internalReasonCode, + "restricted due to " + + JobParameters.getInternalReasonCodeDescription( + internalReasonCode)); + } + } + } + } + private void noteConcurrency() { mService.mJobPackageTracker.noteConcurrency(mRunningJobs.size(), // TODO: log per type instead of only TOP @@ -1078,6 +1181,24 @@ class JobConcurrencyManager { } @GuardedBy("mLock") + boolean executeTimeoutCommandLocked(PrintWriter pw, String pkgName, int userId, + boolean hasJobId, int jobId) { + boolean foundSome = false; + for (int i = 0; i < mActiveServices.size(); i++) { + final JobServiceContext jc = mActiveServices.get(i); + final JobStatus js = jc.getRunningJobLocked(); + if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) { + foundSome = true; + pw.print("Timing out: "); + js.printUniqueId(pw); + pw.print(" "); + pw.println(js.getServiceComponent().flattenToShortString()); + } + } + return foundSome; + } + + @GuardedBy("mLock") private String printPendingQueueLocked() { StringBuilder s = new StringBuilder("Pending queue: "); Iterator<JobStatus> it = mService.mPendingJobs.iterator(); @@ -1200,6 +1321,43 @@ class JobConcurrencyManager { } } + @GuardedBy("mLock") + void dumpActiveJobsLocked(IndentingPrintWriter pw, Predicate<JobStatus> predicate, + long nowElapsed, long nowUptime) { + pw.println("Active jobs:"); + pw.increaseIndent(); + for (int i = 0; i < mActiveServices.size(); i++) { + JobServiceContext jsc = mActiveServices.get(i); + final JobStatus job = jsc.getRunningJobLocked(); + + if (job != null && !predicate.test(job)) { + continue; + } + + pw.print("Slot #"); pw.print(i); pw.print(": "); + jsc.dumpLocked(pw, nowElapsed); + + if (job != null) { + pw.increaseIndent(); + + pw.increaseIndent(); + job.dump(pw, false, nowElapsed); + pw.decreaseIndent(); + + pw.print("Evaluated bias: "); + pw.println(JobInfo.getBiasString(job.lastEvaluatedBias)); + + pw.print("Active at "); + TimeUtils.formatDuration(job.madeActive - nowUptime, pw); + pw.print(", pending for "); + TimeUtils.formatDuration(job.madeActive - job.madePending, pw); + pw.decreaseIndent(); + pw.println(); + } + } + pw.decreaseIndent(); + } + public void dumpProtoLocked(ProtoOutputStream proto, long tag, long now, long nowRealtime) { final long token = proto.start(tag); diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java index b9362789c6c6..3d74bc98ad32 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java @@ -57,7 +57,6 @@ import android.content.pm.ServiceInfo; import android.net.Uri; import android.os.BatteryManager; import android.os.BatteryManagerInternal; -import android.os.BatteryStats; import android.os.BatteryStatsInternal; import android.os.Binder; import android.os.Handler; @@ -67,7 +66,6 @@ import android.os.Message; import android.os.ParcelFileDescriptor; import android.os.Process; import android.os.RemoteException; -import android.os.ServiceManager; import android.os.SystemClock; import android.os.UserHandle; import android.os.WorkSource; @@ -90,7 +88,6 @@ import android.util.proto.ProtoOutputStream; import com.android.internal.annotations.GuardedBy; import com.android.internal.annotations.VisibleForTesting; -import com.android.internal.app.IBatteryStats; import com.android.internal.os.SomeArgs; import com.android.internal.util.ArrayUtils; import com.android.internal.util.DumpUtils; @@ -100,7 +97,6 @@ import com.android.server.AppStateTrackerImpl; import com.android.server.DeviceIdleInternal; import com.android.server.JobSchedulerBackgroundThread; import com.android.server.LocalServices; -import com.android.server.job.JobSchedulerServiceDumpProto.ActiveJob; import com.android.server.job.JobSchedulerServiceDumpProto.PendingJob; import com.android.server.job.controllers.BackgroundJobsController; import com.android.server.job.controllers.BatteryController; @@ -243,12 +239,6 @@ public class JobSchedulerService extends com.android.server.SystemService static final int MSG_CHECK_CHANGED_JOB_LIST = 8; static final int MSG_CHECK_MEDIA_EXEMPTION = 9; - /** - * Track Services that have currently active or pending jobs. The index is provided by - * {@link JobStatus#getServiceToken()} - */ - final List<JobServiceContext> mActiveServices = new ArrayList<>(); - /** List of controllers that will notify this service of updates to jobs. */ final List<StateController> mControllers; /** @@ -307,7 +297,6 @@ public class JobSchedulerService extends com.android.server.SystemService PackageManagerInternal mLocalPM; ActivityManagerInternal mActivityManagerInternal; - IBatteryStats mBatteryStats; DeviceIdleInternal mLocalDeviceIdleController; @VisibleForTesting AppStateTrackerImpl mAppStateTracker; @@ -1578,7 +1567,8 @@ public class JobSchedulerService extends com.android.server.SystemService mJobPackageTracker.noteNonpending(cancelled); } // Cancel if running. - stopJobOnServiceContextLocked(cancelled, reason, internalReasonCode, debugReason); + mConcurrencyManager.stopJobOnServiceContextLocked( + cancelled, reason, internalReasonCode, debugReason); // If this is a replacement, bring in the new version of the job if (incomingJob != null) { if (DEBUG) Slog.i(TAG, "Tracking replacement job " + incomingJob.toShortString()); @@ -1627,19 +1617,7 @@ public class JobSchedulerService extends com.android.server.SystemService if (DEBUG) { Slog.d(TAG, "Doze state changed: " + deviceIdle); } - if (deviceIdle) { - // When becoming idle, make sure no jobs are actively running, - // except those using the idle exemption flag. - for (int i=0; i<mActiveServices.size(); i++) { - JobServiceContext jsc = mActiveServices.get(i); - final JobStatus executing = jsc.getRunningJobLocked(); - if (executing != null && !executing.canRunInDoze()) { - jsc.cancelExecutingJobLocked(JobParameters.STOP_REASON_DEVICE_STATE, - JobParameters.INTERNAL_STOP_REASON_DEVICE_IDLE, - "cancelled due to doze"); - } - } - } else { + if (!deviceIdle) { // When coming out of idle, allow thing to start back up. if (mReadyToRock) { if (mLocalDeviceIdleController != null) { @@ -1682,10 +1660,10 @@ public class JobSchedulerService extends com.android.server.SystemService // active is true if pending queue contains jobs OR some job is running. boolean active = mPendingJobs.size() > 0; if (mPendingJobs.size() <= 0) { - for (int i=0; i<mActiveServices.size(); i++) { - final JobServiceContext jsc = mActiveServices.get(i); - final JobStatus job = jsc.getRunningJobLocked(); - if (job != null && !job.canRunInDoze()) { + final ArraySet<JobStatus> runningJobs = mConcurrencyManager.getRunningJobsLocked(); + for (int i = runningJobs.size() - 1; i >= 0; --i) { + final JobStatus job = runningJobs.valueAt(i); + if (!job.canRunInDoze()) { // We will report active if we have a job running and it does not have an // exception that allows it to run in Doze. active = true; @@ -1895,16 +1873,9 @@ public class JobSchedulerService extends com.android.server.SystemService synchronized (mLock) { // Let's go! mReadyToRock = true; - mBatteryStats = IBatteryStats.Stub.asInterface(ServiceManager.getService( - BatteryStats.SERVICE_NAME)); mLocalDeviceIdleController = LocalServices.getService(DeviceIdleInternal.class); - // Create the "runners". - for (int i = 0; i < MAX_JOB_CONTEXTS_COUNT; i++) { - mActiveServices.add( - new JobServiceContext(this, mConcurrencyManager, mBatteryStats, - mJobPackageTracker, getContext().getMainLooper())); - } + mConcurrencyManager.onThirdPartyAppsCanStart(); // Attach jobs to their controllers. mJobs.forEachJob((job) -> { for (int controller = 0; controller < mControllers.size(); controller++) { @@ -1961,19 +1932,6 @@ public class JobSchedulerService extends com.android.server.SystemService return removed; } - private boolean stopJobOnServiceContextLocked(JobStatus job, - @JobParameters.StopReason int reason, int internalReasonCode, String debugReason) { - for (int i = 0; i < mActiveServices.size(); i++) { - JobServiceContext jsc = mActiveServices.get(i); - final JobStatus executing = jsc.getRunningJobLocked(); - if (executing != null && executing.matches(job.getUid(), job.getJobId())) { - jsc.cancelExecutingJobLocked(reason, internalReasonCode, debugReason); - return true; - } - } - return false; - } - /** Return {@code true} if the specified job is currently executing. */ @GuardedBy("mLock") public boolean isCurrentlyRunningLocked(JobStatus job) { @@ -2383,7 +2341,8 @@ public class JobSchedulerService extends com.android.server.SystemService * - if passes all the restrictions or has {@link JobInfo#BIAS_FOREGROUND_SERVICE} bias * or higher. */ - private JobRestriction checkIfRestricted(JobStatus job) { + @GuardedBy("mLock") + JobRestriction checkIfRestricted(JobStatus job) { if (evaluateJobBiasLocked(job) >= JobInfo.BIAS_FOREGROUND_SERVICE) { // Jobs with BIAS_FOREGROUND_SERVICE or higher should not be restricted return null; @@ -2397,38 +2356,9 @@ public class JobSchedulerService extends com.android.server.SystemService return null; } + @GuardedBy("mLock") private void stopNonReadyActiveJobsLocked() { - for (int i=0; i<mActiveServices.size(); i++) { - JobServiceContext serviceContext = mActiveServices.get(i); - final JobStatus running = serviceContext.getRunningJobLocked(); - if (running == null) { - continue; - } - if (!running.isReady()) { - if (running.getEffectiveStandbyBucket() == RESTRICTED_INDEX - && running.getStopReason() == JobParameters.STOP_REASON_APP_STANDBY) { - serviceContext.cancelExecutingJobLocked( - running.getStopReason(), - JobParameters.INTERNAL_STOP_REASON_RESTRICTED_BUCKET, - "cancelled due to restricted bucket"); - } else { - serviceContext.cancelExecutingJobLocked( - running.getStopReason(), - JobParameters.INTERNAL_STOP_REASON_CONSTRAINTS_NOT_SATISFIED, - "cancelled due to unsatisfied constraints"); - } - } else { - final JobRestriction restriction = checkIfRestricted(running); - if (restriction != null) { - final int internalReasonCode = restriction.getInternalReason(); - serviceContext.cancelExecutingJobLocked(restriction.getReason(), - internalReasonCode, - "restricted due to " - + JobParameters.getInternalReasonCodeDescription( - internalReasonCode)); - } - } - } + mConcurrencyManager.stopNonReadyActiveJobsLocked(); } /** @@ -2598,7 +2528,7 @@ public class JobSchedulerService extends com.android.server.SystemService debugReason = "couldn't figure out why the job should stop running"; } } - stopJobOnServiceContextLocked(job, job.getStopReason(), + mConcurrencyManager.stopJobOnServiceContextLocked(job, job.getStopReason(), internalStopReason, debugReason); } else if (mPendingJobs.remove(job)) { noteJobNonPending(job); @@ -3516,9 +3446,11 @@ public class JobSchedulerService extends com.android.server.SystemService final ArrayList<JobInfo> runningJobs; synchronized (mLock) { - runningJobs = new ArrayList<>(mActiveServices.size()); - for (JobServiceContext jsc : mActiveServices) { - final JobStatus job = jsc.getRunningJobLocked(); + final ArraySet<JobStatus> runningJobStatuses = + mConcurrencyManager.getRunningJobsLocked(); + runningJobs = new ArrayList<>(runningJobStatuses.size()); + for (int i = runningJobStatuses.size() - 1; i >= 0; --i) { + final JobStatus job = runningJobStatuses.valueAt(i); if (job != null) { runningJobs.add(job.getJob()); } @@ -3599,18 +3531,8 @@ public class JobSchedulerService extends com.android.server.SystemService } synchronized (mLock) { - boolean foundSome = false; - for (int i = 0; i < mActiveServices.size(); i++) { - final JobServiceContext jc = mActiveServices.get(i); - final JobStatus js = jc.getRunningJobLocked(); - if (jc.timeoutIfExecutingLocked(pkgName, userId, hasJobId, jobId, "shell")) { - foundSome = true; - pw.print("Timing out: "); - js.printUniqueId(pw); - pw.print(" "); - pw.println(js.getServiceComponent().flattenToShortString()); - } - } + final boolean foundSome = mConcurrencyManager.executeTimeoutCommandLocked(pw, + pkgName, userId, hasJobId, jobId); if (!foundSome) { pw.println("No matching executing jobs found."); } @@ -4037,38 +3959,7 @@ public class JobSchedulerService extends com.android.server.SystemService pw.decreaseIndent(); pw.println(); - pw.println("Active jobs:"); - pw.increaseIndent(); - for (int i=0; i<mActiveServices.size(); i++) { - JobServiceContext jsc = mActiveServices.get(i); - final JobStatus job = jsc.getRunningJobLocked(); - - if (job != null && !predicate.test(job)) { - continue; - } - - pw.print("Slot #"); pw.print(i); pw.print(": "); - jsc.dumpLocked(pw, nowElapsed); - - if (job != null) { - pw.increaseIndent(); - - pw.increaseIndent(); - job.dump(pw, false, nowElapsed); - pw.decreaseIndent(); - - pw.print("Evaluated bias: "); - pw.println(JobInfo.getBiasString(job.lastEvaluatedBias)); - - pw.print("Active at "); - TimeUtils.formatDuration(job.madeActive - nowUptime, pw); - pw.print(", pending for "); - TimeUtils.formatDuration(job.madeActive - job.madePending, pw); - pw.decreaseIndent(); - pw.println(); - } - } - pw.decreaseIndent(); + mConcurrencyManager.dumpActiveJobsLocked(pw, predicate, nowElapsed, nowUptime); pw.println(); boolean recentPrinted = false; @@ -4228,45 +4119,6 @@ public class JobSchedulerService extends com.android.server.SystemService proto.end(pjToken); } - for (JobServiceContext jsc : mActiveServices) { - final long ajToken = proto.start(JobSchedulerServiceDumpProto.ACTIVE_JOBS); - final JobStatus job = jsc.getRunningJobLocked(); - - if (job == null) { - final long ijToken = proto.start(ActiveJob.INACTIVE); - - proto.write(ActiveJob.InactiveJob.TIME_SINCE_STOPPED_MS, - nowElapsed - jsc.mStoppedTime); - if (jsc.mStoppedReason != null) { - proto.write(ActiveJob.InactiveJob.STOPPED_REASON, - jsc.mStoppedReason); - } - - proto.end(ijToken); - } else { - final long rjToken = proto.start(ActiveJob.RUNNING); - - job.writeToShortProto(proto, ActiveJob.RunningJob.INFO); - - proto.write(ActiveJob.RunningJob.RUNNING_DURATION_MS, - nowElapsed - jsc.getExecutionStartTimeElapsed()); - proto.write(ActiveJob.RunningJob.TIME_UNTIL_TIMEOUT_MS, - jsc.getTimeoutElapsed() - nowElapsed); - - job.dump(proto, ActiveJob.RunningJob.DUMP, false, nowElapsed); - - proto.write(ActiveJob.RunningJob.EVALUATED_PRIORITY, - evaluateJobBiasLocked(job)); - - proto.write(ActiveJob.RunningJob.TIME_SINCE_MADE_ACTIVE_MS, - nowUptime - job.madeActive); - proto.write(ActiveJob.RunningJob.PENDING_DURATION_MS, - job.madeActive - job.madePending); - - proto.end(rjToken); - } - proto.end(ajToken); - } if (filterUid == -1) { proto.write(JobSchedulerServiceDumpProto.IS_READY_TO_ROCK, mReadyToRock); proto.write(JobSchedulerServiceDumpProto.REPORTED_ACTIVE, mReportedActive); diff --git a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java index efcf14f07ee9..30fdb1e9ad4e 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java +++ b/apex/jobscheduler/service/java/com/android/server/job/controllers/JobStatus.java @@ -441,11 +441,6 @@ public final class JobStatus { /** The reason a job most recently went from ready to not ready. */ private int mReasonReadyToUnready = JobParameters.STOP_REASON_UNDEFINED; - /** Provide a handle to the service that this job will be run on. */ - public int getServiceToken() { - return callingUid; - } - /** * Core constructor for JobStatus instances. All other ctors funnel down to this one. * diff --git a/core/api/current.txt b/core/api/current.txt index 50fa85dcc30a..2e4b4b56c359 100644 --- a/core/api/current.txt +++ b/core/api/current.txt @@ -5815,6 +5815,7 @@ package android.app { public class LocaleManager { method @NonNull public android.os.LocaleList getApplicationLocales(); method @NonNull @RequiresPermission(value="android.permission.READ_APP_SPECIFIC_LOCALES", conditional=true) public android.os.LocaleList getApplicationLocales(@NonNull String); + method @NonNull public android.os.LocaleList getSystemLocales(); method public void setApplicationLocales(@NonNull android.os.LocaleList); } @@ -9737,8 +9738,8 @@ package android.content { method @Nullable public abstract android.content.Intent registerReceiver(android.content.BroadcastReceiver, android.content.IntentFilter, @Nullable String, @Nullable android.os.Handler, int); method @Deprecated @RequiresPermission(android.Manifest.permission.BROADCAST_STICKY) public abstract void removeStickyBroadcast(@RequiresPermission android.content.Intent); method @Deprecated @RequiresPermission(allOf={"android.permission.INTERACT_ACROSS_USERS", android.Manifest.permission.BROADCAST_STICKY}) public abstract void removeStickyBroadcastAsUser(@RequiresPermission android.content.Intent, android.os.UserHandle); - method public void revokeOwnPermissionOnKill(@NonNull String); - method public void revokeOwnPermissionsOnKill(@NonNull java.util.Collection<java.lang.String>); + method public void revokeSelfPermissionOnKill(@NonNull String); + method public void revokeSelfPermissionsOnKill(@NonNull java.util.Collection<java.lang.String>); method public abstract void revokeUriPermission(android.net.Uri, int); method public abstract void revokeUriPermission(String, android.net.Uri, int); method public abstract void sendBroadcast(@RequiresPermission android.content.Intent); @@ -10126,12 +10127,16 @@ package android.content { method @Nullable public long[] getLongArrayExtra(String); method public long getLongExtra(String, long); method @Nullable public String getPackage(); - method @Nullable public android.os.Parcelable[] getParcelableArrayExtra(String); - method @Nullable public <T extends android.os.Parcelable> java.util.ArrayList<T> getParcelableArrayListExtra(String); - method @Nullable public <T extends android.os.Parcelable> T getParcelableExtra(String); + method @Deprecated @Nullable public android.os.Parcelable[] getParcelableArrayExtra(String); + method @Nullable public <T> T[] getParcelableArrayExtra(@Nullable String, @NonNull Class<T>); + method @Deprecated @Nullable public <T extends android.os.Parcelable> java.util.ArrayList<T> getParcelableArrayListExtra(String); + method @Nullable public <T> java.util.ArrayList<T> getParcelableArrayListExtra(@Nullable String, @NonNull Class<? extends T>); + method @Deprecated @Nullable public <T extends android.os.Parcelable> T getParcelableExtra(String); + method @Nullable public <T> T getParcelableExtra(@Nullable String, @NonNull Class<T>); method @Nullable public String getScheme(); method @Nullable public android.content.Intent getSelector(); - method @Nullable public java.io.Serializable getSerializableExtra(String); + method @Deprecated @Nullable public java.io.Serializable getSerializableExtra(String); + method @Nullable public <T extends java.io.Serializable> T getSerializableExtra(@Nullable String, @NonNull Class<T>); method @Nullable public short[] getShortArrayExtra(String); method public short getShortExtra(String, short); method @Nullable public android.graphics.Rect getSourceBounds(); @@ -19488,26 +19493,26 @@ package android.location { method @NonNull public static String convert(@FloatRange double, int); method @FloatRange public static double convert(@NonNull String); method public int describeContents(); - method public static void distanceBetween(@FloatRange double, @FloatRange double, @FloatRange double, @FloatRange double, float[]); - method @FloatRange public float distanceTo(@NonNull android.location.Location); - method public void dump(@NonNull android.util.Printer, @Nullable String); - method @FloatRange public float getAccuracy(); + method public static void distanceBetween(@FloatRange(from=-90.0, to=90.0) double, @FloatRange(from=-180.0, to=180.0) double, @FloatRange(from=-90.0, to=90.0) double, @FloatRange(from=-180.0, to=180.0) double, float[]); + method @FloatRange(from=0.0) public float distanceTo(@NonNull android.location.Location); + method @Deprecated public void dump(@NonNull android.util.Printer, @Nullable String); + method @FloatRange(from=0.0) public float getAccuracy(); method @FloatRange public double getAltitude(); - method @FloatRange(from=0.0f, to=360.0f, toInclusive=false) public float getBearing(); - method @FloatRange public float getBearingAccuracyDegrees(); - method @IntRange public long getElapsedRealtimeAgeMillis(); - method @IntRange public long getElapsedRealtimeAgeMillis(@IntRange long); - method @IntRange public long getElapsedRealtimeMillis(); - method @IntRange public long getElapsedRealtimeNanos(); - method @FloatRange public double getElapsedRealtimeUncertaintyNanos(); + method @FloatRange(from=0.0, to=360.0, toInclusive=false) public float getBearing(); + method @FloatRange(from=0.0) public float getBearingAccuracyDegrees(); + method @IntRange(from=0) public long getElapsedRealtimeAgeMillis(); + method public long getElapsedRealtimeAgeMillis(@IntRange(from=0) long); + method @IntRange(from=0) public long getElapsedRealtimeMillis(); + method @IntRange(from=0) public long getElapsedRealtimeNanos(); + method @FloatRange(from=0.0) public double getElapsedRealtimeUncertaintyNanos(); method @Nullable public android.os.Bundle getExtras(); - method @FloatRange public double getLatitude(); - method @FloatRange public double getLongitude(); + method @FloatRange(from=-90.0, to=90.0) public double getLatitude(); + method @FloatRange(from=-180.0, to=180.0) public double getLongitude(); method @Nullable public String getProvider(); - method @FloatRange public float getSpeed(); - method @FloatRange public float getSpeedAccuracyMetersPerSecond(); - method @IntRange public long getTime(); - method @FloatRange public float getVerticalAccuracyMeters(); + method @FloatRange(from=0.0) public float getSpeed(); + method @FloatRange(from=0.0) public float getSpeedAccuracyMetersPerSecond(); + method @IntRange(from=0) public long getTime(); + method @FloatRange(from=0.0) public float getVerticalAccuracyMeters(); method public boolean hasAccuracy(); method public boolean hasAltitude(); method public boolean hasBearing(); @@ -19529,21 +19534,21 @@ package android.location { method public void removeVerticalAccuracy(); method public void reset(); method public void set(@NonNull android.location.Location); - method public void setAccuracy(@FloatRange float); + method public void setAccuracy(@FloatRange(from=0.0) float); method public void setAltitude(@FloatRange double); method public void setBearing(@FloatRange(fromInclusive=false, toInclusive=false) float); - method public void setBearingAccuracyDegrees(@FloatRange float); - method public void setElapsedRealtimeNanos(@IntRange long); - method public void setElapsedRealtimeUncertaintyNanos(@FloatRange double); + method public void setBearingAccuracyDegrees(@FloatRange(from=0.0) float); + method public void setElapsedRealtimeNanos(@IntRange(from=0) long); + method public void setElapsedRealtimeUncertaintyNanos(@FloatRange(from=0.0) double); method public void setExtras(@Nullable android.os.Bundle); - method public void setLatitude(@FloatRange double); - method public void setLongitude(@FloatRange double); + method public void setLatitude(@FloatRange(from=-90.0, to=90.0) double); + method public void setLongitude(@FloatRange(from=-180.0, to=180.0) double); method public void setMock(boolean); method public void setProvider(@Nullable String); - method public void setSpeed(@FloatRange float); - method public void setSpeedAccuracyMetersPerSecond(@FloatRange float); - method public void setTime(@IntRange long); - method public void setVerticalAccuracyMeters(@FloatRange float); + method public void setSpeed(@FloatRange(from=0.0) float); + method public void setSpeedAccuracyMetersPerSecond(@FloatRange(from=0.0) float); + method public void setTime(@IntRange(from=0) long); + method public void setVerticalAccuracyMeters(@FloatRange(from=0.0) float); method public void writeToParcel(@NonNull android.os.Parcel, int); field @NonNull public static final android.os.Parcelable.Creator<android.location.Location> CREATOR; field public static final int FORMAT_DEGREES = 0; // 0x0 @@ -22187,7 +22192,7 @@ package android.media { field public static final String KEY_AAC_DRC_OUTPUT_LOUDNESS = "aac-drc-output-loudness"; field public static final String KEY_AAC_DRC_TARGET_REFERENCE_LEVEL = "aac-target-ref-level"; field public static final String KEY_AAC_ENCODED_TARGET_LEVEL = "aac-encoded-target-level"; - field public static final String KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT = "aac-max-output-channel_count"; + field @Deprecated public static final String KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT = "aac-max-output-channel_count"; field public static final String KEY_AAC_PROFILE = "aac-profile"; field public static final String KEY_AAC_SBR_MODE = "aac-sbr-mode"; field public static final String KEY_ALLOW_FRAME_DROP = "allow-frame-drop"; @@ -23549,17 +23554,24 @@ package android.media { } public class Spatializer { + method public void addOnHeadTrackerAvailableListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.Spatializer.OnHeadTrackerAvailableListener); method public void addOnSpatializerStateChangedListener(@NonNull java.util.concurrent.Executor, @NonNull android.media.Spatializer.OnSpatializerStateChangedListener); method public boolean canBeSpatialized(@NonNull android.media.AudioAttributes, @NonNull android.media.AudioFormat); method public int getImmersiveAudioLevel(); method public boolean isAvailable(); method public boolean isEnabled(); + method public boolean isHeadTrackerAvailable(); + method public void removeOnHeadTrackerAvailableListener(@NonNull android.media.Spatializer.OnHeadTrackerAvailableListener); method public void removeOnSpatializerStateChangedListener(@NonNull android.media.Spatializer.OnSpatializerStateChangedListener); field public static final int SPATIALIZER_IMMERSIVE_LEVEL_MULTICHANNEL = 1; // 0x1 field public static final int SPATIALIZER_IMMERSIVE_LEVEL_NONE = 0; // 0x0 field public static final int SPATIALIZER_IMMERSIVE_LEVEL_OTHER = -1; // 0xffffffff } + public static interface Spatializer.OnHeadTrackerAvailableListener { + method public void onHeadTrackerAvailableChanged(@NonNull android.media.Spatializer, boolean); + } + public static interface Spatializer.OnSpatializerStateChangedListener { method public void onSpatializerAvailableChanged(@NonNull android.media.Spatializer, boolean); method public void onSpatializerEnabledChanged(@NonNull android.media.Spatializer, boolean); @@ -26099,21 +26111,8 @@ package android.media.tv.interactive { method @NonNull public android.media.tv.interactive.AppLinkInfo.Builder setUriScheme(@NonNull String); } - public final class TvInteractiveAppInfo implements android.os.Parcelable { - ctor public TvInteractiveAppInfo(@NonNull android.content.Context, @NonNull android.content.ComponentName); - method public int describeContents(); - method @NonNull public String getId(); - method @Nullable public android.content.pm.ServiceInfo getServiceInfo(); - method @NonNull public int getSupportedTypes(); - method public void writeToParcel(@NonNull android.os.Parcel, int); - field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.interactive.TvInteractiveAppInfo> CREATOR; - field public static final int INTERACTIVE_APP_TYPE_ATSC = 2; // 0x2 - field public static final int INTERACTIVE_APP_TYPE_GINGA = 4; // 0x4 - field public static final int INTERACTIVE_APP_TYPE_HBBTV = 1; // 0x1 - } - public final class TvInteractiveAppManager { - method @NonNull public java.util.List<android.media.tv.interactive.TvInteractiveAppInfo> getTvInteractiveAppServiceList(); + method @NonNull public java.util.List<android.media.tv.interactive.TvInteractiveAppServiceInfo> getTvInteractiveAppServiceList(); method public void prepare(@NonNull String, int); method public void registerAppLinkInfo(@NonNull String, @NonNull android.media.tv.interactive.AppLinkInfo); method public void registerCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.tv.interactive.TvInteractiveAppManager.TvInteractiveAppCallback); @@ -26137,6 +26136,7 @@ package android.media.tv.interactive { field public static final String INTENT_KEY_BI_INTERACTIVE_APP_TYPE = "bi_interactive_app_type"; field public static final String INTENT_KEY_BI_INTERACTIVE_APP_URI = "bi_interactive_app_uri"; field public static final String INTENT_KEY_CHANNEL_URI = "channel_uri"; + field public static final String INTENT_KEY_COMMAND_TYPE = "command_type"; field public static final String INTENT_KEY_INTERACTIVE_APP_SERVICE_ID = "interactive_app_id"; field public static final String INTENT_KEY_TV_INPUT_ID = "tv_input_id"; field public static final int INTERACTIVE_APP_STATE_ERROR = 3; // 0x3 @@ -26211,6 +26211,7 @@ package android.media.tv.interactive { method public abstract boolean onSetSurface(@Nullable android.view.Surface); method public void onSetTeletextAppEnabled(boolean); method public void onSignalStrength(int); + method public void onSigningResult(@NonNull String, @NonNull byte[]); method public void onStartInteractiveApp(); method public void onStopInteractiveApp(); method public void onStreamVolume(float); @@ -26229,6 +26230,7 @@ package android.media.tv.interactive { method @CallSuper public void requestCurrentChannelLcn(); method @CallSuper public void requestCurrentChannelUri(); method @CallSuper public void requestCurrentTvInputId(); + method @CallSuper public void requestSigning(@NonNull String, @NonNull String, @NonNull String, @NonNull byte[]); method @CallSuper public void requestStreamVolume(); method @CallSuper public void requestTrackInfoList(); method @CallSuper public void sendPlaybackCommandRequest(@NonNull String, @Nullable android.os.Bundle); @@ -26236,6 +26238,19 @@ package android.media.tv.interactive { method @CallSuper public void setVideoBounds(@NonNull android.graphics.Rect); } + public final class TvInteractiveAppServiceInfo implements android.os.Parcelable { + ctor public TvInteractiveAppServiceInfo(@NonNull android.content.Context, @NonNull android.content.ComponentName); + method public int describeContents(); + method @NonNull public String getId(); + method @Nullable public android.content.pm.ServiceInfo getServiceInfo(); + method @NonNull public int getSupportedTypes(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.media.tv.interactive.TvInteractiveAppServiceInfo> CREATOR; + field public static final int INTERACTIVE_APP_TYPE_ATSC = 2; // 0x2 + field public static final int INTERACTIVE_APP_TYPE_GINGA = 4; // 0x4 + field public static final int INTERACTIVE_APP_TYPE_HBBTV = 1; // 0x1 + } + public class TvInteractiveAppView extends android.view.ViewGroup { ctor public TvInteractiveAppView(@NonNull android.content.Context); ctor public TvInteractiveAppView(@NonNull android.content.Context, @Nullable android.util.AttributeSet); @@ -26257,6 +26272,7 @@ package android.media.tv.interactive { method public void sendCurrentChannelLcn(int); method public void sendCurrentChannelUri(@Nullable android.net.Uri); method public void sendCurrentTvInputId(@Nullable String); + method public void sendSigningResult(@NonNull String, @NonNull byte[]); method public void sendStreamVolume(float); method public void sendTrackInfoList(@Nullable java.util.List<android.media.tv.TvTrackInfo>); method public void setCallback(@NonNull java.util.concurrent.Executor, @NonNull android.media.tv.interactive.TvInteractiveAppView.TvInteractiveAppCallback); @@ -26265,6 +26281,9 @@ package android.media.tv.interactive { method public int setTvView(@Nullable android.media.tv.TvView); method public void startInteractiveApp(); method public void stopInteractiveApp(); + field public static final String BI_INTERACTIVE_APP_KEY_ALIAS = "alias"; + field public static final String BI_INTERACTIVE_APP_KEY_CERTIFICATE = "certificate"; + field public static final String BI_INTERACTIVE_APP_KEY_PRIVATE_KEY = "private_key"; } public static interface TvInteractiveAppView.OnUnhandledInputEventListener { @@ -26278,6 +26297,7 @@ package android.media.tv.interactive { method public void onRequestCurrentChannelLcn(@NonNull String); method public void onRequestCurrentChannelUri(@NonNull String); method public void onRequestCurrentTvInputId(@NonNull String); + method public void onRequestSigning(@NonNull String, @NonNull String, @NonNull String, @NonNull String, @NonNull byte[]); method public void onRequestStreamVolume(@NonNull String); method public void onRequestTrackInfoList(@NonNull String); method public void onSetVideoBounds(@NonNull String, @NonNull android.graphics.Rect); diff --git a/core/api/system-current.txt b/core/api/system-current.txt index 2bdc35cf70e5..3359179201a9 100644 --- a/core/api/system-current.txt +++ b/core/api/system-current.txt @@ -5491,6 +5491,32 @@ package android.location { method @NonNull public android.location.GnssCapabilities.Builder setHasSatellitePvt(boolean); } + public final class GnssExcessPathInfo implements android.os.Parcelable { + method public int describeContents(); + method @FloatRange(from=0.0f) public float getAttenuationDb(); + method @FloatRange(from=0.0f) public float getExcessPathLengthMeters(); + method @FloatRange(from=0.0f) public float getExcessPathLengthUncertaintyMeters(); + method @NonNull public android.location.GnssReflectingPlane getReflectingPlane(); + method public boolean hasAttenuation(); + method public boolean hasExcessPathLength(); + method public boolean hasExcessPathLengthUncertainty(); + method public boolean hasReflectingPlane(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.location.GnssExcessPathInfo> CREATOR; + } + + public static final class GnssExcessPathInfo.Builder { + ctor public GnssExcessPathInfo.Builder(); + method @NonNull public android.location.GnssExcessPathInfo build(); + method @NonNull public android.location.GnssExcessPathInfo.Builder clearAttenuationDb(); + method @NonNull public android.location.GnssExcessPathInfo.Builder clearExcessPathLengthMeters(); + method @NonNull public android.location.GnssExcessPathInfo.Builder clearExcessPathLengthUncertaintyMeters(); + method @NonNull public android.location.GnssExcessPathInfo.Builder setAttenuationDb(@FloatRange(from=0.0f) float); + method @NonNull public android.location.GnssExcessPathInfo.Builder setExcessPathLengthMeters(@FloatRange(from=0.0f) float); + method @NonNull public android.location.GnssExcessPathInfo.Builder setExcessPathLengthUncertaintyMeters(@FloatRange(from=0.0f) float); + method @NonNull public android.location.GnssExcessPathInfo.Builder setReflectingPlane(@Nullable android.location.GnssReflectingPlane); + } + public final class GnssMeasurement implements android.os.Parcelable { method @Nullable public java.util.Collection<android.location.CorrelationVector> getCorrelationVectors(); method @Nullable public android.location.SatellitePvt getSatellitePvt(); @@ -5572,15 +5598,18 @@ package android.location { public final class GnssSingleSatCorrection implements android.os.Parcelable { method public int describeContents(); method @FloatRange(from=0.0f, fromInclusive=false) public float getCarrierFrequencyHz(); + method @FloatRange(from=0.0f) public float getCombinedAttenuationDb(); method public int getConstellationType(); method @FloatRange(from=0.0f) public float getExcessPathLengthMeters(); method @FloatRange(from=0.0f) public float getExcessPathLengthUncertaintyMeters(); + method @NonNull public java.util.List<android.location.GnssExcessPathInfo> getGnssExcessPathInfoList(); method @FloatRange(from=0.0f, to=1.0f) public float getProbabilityLineOfSight(); - method @Nullable public android.location.GnssReflectingPlane getReflectingPlane(); + method @Deprecated @Nullable public android.location.GnssReflectingPlane getReflectingPlane(); method @IntRange(from=0) public int getSatelliteId(); + method public boolean hasCombinedAttenuation(); method public boolean hasExcessPathLength(); method public boolean hasExcessPathLengthUncertainty(); - method public boolean hasReflectingPlane(); + method @Deprecated public boolean hasReflectingPlane(); method public boolean hasValidSatelliteLineOfSight(); method public void writeToParcel(@NonNull android.os.Parcel, int); field public static final android.os.Parcelable.Creator<android.location.GnssSingleSatCorrection> CREATOR; @@ -5589,15 +5618,18 @@ package android.location { public static final class GnssSingleSatCorrection.Builder { ctor public GnssSingleSatCorrection.Builder(); method @NonNull public android.location.GnssSingleSatCorrection build(); + method @NonNull public android.location.GnssSingleSatCorrection.Builder clearCombinedAttenuationDb(); method @NonNull public android.location.GnssSingleSatCorrection.Builder clearExcessPathLengthMeters(); method @NonNull public android.location.GnssSingleSatCorrection.Builder clearExcessPathLengthUncertaintyMeters(); method @NonNull public android.location.GnssSingleSatCorrection.Builder clearProbabilityLineOfSight(); method @NonNull public android.location.GnssSingleSatCorrection.Builder setCarrierFrequencyHz(@FloatRange(from=0.0f, fromInclusive=false) float); + method @NonNull public android.location.GnssSingleSatCorrection.Builder setCombinedAttenuationDb(@FloatRange(from=0.0f) float); method @NonNull public android.location.GnssSingleSatCorrection.Builder setConstellationType(int); method @NonNull public android.location.GnssSingleSatCorrection.Builder setExcessPathLengthMeters(@FloatRange(from=0.0f) float); method @NonNull public android.location.GnssSingleSatCorrection.Builder setExcessPathLengthUncertaintyMeters(@FloatRange(from=0.0f) float); + method @NonNull public android.location.GnssSingleSatCorrection.Builder setGnssExcessPathInfoList(@NonNull java.util.List<android.location.GnssExcessPathInfo>); method @NonNull public android.location.GnssSingleSatCorrection.Builder setProbabilityLineOfSight(@FloatRange(from=0.0f, to=1.0f) float); - method @NonNull public android.location.GnssSingleSatCorrection.Builder setReflectingPlane(@Nullable android.location.GnssReflectingPlane); + method @Deprecated @NonNull public android.location.GnssSingleSatCorrection.Builder setReflectingPlane(@Nullable android.location.GnssReflectingPlane); method @NonNull public android.location.GnssSingleSatCorrection.Builder setSatelliteId(@IntRange(from=0) int); } @@ -10050,9 +10082,9 @@ package android.permission { method @BinderThread public void onOneTimePermissionSessionTimeout(@NonNull String); method @Deprecated @BinderThread public void onRestoreDelayedRuntimePermissionsBackup(@NonNull String, @NonNull android.os.UserHandle, @NonNull java.util.function.Consumer<java.lang.Boolean>); method @Deprecated @BinderThread public void onRestoreRuntimePermissionsBackup(@NonNull android.os.UserHandle, @NonNull java.io.InputStream, @NonNull Runnable); - method @BinderThread public void onRevokeOwnPermissionsOnKill(@NonNull String, @NonNull java.util.List<java.lang.String>, @NonNull Runnable); method @BinderThread public abstract void onRevokeRuntimePermission(@NonNull String, @NonNull String, @NonNull Runnable); method @BinderThread public abstract void onRevokeRuntimePermissions(@NonNull java.util.Map<java.lang.String,java.util.List<java.lang.String>>, boolean, int, @NonNull String, @NonNull java.util.function.Consumer<java.util.Map<java.lang.String,java.util.List<java.lang.String>>>); + method @BinderThread public void onRevokeSelfPermissionsOnKill(@NonNull String, @NonNull java.util.List<java.lang.String>, @NonNull Runnable); method @Deprecated @BinderThread public abstract void onSetRuntimePermissionGrantStateByDeviceAdmin(@NonNull String, @NonNull String, @NonNull String, int, @NonNull java.util.function.Consumer<java.lang.Boolean>); method @BinderThread public void onSetRuntimePermissionGrantStateByDeviceAdmin(@NonNull String, @NonNull android.permission.AdminPermissionControlParams, @NonNull java.util.function.Consumer<java.lang.Boolean>); method @BinderThread public void onStageAndApplyRuntimePermissionsBackup(@NonNull android.os.UserHandle, @NonNull java.io.InputStream, @NonNull Runnable); diff --git a/core/api/test-current.txt b/core/api/test-current.txt index 2e8bed32665c..d984abe457c9 100644 --- a/core/api/test-current.txt +++ b/core/api/test-current.txt @@ -300,7 +300,6 @@ package android.app { } public class LocaleManager { - method @Nullable public android.os.LocaleList getSystemLocales(); method public void setSystemLocales(@NonNull android.os.LocaleList); } diff --git a/core/java/android/app/ContextImpl.java b/core/java/android/app/ContextImpl.java index f5eb1f6e24ed..ac46066997ff 100644 --- a/core/java/android/app/ContextImpl.java +++ b/core/java/android/app/ContextImpl.java @@ -77,6 +77,7 @@ import android.os.Trace; import android.os.UserHandle; import android.os.UserManager; import android.os.storage.StorageManager; +import android.permission.PermissionControllerManager; import android.permission.PermissionManager; import android.system.ErrnoException; import android.system.Os; @@ -216,6 +217,12 @@ class ContextImpl extends Context { @UnsupportedAppUsage private @Nullable ClassLoader mClassLoader; + /** + * The {@link com.android.server.wm.WindowToken} representing this instance if it is + * {@link #CONTEXT_TYPE_WINDOW_CONTEXT} or {@link #CONTEXT_TYPE_SYSTEM_OR_SYSTEM_UI}. + * If the type is {@link #CONTEXT_TYPE_ACTIVITY}, then represents the + * {@link android.window.WindowContainerToken} of the activity. + */ private final @Nullable IBinder mToken; private final @NonNull UserHandle mUser; @@ -2180,8 +2187,9 @@ class ContextImpl extends Context { } @Override - public void revokeOwnPermissionsOnKill(@NonNull Collection<String> permissions) { - getSystemService(PermissionManager.class).revokeOwnPermissionsOnKill(permissions); + public void revokeSelfPermissionsOnKill(@NonNull Collection<String> permissions) { + getSystemService(PermissionControllerManager.class).revokeSelfPermissionsOnKill( + getPackageName(), new ArrayList<String>(permissions)); } @Override diff --git a/core/java/android/app/GameManager.java b/core/java/android/app/GameManager.java index 6f49c9e647a4..a138fa1f6fd5 100644 --- a/core/java/android/app/GameManager.java +++ b/core/java/android/app/GameManager.java @@ -191,7 +191,7 @@ public final class GameManager { */ @TestApi @RequiresPermission(Manifest.permission.MANAGE_GAME_MODE) - public @GameMode boolean isAngleEnabled(@NonNull String packageName) { + public boolean isAngleEnabled(@NonNull String packageName) { try { return mService.isAngleEnabled(packageName, mContext.getUserId()); } catch (RemoteException e) { diff --git a/core/java/android/app/ILocaleManager.aidl b/core/java/android/app/ILocaleManager.aidl index 348cb2d30739..3002c8bb9c3e 100644 --- a/core/java/android/app/ILocaleManager.aidl +++ b/core/java/android/app/ILocaleManager.aidl @@ -40,4 +40,9 @@ import android.os.LocaleList; */ LocaleList getApplicationLocales(String packageName, int userId); + /** + * Returns the current system locales. + */ + LocaleList getSystemLocales(); + }
\ No newline at end of file diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java index cedf483eb076..e9c29b8aa0a5 100644 --- a/core/java/android/app/KeyguardManager.java +++ b/core/java/android/app/KeyguardManager.java @@ -1103,9 +1103,12 @@ public class KeyguardManager { } /** - * Registers a listener to execute when the keyguard visibility changes. + * Registers a listener to execute when the keyguard locked state changes. * - * @param listener The listener to add to receive keyguard visibility changes. + * @param listener The listener to add to receive keyguard locked state changes. + * + * @see #isKeyguardLocked() + * @see #removeKeyguardLockedStateListener(KeyguardLockedStateListener) */ @RequiresPermission(Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE) public void addKeyguardLockedStateListener(@NonNull @CallbackExecutor Executor executor, @@ -1124,7 +1127,12 @@ public class KeyguardManager { } /** - * Unregisters a listener that executes when the keyguard visibility changes. + * Unregisters a listener that executes when the keyguard locked state changes. + * + * @param listener The listener to remove. + * + * @see #isKeyguardLocked() + * @see #addKeyguardLockedStateListener(Executor, KeyguardLockedStateListener) */ @RequiresPermission(Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE) public void removeKeyguardLockedStateListener(@NonNull KeyguardLockedStateListener listener) { diff --git a/core/java/android/app/LocaleManager.java b/core/java/android/app/LocaleManager.java index 522dc845f57c..efe9e35d4c64 100644 --- a/core/java/android/app/LocaleManager.java +++ b/core/java/android/app/LocaleManager.java @@ -18,7 +18,6 @@ package android.app; import android.Manifest; import android.annotation.NonNull; -import android.annotation.Nullable; import android.annotation.RequiresPermission; import android.annotation.SystemApi; import android.annotation.SystemService; @@ -127,31 +126,36 @@ public class LocaleManager { } /** - * Sets the current system locales to the provided value. + * Returns the current system locales, ignoring app-specific overrides. * - * @hide + * <p><b>Note:</b> Apps should generally access the user's locale preferences as indicated in + * their in-process {@link LocaleList}s. However, in case an app-specific locale is set, this + * method helps cater to rare use-cases which might require specifically knowing the system + * locale. + * + * <p><b>Note:</b> This API is not user-aware. It returns the system locales for the foreground + * user. */ - @TestApi - public void setSystemLocales(@NonNull LocaleList locales) { + @NonNull + public LocaleList getSystemLocales() { try { - Configuration conf = ActivityManager.getService().getConfiguration(); - conf.setLocales(locales); - ActivityManager.getService().updatePersistentConfiguration(conf); + return mService.getSystemLocales(); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } /** - * Returns the current system locales for the device. + * Sets the current system locales to the provided value. * * @hide */ @TestApi - @Nullable - public LocaleList getSystemLocales() { + public void setSystemLocales(@NonNull LocaleList locales) { try { - return ActivityManager.getService().getConfiguration().getLocales(); + Configuration conf = ActivityManager.getService().getConfiguration(); + conf.setLocales(locales); + ActivityManager.getService().updatePersistentConfiguration(conf); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } diff --git a/core/java/android/app/admin/FactoryResetProtectionPolicy.java b/core/java/android/app/admin/FactoryResetProtectionPolicy.java index 40ae1f0c11ea..7e951779d2a6 100644 --- a/core/java/android/app/admin/FactoryResetProtectionPolicy.java +++ b/core/java/android/app/admin/FactoryResetProtectionPolicy.java @@ -25,6 +25,7 @@ import android.annotation.Nullable; import android.content.ComponentName; import android.os.Parcel; import android.os.Parcelable; +import android.util.IndentingPrintWriter; import android.util.Log; import android.util.TypedXmlPullParser; import android.util.TypedXmlSerializer; @@ -254,4 +255,18 @@ public final class FactoryResetProtectionPolicy implements Parcelable { return !mFactoryResetProtectionAccounts.isEmpty() && mFactoryResetProtectionEnabled; } + /** + * @hide + */ + public void dump(IndentingPrintWriter pw) { + pw.print("factoryResetProtectionEnabled="); + pw.println(mFactoryResetProtectionEnabled); + + pw.print("factoryResetProtectionAccounts="); + pw.increaseIndent(); + for (int i = 0; i < mFactoryResetProtectionAccounts.size(); i++) { + pw.println(mFactoryResetProtectionAccounts.get(i)); + } + pw.decreaseIndent(); + } } diff --git a/core/java/android/app/usage/BroadcastResponseStats.java b/core/java/android/app/usage/BroadcastResponseStats.java index e1d37e1b1ae0..572c45355e42 100644 --- a/core/java/android/app/usage/BroadcastResponseStats.java +++ b/core/java/android/app/usage/BroadcastResponseStats.java @@ -29,6 +29,8 @@ import java.util.Objects; * Class containing a collection of stats related to response events started from an app * after receiving a broadcast. * + * @see UsageStatsManager#queryBroadcastResponseStats(String, long) + * @see UsageStatsManager#clearBroadcastResponseStats(String, long) * @hide */ @SystemApi diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java index 60efb4d3ec81..24b1b6adb450 100644 --- a/core/java/android/content/Context.java +++ b/core/java/android/content/Context.java @@ -6508,22 +6508,22 @@ public abstract class Context { /** - * Triggers the asynchronous revocation of a permission. + * Triggers the asynchronous revocation of a runtime permission. If the permission is not + * currently granted, nothing happens (even if later granted by the user). * * @param permName The name of the permission to be revoked. - * @see #revokeOwnPermissionsOnKill(Collection) + * @see #revokeSelfPermissionsOnKill(Collection) + * @throws IllegalArgumentException if the permission is not a runtime permission */ - public void revokeOwnPermissionOnKill(@NonNull String permName) { - revokeOwnPermissionsOnKill(Collections.singletonList(permName)); + public void revokeSelfPermissionOnKill(@NonNull String permName) { + revokeSelfPermissionsOnKill(Collections.singletonList(permName)); } /** * Triggers the revocation of one or more permissions for the calling package. A package is only - * able to revoke a permission under the following conditions: - * <ul> - * <li>Each permission in {@code permissions} must be granted to the calling package. - * <li>Each permission in {@code permissions} must be a runtime permission. - * </ul> + * able to revoke runtime permissions. If a permission is not currently granted, it is ignored + * and will not get revoked (even if later granted by the user). Ultimately, you should never + * make assumptions about a permission status as users may grant or revoke them at any time. * <p> * Background permissions which have no corresponding foreground permission still granted once * the revocation is effective will also be revoked. @@ -6549,8 +6549,9 @@ public abstract class Context { * @param permissions Collection of permissions to be revoked. * @see PackageManager#getGroupOfPlatformPermission(String, Executor, Consumer) * @see PackageManager#getPlatformPermissionsForGroup(String, Executor, Consumer) + * @throws IllegalArgumentException if any of the permissions is not a runtime permission */ - public void revokeOwnPermissionsOnKill(@NonNull Collection<String> permissions) { + public void revokeSelfPermissionsOnKill(@NonNull Collection<String> permissions) { throw new AbstractMethodError("Must be overridden in implementing class"); } @@ -7145,8 +7146,9 @@ public abstract class Context { } /** - * Returns token if the {@link Context} is a {@link android.app.WindowContext}. Returns - * {@code null} otherwise. + * Returns the {@link IBinder} representing the associated + * {@link com.android.server.wm.WindowToken} if the {@link Context} is a + * {@link android.app.WindowContext}. Returns {@code null} otherwise. * * @hide */ diff --git a/core/java/android/content/ContextWrapper.java b/core/java/android/content/ContextWrapper.java index 9adf17367039..4ecd7761ac4f 100644 --- a/core/java/android/content/ContextWrapper.java +++ b/core/java/android/content/ContextWrapper.java @@ -1036,8 +1036,8 @@ public class ContextWrapper extends Context { } @Override - public void revokeOwnPermissionsOnKill(@NonNull Collection<String> permissions) { - mBase.revokeOwnPermissionsOnKill(permissions); + public void revokeSelfPermissionsOnKill(@NonNull Collection<String> permissions) { + mBase.revokeSelfPermissionsOnKill(permissions); } @Override diff --git a/core/java/android/content/Intent.java b/core/java/android/content/Intent.java index 478befd9c26d..2c207bc90444 100644 --- a/core/java/android/content/Intent.java +++ b/core/java/android/content/Intent.java @@ -8903,8 +8903,12 @@ public class Intent implements Parcelable, Cloneable { * @return the value of an item previously added with putExtra(), * or null if no Parcelable value was found. * + * @deprecated Use the type-safer {@link #getParcelableExtra(String, Class)} starting from + * Android {@link Build.VERSION_CODES#TIRAMISU}. + * * @see #putExtra(String, Parcelable) */ + @Deprecated public @Nullable <T extends Parcelable> T getParcelableExtra(String name) { return mExtras == null ? null : mExtras.<T>getParcelable(name); } @@ -8913,12 +8917,31 @@ public class Intent implements Parcelable, Cloneable { * Retrieve extended data from the intent. * * @param name The name of the desired item. + * @param clazz The type of the object expected. + * + * @return the value of an item previously added with putExtra(), + * or null if no Parcelable value was found. + * + * @see #putExtra(String, Parcelable) + */ + public @Nullable <T> T getParcelableExtra(@Nullable String name, @NonNull Class<T> clazz) { + return mExtras == null ? null : mExtras.getParcelable(name, clazz); + } + + /** + * Retrieve extended data from the intent. + * + * @param name The name of the desired item. * * @return the value of an item previously added with putExtra(), * or null if no Parcelable[] value was found. * + * @deprecated Use the type-safer {@link #getParcelableArrayExtra(String, Class)} starting from + * Android {@link Build.VERSION_CODES#TIRAMISU}. + * * @see #putExtra(String, Parcelable[]) */ + @Deprecated public @Nullable Parcelable[] getParcelableArrayExtra(String name) { return mExtras == null ? null : mExtras.getParcelableArray(name); } @@ -8927,13 +8950,34 @@ public class Intent implements Parcelable, Cloneable { * Retrieve extended data from the intent. * * @param name The name of the desired item. + * @param clazz The type of the items inside the array. This is only verified when unparceling. + * + * @return the value of an item previously added with putExtra(), + * or null if no Parcelable[] value was found. + * + * @see #putExtra(String, Parcelable[]) + */ + @SuppressLint({"ArrayReturn", "NullableCollection"}) + public @Nullable <T> T[] getParcelableArrayExtra(@Nullable String name, + @NonNull Class<T> clazz) { + return mExtras == null ? null : mExtras.getParcelableArray(name, clazz); + } + + /** + * Retrieve extended data from the intent. + * + * @param name The name of the desired item. * * @return the value of an item previously added with * putParcelableArrayListExtra(), or null if no * ArrayList<Parcelable> value was found. * + * @deprecated Use the type-safer {@link #getParcelableArrayListExtra(String, Class)} starting + * from Android {@link Build.VERSION_CODES#TIRAMISU}. + * * @see #putParcelableArrayListExtra(String, ArrayList) */ + @Deprecated public @Nullable <T extends Parcelable> ArrayList<T> getParcelableArrayListExtra(String name) { return mExtras == null ? null : mExtras.<T>getParcelableArrayList(name); } @@ -8942,10 +8986,32 @@ public class Intent implements Parcelable, Cloneable { * Retrieve extended data from the intent. * * @param name The name of the desired item. + * @param clazz The type of the items inside the array list. This is only verified when + * unparceling. + * + * @return the value of an item previously added with + * putParcelableArrayListExtra(), or null if no + * ArrayList<Parcelable> value was found. + * + * @see #putParcelableArrayListExtra(String, ArrayList) + */ + @SuppressLint({"ConcreteCollection", "NullableCollection"}) + public @Nullable <T> ArrayList<T> getParcelableArrayListExtra(@Nullable String name, + @NonNull Class<? extends T> clazz) { + return mExtras == null ? null : mExtras.<T>getParcelableArrayList(name, clazz); + } + + /** + * Retrieve extended data from the intent. + * + * @param name The name of the desired item. * * @return the value of an item previously added with putExtra(), * or null if no Serializable value was found. * + * @deprecated Use the type-safer {@link #getSerializableExtra(String, Class)} starting from + * Android {@link Build.VERSION_CODES#TIRAMISU}. + * * @see #putExtra(String, Serializable) */ public @Nullable Serializable getSerializableExtra(String name) { @@ -8956,6 +9022,22 @@ public class Intent implements Parcelable, Cloneable { * Retrieve extended data from the intent. * * @param name The name of the desired item. + * @param clazz The type of the object expected. + * + * @return the value of an item previously added with putExtra(), + * or null if no Serializable value was found. + * + * @see #putExtra(String, Serializable) + */ + public @Nullable <T extends Serializable> T getSerializableExtra(@Nullable String name, + @NonNull Class<T> clazz) { + return mExtras == null ? null : mExtras.getSerializable(name, clazz); + } + + /** + * Retrieve extended data from the intent. + * + * @param name The name of the desired item. * * @return the value of an item previously added with * putIntegerArrayListExtra(), or null if no diff --git a/core/java/android/content/pm/PackageInfo.java b/core/java/android/content/pm/PackageInfo.java index eefa63f5b8fa..f4de82946253 100644 --- a/core/java/android/content/pm/PackageInfo.java +++ b/core/java/android/content/pm/PackageInfo.java @@ -213,7 +213,8 @@ public class PackageInfo implements Parcelable { * or null if there were none. This is only filled in if the flag * {@link PackageManager#GET_PERMISSIONS} was set. Each value matches * the corresponding entry in {@link #requestedPermissions}, and will have - * the flag {@link #REQUESTED_PERMISSION_GRANTED} set as appropriate. + * the flags {@link #REQUESTED_PERMISSION_GRANTED} and + * {@link #REQUESTED_PERMISSION_NEVER_FOR_LOCATION} set as appropriate. */ public int[] requestedPermissionsFlags; diff --git a/core/java/android/content/res/AssetManager.java b/core/java/android/content/res/AssetManager.java index a05f5c927b29..c8bbb0c1994d 100644 --- a/core/java/android/content/res/AssetManager.java +++ b/core/java/android/content/res/AssetManager.java @@ -79,6 +79,13 @@ public final class AssetManager implements AutoCloseable { @GuardedBy("sSync") private static ArraySet<ApkAssets> sSystemApkAssetsSet; /** + * Cookie value to use when the actual cookie is unknown. This value tells the system to search + * all the ApkAssets for the asset. + * @hide + */ + public static final int COOKIE_UNKNOWN = -1; + + /** * Mode for {@link #open(String, int)}: no specific information about how * data will be accessed. */ diff --git a/core/java/android/inputmethodservice/NavigationBarController.java b/core/java/android/inputmethodservice/NavigationBarController.java index 0f9075b498ae..03d11515c0a8 100644 --- a/core/java/android/inputmethodservice/NavigationBarController.java +++ b/core/java/android/inputmethodservice/NavigationBarController.java @@ -294,8 +294,8 @@ final class NavigationBarController { dest.setTouchableInsets( ViewTreeObserver.InternalInsetsInfo.TOUCHABLE_INSETS_REGION); - // TODO(b/205803355): See if we can use View#OnLayoutChangeListener(). - // TODO(b/205803355): See if we can replace DecorView#mNavigationColorViewState.view + // TODO(b/215443343): See if we can use View#OnLayoutChangeListener(). + // TODO(b/215443343): See if we can replace DecorView#mNavigationColorViewState.view boolean zOrderChanged = false; if (decor instanceof ViewGroup) { ViewGroup decorGroup = (ViewGroup) decor; diff --git a/core/java/android/inputmethodservice/navigationbar/DeadZone.java b/core/java/android/inputmethodservice/navigationbar/DeadZone.java index 4cfd8139d912..382b6b074962 100644 --- a/core/java/android/inputmethodservice/navigationbar/DeadZone.java +++ b/core/java/android/inputmethodservice/navigationbar/DeadZone.java @@ -148,7 +148,7 @@ final class DeadZone { if (DEBUG) { Log.v(TAG, this + " ACTION_DOWN: " + event.getX() + "," + event.getY()); } - //TODO(b/205803355): call mNavBarController.touchAutoDim(mDisplayId); here + //TODO(b/215443343): call mNavBarController.touchAutoDim(mDisplayId); here int size = (int) getSize(event.getEventTime()); // In the vertical orientation consume taps along the left edge. // In horizontal orientation consume taps along the top edge. diff --git a/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java b/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java index cfdb6caab9d3..92d358fe1663 100644 --- a/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java +++ b/core/java/android/inputmethodservice/navigationbar/KeyButtonView.java @@ -89,7 +89,7 @@ public class KeyButtonView extends ImageView implements ButtonInterface { public KeyButtonView(Context context, AttributeSet attrs) { super(context, attrs); - // TODO(b/205803355): Figure out better place to set this. + // TODO(b/215443343): Figure out better place to set this. switch (getId()) { case com.android.internal.R.id.input_method_nav_back: mCode = KEYCODE_BACK; @@ -285,11 +285,11 @@ public class KeyButtonView extends ImageView implements ButtonInterface { private void sendEvent(int action, int flags, long when) { if (mCode == KeyEvent.KEYCODE_BACK && flags != KeyEvent.FLAG_LONG_PRESS) { if (action == MotionEvent.ACTION_UP) { - // TODO(b/205803355): Implement notifyBackAction(); + // TODO(b/215443343): Implement notifyBackAction(); } } - // TODO(b/205803355): Consolidate this logic to somewhere else. + // TODO(b/215443343): Consolidate this logic to somewhere else. if (mContext instanceof InputMethodService) { final int repeatCount = (flags & KeyEvent.FLAG_LONG_PRESS) != 0 ? 1 : 0; final KeyEvent ev = new KeyEvent(mDownTime, when, action, mCode, repeatCount, diff --git a/core/java/android/net/SntpClient.java b/core/java/android/net/SntpClient.java index 0eb4cf3ecadf..b05f7cf241e3 100644 --- a/core/java/android/net/SntpClient.java +++ b/core/java/android/net/SntpClient.java @@ -60,7 +60,7 @@ public class SntpClient { private static final int TRANSMIT_TIME_OFFSET = 40; private static final int NTP_PACKET_SIZE = 48; - private static final int NTP_PORT = 123; + public static final int STANDARD_NTP_PORT = 123; private static final int NTP_MODE_CLIENT = 3; private static final int NTP_MODE_SERVER = 4; private static final int NTP_MODE_BROADCAST = 5; @@ -108,18 +108,21 @@ public class SntpClient { * Sends an SNTP request to the given host and processes the response. * * @param host host name of the server. + * @param port port of the server. * @param timeout network timeout in milliseconds. the timeout doesn't include the DNS lookup * time, and it applies to each individual query to the resolved addresses of * the NTP server. * @param network network over which to send the request. * @return true if the transaction was successful. */ - public boolean requestTime(String host, int timeout, Network network) { + public boolean requestTime(String host, int port, int timeout, Network network) { final Network networkForResolv = network.getPrivateDnsBypassingCopy(); try { final InetAddress[] addresses = networkForResolv.getAllByName(host); for (int i = 0; i < addresses.length; i++) { - if (requestTime(addresses[i], NTP_PORT, timeout, networkForResolv)) return true; + if (requestTime(addresses[i], port, timeout, networkForResolv)) { + return true; + } } } catch (UnknownHostException e) { Log.w(TAG, "Unknown host: " + host); diff --git a/core/java/android/os/storage/IStorageManager.aidl b/core/java/android/os/storage/IStorageManager.aidl index c021c079ae2e..a0f6598640ba 100644 --- a/core/java/android/os/storage/IStorageManager.aidl +++ b/core/java/android/os/storage/IStorageManager.aidl @@ -125,7 +125,6 @@ interface IStorageManager { boolean isUserKeyUnlocked(int userId) = 65; void prepareUserStorage(in String volumeUuid, int userId, int serialNumber, int flags) = 66; void destroyUserStorage(in String volumeUuid, int userId, int flags) = 67; - boolean isConvertibleToFBE() = 68; void addUserKeyAuth(int userId, int serialNumber, in byte[] secret) = 70; void fixateNewestUserKeyAuth(int userId) = 71; void fstrim(int flags, IVoldTaskListener listener) = 72; diff --git a/core/java/android/permission/IPermissionController.aidl b/core/java/android/permission/IPermissionController.aidl index c9dd06cfaa43..e3f02e73a41f 100644 --- a/core/java/android/permission/IPermissionController.aidl +++ b/core/java/android/permission/IPermissionController.aidl @@ -59,6 +59,6 @@ oneway interface IPermissionController { void getHibernationEligibility( in String packageName, in AndroidFuture callback); - void revokeOwnPermissionsOnKill(in String packageName, in List<String> permissions, + void revokeSelfPermissionsOnKill(in String packageName, in List<String> permissions, in AndroidFuture callback); } diff --git a/core/java/android/permission/IPermissionManager.aidl b/core/java/android/permission/IPermissionManager.aidl index 619c8705ddae..6a93b354f4da 100644 --- a/core/java/android/permission/IPermissionManager.aidl +++ b/core/java/android/permission/IPermissionManager.aidl @@ -76,8 +76,6 @@ interface IPermissionManager { List<SplitPermissionInfoParcelable> getSplitPermissions(); - void revokeOwnPermissionsOnKill(String packageName, in List<String> permissions); - void startOneTimePermissionSession(String packageName, int userId, long timeout, long revokeAfterKilledDelay, int importanceToResetTimer, int importanceToKeepSessionAlive); diff --git a/core/java/android/permission/PermissionControllerManager.java b/core/java/android/permission/PermissionControllerManager.java index a005ab4e6ac7..3c2c7f03761b 100644 --- a/core/java/android/permission/PermissionControllerManager.java +++ b/core/java/android/permission/PermissionControllerManager.java @@ -916,15 +916,15 @@ public final class PermissionControllerManager { * @param packageName The name of the package for which the permissions will be revoked. * @param permissions List of permissions to be revoked. * - * @see Context#revokeOwnPermissionsOnKill(java.util.Collection) + * @see Context#revokeSelfPermissionsOnKill(java.util.Collection) * * @hide */ - public void revokeOwnPermissionsOnKill(@NonNull String packageName, + public void revokeSelfPermissionsOnKill(@NonNull String packageName, @NonNull List<String> permissions) { mRemoteService.postAsync(service -> { AndroidFuture<Void> callback = new AndroidFuture<>(); - service.revokeOwnPermissionsOnKill(packageName, permissions, callback); + service.revokeSelfPermissionsOnKill(packageName, permissions, callback); return callback; }).whenComplete((result, err) -> { if (err != null) { diff --git a/core/java/android/permission/PermissionControllerService.java b/core/java/android/permission/PermissionControllerService.java index 3292e7110ee5..4efffc5a11ef 100644 --- a/core/java/android/permission/PermissionControllerService.java +++ b/core/java/android/permission/PermissionControllerService.java @@ -40,6 +40,7 @@ import android.compat.annotation.Disabled; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; +import android.os.Binder; import android.os.Bundle; import android.os.IBinder; import android.os.ParcelFileDescriptor; @@ -339,10 +340,10 @@ public abstract class PermissionControllerService extends Service { * @param permissions List of permissions to be revoked. * @param callback Callback waiting for operation to be complete. * - * @see PermissionManager#revokeOwnPermissionsOnKill(java.util.Collection) + * @see android.content.Context#revokeSelfPermissionsOnKill(java.util.Collection) */ @BinderThread - public void onRevokeOwnPermissionsOnKill(@NonNull String packageName, + public void onRevokeSelfPermissionsOnKill(@NonNull String packageName, @NonNull List<String> permissions, @NonNull Runnable callback) { throw new AbstractMethodError("Must be overridden in implementing class"); } @@ -703,13 +704,19 @@ public abstract class PermissionControllerService extends Service { } @Override - public void revokeOwnPermissionsOnKill(@NonNull String packageName, + public void revokeSelfPermissionsOnKill(@NonNull String packageName, @NonNull List<String> permissions, @NonNull AndroidFuture callback) { try { - enforceSomePermissionsGrantedToCaller( - Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); Objects.requireNonNull(callback); - onRevokeOwnPermissionsOnKill(packageName, permissions, + + final int callingUid = Binder.getCallingUid(); + int targetPackageUid = getPackageManager().getPackageUid(packageName, + PackageManager.PackageInfoFlags.of(0)); + if (targetPackageUid != callingUid) { + enforceSomePermissionsGrantedToCaller( + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); + } + onRevokeSelfPermissionsOnKill(packageName, permissions, () -> callback.complete(null)); } catch (Throwable t) { callback.completeExceptionally(t); diff --git a/core/java/android/permission/PermissionManager.java b/core/java/android/permission/PermissionManager.java index c509de6bb5e1..7a797ce28870 100644 --- a/core/java/android/permission/PermissionManager.java +++ b/core/java/android/permission/PermissionManager.java @@ -76,7 +76,6 @@ import com.android.internal.annotations.Immutable; import com.android.internal.util.CollectionUtils; import java.util.ArrayList; -import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -626,19 +625,6 @@ public final class PermissionManager { } /** - * @see Context#revokeOwnPermissionsOnKill(Collection) - * @hide - */ - public void revokeOwnPermissionsOnKill(@NonNull Collection<String> permissions) { - try { - mPermissionManager.revokeOwnPermissionsOnKill(mContext.getPackageName(), - new ArrayList<String>(permissions)); - } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); - } - } - - /** * Gets the state flags associated with a permission. * * @param packageName the package name for which to get the flags diff --git a/core/java/android/permission/PermissionUsageHelper.java b/core/java/android/permission/PermissionUsageHelper.java index 0b57842cde11..4ed939c48bd7 100644 --- a/core/java/android/permission/PermissionUsageHelper.java +++ b/core/java/android/permission/PermissionUsageHelper.java @@ -47,6 +47,7 @@ import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.res.Resources; import android.icu.text.ListFormatter; +import android.location.LocationManager; import android.media.AudioManager; import android.os.Process; import android.os.UserHandle; @@ -411,10 +412,13 @@ public class PermissionUsageHelper implements AppOpsManager.OnOpActiveChangedLis } /** - * Returns true if the app supports subattribution. + * Returns true if the app satisfies subattribution policies and supports it */ private boolean isSubattributionSupported(String packageName, int uid) { try { + if (!isLocationProvider(packageName)) { + return false; + } PackageManager userPkgManager = getUserContext(UserHandle.getUserHandleForUid(uid)).getPackageManager(); ApplicationInfo appInfo = userPkgManager.getApplicationInfoAsUser(packageName, @@ -430,6 +434,15 @@ public class PermissionUsageHelper implements AppOpsManager.OnOpActiveChangedLis } /** + * @param packageName + * @return If the package is location provider + */ + private boolean isLocationProvider(String packageName) { + return Objects.requireNonNull( + mContext.getSystemService(LocationManager.class)).isProviderPackage(packageName); + } + + /** * Get the raw usages from the system, and then parse out the ones that are not recent enough, * determine which permission group each belongs in, and removes duplicates (if the same app * uses multiple permissions of the same group). Stores the package name, attribution tag, user, diff --git a/core/java/android/util/NtpTrustedTime.java b/core/java/android/util/NtpTrustedTime.java index aebc5e86605a..01a037ae3495 100644 --- a/core/java/android/util/NtpTrustedTime.java +++ b/core/java/android/util/NtpTrustedTime.java @@ -140,6 +140,10 @@ public class NtpTrustedTime implements TrustedTime { /** An in-memory config override for use during tests. */ @Nullable + private Integer mPortForTests; + + /** An in-memory config override for use during tests. */ + @Nullable private Duration mTimeoutForTests; // Declared volatile and accessed outside of synchronized blocks to avoid blocking reads during @@ -163,9 +167,11 @@ public class NtpTrustedTime implements TrustedTime { * Overrides the NTP server config for tests. Passing {@code null} to a parameter clears the * test value, i.e. so the normal value will be used next time. */ - public void setServerConfigForTests(@Nullable String hostname, @Nullable Duration timeout) { + public void setServerConfigForTests( + @Nullable String hostname, @Nullable Integer port, @Nullable Duration timeout) { synchronized (this) { mHostnameForTests = hostname; + mPortForTests = port; mTimeoutForTests = timeout; } } @@ -195,8 +201,9 @@ public class NtpTrustedTime implements TrustedTime { if (LOGD) Log.d(TAG, "forceRefresh() from cache miss"); final SntpClient client = new SntpClient(); final String serverName = connectionInfo.getServer(); + final int port = connectionInfo.getPort(); final int timeoutMillis = connectionInfo.getTimeoutMillis(); - if (client.requestTime(serverName, timeoutMillis, network)) { + if (client.requestTime(serverName, port, timeoutMillis, network)) { long ntpCertainty = client.getRoundTripTime() / 2; mTimeResult = new TimeResult( client.getNtpTime(), client.getNtpTimeReference(), ntpCertainty); @@ -297,10 +304,12 @@ public class NtpTrustedTime implements TrustedTime { private static class NtpConnectionInfo { @NonNull private final String mServer; + private final int mPort; private final int mTimeoutMillis; - NtpConnectionInfo(@NonNull String server, int timeoutMillis) { + NtpConnectionInfo(@NonNull String server, int port, int timeoutMillis) { mServer = Objects.requireNonNull(server); + mPort = port; mTimeoutMillis = timeoutMillis; } @@ -309,6 +318,11 @@ public class NtpTrustedTime implements TrustedTime { return mServer; } + @NonNull + public int getPort() { + return mPort; + } + int getTimeoutMillis() { return mTimeoutMillis; } @@ -317,6 +331,7 @@ public class NtpTrustedTime implements TrustedTime { public String toString() { return "NtpConnectionInfo{" + "mServer='" + mServer + '\'' + + ", mPort='" + mPort + '\'' + ", mTimeoutMillis=" + mTimeoutMillis + '}'; } @@ -341,6 +356,13 @@ public class NtpTrustedTime implements TrustedTime { } } + final Integer port; + if (mPortForTests != null) { + port = mPortForTests; + } else { + port = SntpClient.STANDARD_NTP_PORT; + } + final int timeoutMillis; if (mTimeoutForTests != null) { timeoutMillis = (int) mTimeoutForTests.toMillis(); @@ -350,7 +372,8 @@ public class NtpTrustedTime implements TrustedTime { timeoutMillis = Settings.Global.getInt( resolver, Settings.Global.NTP_TIMEOUT, defaultTimeoutMillis); } - return TextUtils.isEmpty(hostname) ? null : new NtpConnectionInfo(hostname, timeoutMillis); + return TextUtils.isEmpty(hostname) ? null : + new NtpConnectionInfo(hostname, port, timeoutMillis); } /** Prints debug information. */ diff --git a/core/java/android/util/TimingsTraceLog.java b/core/java/android/util/TimingsTraceLog.java index 066709fd8744..48a5ceae1aef 100644 --- a/core/java/android/util/TimingsTraceLog.java +++ b/core/java/android/util/TimingsTraceLog.java @@ -147,7 +147,7 @@ public class TimingsTraceLog { * Logs a duration so it can be parsed by external tools for performance reporting. */ public void logDuration(String name, long timeMs) { - Slog.d(mTag, name + " took to complete: " + timeMs + "ms"); + Slog.v(mTag, name + " took to complete: " + timeMs + "ms"); } /** diff --git a/core/java/android/view/ContentRecordingSession.java b/core/java/android/view/ContentRecordingSession.java index db4ec1155e64..c66c70af0656 100644 --- a/core/java/android/view/ContentRecordingSession.java +++ b/core/java/android/view/ContentRecordingSession.java @@ -66,10 +66,11 @@ public final class ContentRecordingSession implements Parcelable { private int mContentToRecord = RECORD_CONTENT_DISPLAY; /** - * The window token of the layer of the hierarchy to record. - * The display content if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_DISPLAY}, or task if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_TASK}. + * The token of the layer of the hierarchy to record. + * If {@link #getContentToRecord()} is @link RecordContent#RECORD_CONTENT_DISPLAY}, then + * represents the WindowToken corresponding to the DisplayContent to record. + * If {@link #getContentToRecord()} is {@link RecordContent#RECORD_CONTENT_TASK}, then + * represents the {@link android.window.WindowContainerToken} of the Task to record. */ @VisibleForTesting @Nullable @@ -192,10 +193,11 @@ public final class ContentRecordingSession implements Parcelable { } /** - * The window token of the layer of the hierarchy to record. - * The display content if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_DISPLAY}, or task if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_TASK}. + * {The token of the layer of the hierarchy to record. + * If {@link #getContentToRecord()} is @link RecordContent#RECORD_CONTENT_DISPLAY}, then + * represents the WindowToken corresponding to the DisplayContent to record. + * If {@link #getContentToRecord()} is {@link RecordContent#RECORD_CONTENT_TASK}, then + * represents the {@link android.window.WindowContainerToken} of the Task to record. */ @DataClass.Generated.Member public @VisibleForTesting @Nullable IBinder getTokenToRecord() { @@ -231,10 +233,11 @@ public final class ContentRecordingSession implements Parcelable { } /** - * The window token of the layer of the hierarchy to record. - * The display content if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_DISPLAY}, or task if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_TASK}. + * {The token of the layer of the hierarchy to record. + * If {@link #getContentToRecord()} is @link RecordContent#RECORD_CONTENT_DISPLAY}, then + * represents the WindowToken corresponding to the DisplayContent to record. + * If {@link #getContentToRecord()} is {@link RecordContent#RECORD_CONTENT_TASK}, then + * represents the {@link android.window.WindowContainerToken} of the Task to record. */ @DataClass.Generated.Member public @NonNull ContentRecordingSession setTokenToRecord(@VisibleForTesting @NonNull IBinder value) { @@ -390,10 +393,11 @@ public final class ContentRecordingSession implements Parcelable { } /** - * The window token of the layer of the hierarchy to record. - * The display content if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_DISPLAY}, or task if {@link #getContentToRecord()} is - * {@link RecordContent#RECORD_CONTENT_TASK}. + * {The token of the layer of the hierarchy to record. + * If {@link #getContentToRecord()} is @link RecordContent#RECORD_CONTENT_DISPLAY}, then + * represents the WindowToken corresponding to the DisplayContent to record. + * If {@link #getContentToRecord()} is {@link RecordContent#RECORD_CONTENT_TASK}, then + * represents the {@link android.window.WindowContainerToken} of the Task to record. */ @DataClass.Generated.Member public @NonNull Builder setTokenToRecord(@VisibleForTesting @NonNull IBinder value) { @@ -433,7 +437,7 @@ public final class ContentRecordingSession implements Parcelable { } @DataClass.Generated( - time = 1644843382972L, + time = 1645803878639L, codegenVersion = "1.0.23", sourceFile = "frameworks/base/core/java/android/view/ContentRecordingSession.java", inputSignatures = "public static final int RECORD_CONTENT_DISPLAY\npublic static final int RECORD_CONTENT_TASK\nprivate int mDisplayId\nprivate @android.view.ContentRecordingSession.RecordContent int mContentToRecord\nprivate @com.android.internal.annotations.VisibleForTesting @android.annotation.Nullable android.os.IBinder mTokenToRecord\npublic static android.view.ContentRecordingSession createDisplaySession(android.os.IBinder)\npublic static android.view.ContentRecordingSession createTaskSession(android.os.IBinder)\npublic static boolean isValid(android.view.ContentRecordingSession)\npublic static boolean isSameDisplay(android.view.ContentRecordingSession,android.view.ContentRecordingSession)\nclass ContentRecordingSession extends java.lang.Object implements [android.os.Parcelable]\n@com.android.internal.util.DataClass(genConstructor=false, genToString=true, genSetters=true, genEqualsHashCode=true)") diff --git a/core/java/android/view/HandwritingInitiator.java b/core/java/android/view/HandwritingInitiator.java index 190adbdfd5db..61098d60566f 100644 --- a/core/java/android/view/HandwritingInitiator.java +++ b/core/java/android/view/HandwritingInitiator.java @@ -55,10 +55,10 @@ public class HandwritingInitiator { */ private final int mTouchSlop; /** - * The timeout used to distinguish tap from handwriting. If the stylus doesn't move before this - * timeout, it's not considered as handwriting. + * The timeout used to distinguish tap or long click from handwriting. If the stylus doesn't + * move before this timeout, it's not considered as handwriting. */ - private final long mTapTimeoutInMillis; + private final long mHandwritingTimeoutInMillis; private State mState = new State(); private final HandwritingAreaTracker mHandwritingAreasTracker = new HandwritingAreaTracker(); @@ -90,7 +90,7 @@ public class HandwritingInitiator { public HandwritingInitiator(@NonNull ViewConfiguration viewConfiguration, @NonNull InputMethodManager inputMethodManager) { mTouchSlop = viewConfiguration.getScaledTouchSlop(); - mTapTimeoutInMillis = ViewConfiguration.getTapTimeout(); + mHandwritingTimeoutInMillis = ViewConfiguration.getLongPressTimeout(); mImm = inputMethodManager; } @@ -145,7 +145,7 @@ public class HandwritingInitiator { final long timeElapsed = motionEvent.getEventTime() - mState.mStylusDownTimeInMillis; - if (timeElapsed > mTapTimeoutInMillis) { + if (timeElapsed > mHandwritingTimeoutInMillis) { reset(); return; } diff --git a/core/java/com/android/internal/jank/FrameTracker.java b/core/java/com/android/internal/jank/FrameTracker.java index 34c47ede99f0..06bc4b56901a 100644 --- a/core/java/com/android/internal/jank/FrameTracker.java +++ b/core/java/com/android/internal/jank/FrameTracker.java @@ -33,6 +33,7 @@ import android.annotation.Nullable; import android.graphics.HardwareRendererObserver; import android.os.Handler; import android.os.Trace; +import android.text.TextUtils; import android.util.Log; import android.util.SparseArray; import android.view.Choreographer; @@ -188,6 +189,7 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener if (mBeginVsyncId != INVALID_ID) { mSurfaceControlWrapper.addJankStatsListener( FrameTracker.this, mSurfaceControl); + markEvent("FT#deferMonitoring"); postTraceStartMarker(); } } @@ -241,8 +243,9 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener } if (mSurfaceControl != null) { if (mDeferMonitoring) { + markEvent("FT#deferMonitoring"); // Normal case, we begin the instrument from the very beginning, - // except the first frame. + // will exclude the first frame. postTraceStartMarker(); } else { // If we don't begin the instrument from the very beginning, @@ -272,6 +275,7 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener return; } mTracingStarted = true; + markEvent("FT#begin"); Trace.beginAsyncSection(mSession.getName(), (int) mBeginVsyncId); } } @@ -295,6 +299,7 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener Log.d(TAG, "end: " + mSession.getName() + ", end=" + mEndVsyncId + ", reason=" + reason); } + markEvent("FT#end#" + reason); Trace.endAsyncSection(mSession.getName(), (int) mBeginVsyncId); mSession.setReason(reason); @@ -322,6 +327,7 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener reason == REASON_CANCEL_NOT_BEGUN || reason == REASON_CANCEL_SAME_VSYNC; if (mCancelled || (mEndVsyncId != INVALID_ID && !cancelFromEnd)) return false; mCancelled = true; + markEvent("FT#cancel#" + reason); // We don't need to end the trace section if it never begun. if (mTracingStarted) { Trace.endAsyncSection(mSession.getName(), (int) mBeginVsyncId); @@ -343,6 +349,11 @@ public class FrameTracker extends SurfaceControl.OnJankDataListener } } + private void markEvent(String desc) { + Trace.beginSection(TextUtils.formatSimple("%s#%s", mSession.getName(), desc)); + Trace.endSection(); + } + private void notifyCujEvent(String action) { if (mListener == null) return; mListener.onCujEvents(mSession, action); diff --git a/core/java/com/android/internal/os/KernelAllocationStats.java b/core/java/com/android/internal/os/KernelAllocationStats.java index 1c3f8b0bf095..58d51e327ade 100644 --- a/core/java/com/android/internal/os/KernelAllocationStats.java +++ b/core/java/com/android/internal/os/KernelAllocationStats.java @@ -24,21 +24,29 @@ public final class KernelAllocationStats { /** Process dma-buf stats. */ public static final class ProcessDmabuf { + public final int uid; + public final String processName; + public final int oomScore; + /** Size of buffers retained by the process. */ public final int retainedSizeKb; /** Number of buffers retained by the process. */ public final int retainedBuffersCount; - /** Size of buffers mapped to the address space. */ - public final int mappedSizeKb; - /** Count of buffers mapped to the address space. */ - public final int mappedBuffersCount; + /** Size of buffers shared with Surface Flinger. */ + public final int surfaceFlingerSizeKb; + /** Count of buffers shared with Surface Flinger. */ + public final int surfaceFlingerCount; - ProcessDmabuf(int retainedSizeKb, int retainedBuffersCount, - int mappedSizeKb, int mappedBuffersCount) { + ProcessDmabuf(int uid, String processName, int oomScore, int retainedSizeKb, + int retainedBuffersCount, int surfaceFlingerSizeKb, + int surfaceFlingerCount) { + this.uid = uid; + this.processName = processName; + this.oomScore = oomScore; this.retainedSizeKb = retainedSizeKb; this.retainedBuffersCount = retainedBuffersCount; - this.mappedSizeKb = mappedSizeKb; - this.mappedBuffersCount = mappedBuffersCount; + this.surfaceFlingerSizeKb = surfaceFlingerSizeKb; + this.surfaceFlingerCount = surfaceFlingerCount; } } @@ -47,7 +55,7 @@ public final class KernelAllocationStats { * stats could not be read. */ @Nullable - public static native ProcessDmabuf getDmabufAllocations(int pid); + public static native ProcessDmabuf[] getDmabufAllocations(); /** Pid to gpu memory size. */ public static final class ProcessGpuMem { diff --git a/core/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java index cc7e9d95b4f8..e281853d31bf 100644 --- a/core/java/com/android/server/SystemConfig.java +++ b/core/java/com/android/server/SystemConfig.java @@ -34,6 +34,7 @@ import android.os.Trace; import android.os.incremental.IncrementalManager; import android.os.storage.StorageManager; import android.permission.PermissionManager.SplitPermissionInfo; +import android.sysprop.ApexProperties; import android.text.TextUtils; import android.util.ArrayMap; import android.util.ArraySet; @@ -1187,7 +1188,8 @@ public class SystemConfig { boolean systemExt = permFile.toPath().startsWith( Environment.getSystemExtDirectory().toPath() + "/"); boolean apex = permFile.toPath().startsWith( - Environment.getApexDirectory().toPath() + "/"); + Environment.getApexDirectory().toPath() + "/") + && ApexProperties.updatable().orElse(false); if (vendor) { readPrivAppPermissions(parser, mVendorPrivAppPermissions, mVendorPrivAppDenyPermissions); diff --git a/core/jni/Android.bp b/core/jni/Android.bp index 3a76745cc4d9..a1be88440c97 100644 --- a/core/jni/Android.bp +++ b/core/jni/Android.bp @@ -272,6 +272,7 @@ cc_library_shared { "libinput", "libcamera_client", "libcamera_metadata", + "libprocinfo", "libsqlite", "libEGL", "libGLESv1_CM", diff --git a/core/jni/com_android_internal_os_KernelAllocationStats.cpp b/core/jni/com_android_internal_os_KernelAllocationStats.cpp index e0a24430e739..5b104977f1d8 100644 --- a/core/jni/com_android_internal_os_KernelAllocationStats.cpp +++ b/core/jni/com_android_internal_os_KernelAllocationStats.cpp @@ -13,12 +13,19 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#include <android-base/logging.h> +#include <android-base/stringprintf.h> #include <dmabufinfo/dmabufinfo.h> #include <jni.h> #include <meminfo/sysmeminfo.h> +#include <procinfo/process.h> #include "core_jni_helpers.h" +using DmaBuffer = ::android::dmabufinfo::DmaBuffer; +using android::base::ReadFileToString; +using android::base::StringPrintf; + namespace { static jclass gProcessDmabufClazz; static jmethodID gProcessDmabufCtor; @@ -28,30 +35,127 @@ static jmethodID gProcessGpuMemCtor; namespace android { -static jobject KernelAllocationStats_getDmabufAllocations(JNIEnv *env, jobject, jint pid) { - std::vector<dmabufinfo::DmaBuffer> buffers; - if (!dmabufinfo::ReadDmaBufMapRefs(pid, &buffers)) { +struct PidDmaInfo { + uid_t uid; + std::string cmdline; + int oomScoreAdj; +}; + +static jobjectArray KernelAllocationStats_getDmabufAllocations(JNIEnv *env, jobject) { + std::vector<DmaBuffer> buffers; + + if (!dmabufinfo::ReadDmaBufs(&buffers)) { return nullptr; } - jint mappedSize = 0; - jint mappedCount = buffers.size(); - for (const auto &buffer : buffers) { - mappedSize += buffer.size(); + + // Create a reverse map from pid to dmabufs + // Store dmabuf inodes & sizes for later processing. + std::unordered_map<pid_t, std::set<ino_t>> pidToInodes; + std::unordered_map<ino_t, long> inodeToSize; + for (auto &buf : buffers) { + for (auto pid : buf.pids()) { + pidToInodes[pid].insert(buf.inode()); + } + inodeToSize[buf.inode()] = buf.size(); + } + + pid_t surfaceFlingerPid = -1; + // The set of all inodes that are being retained by SurfaceFlinger. Buffers + // shared between another process and SF will appear in this set. + std::set<ino_t> surfaceFlingerBufferInodes; + // The set of all inodes that are being retained by any process other + // than SurfaceFlinger. Buffers shared between another process and SF will + // appear in this set. + std::set<ino_t> otherProcessBufferInodes; + + // Find SurfaceFlinger pid & get cmdlines, oomScoreAdj, etc for each pid + // holding any DMA buffers. + std::unordered_map<pid_t, PidDmaInfo> pidDmaInfos; + for (const auto &pidToInodeEntry : pidToInodes) { + pid_t pid = pidToInodeEntry.first; + + android::procinfo::ProcessInfo processInfo; + if (!android::procinfo::GetProcessInfo(pid, &processInfo)) { + continue; + } + + std::string cmdline; + if (!ReadFileToString(StringPrintf("/proc/%d/cmdline", pid), &cmdline)) { + continue; + } + + // cmdline strings are null-delimited, so we split on \0 here + if (cmdline.substr(0, cmdline.find('\0')) == "/system/bin/surfaceflinger") { + if (surfaceFlingerPid == -1) { + surfaceFlingerPid = pid; + surfaceFlingerBufferInodes = pidToInodes[pid]; + } else { + LOG(ERROR) << "getDmabufAllocations found multiple SF processes; pid1: " << pid + << ", pid2:" << surfaceFlingerPid; + surfaceFlingerPid = -2; // Used as a sentinel value below + } + } else { + otherProcessBufferInodes.insert(pidToInodes[pid].begin(), pidToInodes[pid].end()); + } + + std::string oomScoreAdjStr; + if (!ReadFileToString(StringPrintf("/proc/%d/oom_score_adj", pid), &oomScoreAdjStr)) { + continue; + } + + pidDmaInfos[pid] = PidDmaInfo{.uid = processInfo.uid, + .cmdline = cmdline, + .oomScoreAdj = atoi(oomScoreAdjStr.c_str())}; + } + + if (surfaceFlingerPid < 0) { + LOG(ERROR) << "getDmabufAllocations could not identify SurfaceFlinger " + << "process via /proc/pid/cmdline"; } - mappedSize /= 1024; - - jint retainedSize = -1; - jint retainedCount = -1; - if (dmabufinfo::ReadDmaBufFdRefs(pid, &buffers)) { - retainedCount = buffers.size(); - retainedSize = 0; - for (const auto &buffer : buffers) { - retainedSize += buffer.size(); + + jobjectArray ret = env->NewObjectArray(pidDmaInfos.size(), gProcessDmabufClazz, NULL); + int retArrayIndex = 0; + for (const auto &pidDmaInfosEntry : pidDmaInfos) { + pid_t pid = pidDmaInfosEntry.first; + + // For all processes apart from SurfaceFlinger, this set will store the + // dmabuf inodes that are shared with SF. For SF, it will store the inodes + // that are shared with any other process. + std::set<ino_t> sharedBuffers; + if (pid == surfaceFlingerPid) { + set_intersection(surfaceFlingerBufferInodes.begin(), surfaceFlingerBufferInodes.end(), + otherProcessBufferInodes.begin(), otherProcessBufferInodes.end(), + std::inserter(sharedBuffers, sharedBuffers.end())); + } else if (surfaceFlingerPid > 0) { + set_intersection(pidToInodes[pid].begin(), pidToInodes[pid].end(), + surfaceFlingerBufferInodes.begin(), surfaceFlingerBufferInodes.end(), + std::inserter(sharedBuffers, sharedBuffers.begin())); + } // If surfaceFlingerPid < 0; it means we failed to identify it, and + // the SF-related fields below should be left empty. + + long totalSize = 0; + long sharedBuffersSize = 0; + for (const auto &inode : pidToInodes[pid]) { + totalSize += inodeToSize[inode]; + if (sharedBuffers.count(inode)) { + sharedBuffersSize += inodeToSize[inode]; + } } - retainedSize /= 1024; + + jobject obj = env->NewObject(gProcessDmabufClazz, gProcessDmabufCtor, + /* uid */ pidDmaInfos[pid].uid, + /* process name */ + env->NewStringUTF(pidDmaInfos[pid].cmdline.c_str()), + /* oomscore */ pidDmaInfos[pid].oomScoreAdj, + /* retainedSize */ totalSize / 1024, + /* retainedCount */ pidToInodes[pid].size(), + /* sharedWithSurfaceFlinger size */ sharedBuffersSize / 1024, + /* sharedWithSurfaceFlinger count */ sharedBuffers.size()); + + env->SetObjectArrayElement(ret, retArrayIndex++, obj); } - return env->NewObject(gProcessDmabufClazz, gProcessDmabufCtor, retainedSize, retainedCount, - mappedSize, mappedCount); + + return ret; } static jobject KernelAllocationStats_getGpuAllocations(JNIEnv *env) { @@ -74,7 +178,7 @@ static jobject KernelAllocationStats_getGpuAllocations(JNIEnv *env) { } static const JNINativeMethod methods[] = { - {"getDmabufAllocations", "(I)Lcom/android/internal/os/KernelAllocationStats$ProcessDmabuf;", + {"getDmabufAllocations", "()[Lcom/android/internal/os/KernelAllocationStats$ProcessDmabuf;", (void *)KernelAllocationStats_getDmabufAllocations}, {"getGpuAllocations", "()[Lcom/android/internal/os/KernelAllocationStats$ProcessGpuMem;", (void *)KernelAllocationStats_getGpuAllocations}, @@ -86,7 +190,8 @@ int register_com_android_internal_os_KernelAllocationStats(JNIEnv *env) { jclass clazz = FindClassOrDie(env, "com/android/internal/os/KernelAllocationStats$ProcessDmabuf"); gProcessDmabufClazz = MakeGlobalRefOrDie(env, clazz); - gProcessDmabufCtor = GetMethodIDOrDie(env, gProcessDmabufClazz, "<init>", "(IIII)V"); + gProcessDmabufCtor = + GetMethodIDOrDie(env, gProcessDmabufClazz, "<init>", "(ILjava/lang/String;IIIII)V"); clazz = FindClassOrDie(env, "com/android/internal/os/KernelAllocationStats$ProcessGpuMem"); gProcessGpuMemClazz = MakeGlobalRefOrDie(env, clazz); @@ -94,4 +199,4 @@ int register_com_android_internal_os_KernelAllocationStats(JNIEnv *env) { return res; } -} // namespace android +} // namespace android
\ No newline at end of file diff --git a/core/proto/android/os/appbatterystats.proto b/core/proto/android/os/appbatterystats.proto new file mode 100644 index 000000000000..8769ebb74979 --- /dev/null +++ b/core/proto/android/os/appbatterystats.proto @@ -0,0 +1,47 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +syntax = "proto2"; +package android.os; + +option java_multiple_files = true; + +message AppBatteryStatsProto { + message UidStats { + optional int32 uid = 1; + + message ProcessStateStats { + enum ProcessState { + UNSPECIFIED = 0; + FOREGROUND = 1; + BACKGROUND = 2; + FOREGROUND_SERVICE = 3; + CACHED = 4; + } + + optional ProcessState process_state = 1; + + // Time spent in this state in the past 24 hours + optional int64 duration_ms = 2; + // Estimated power consumed in this state in the past 24 hours + optional double power_mah = 3; + } + + repeated ProcessStateStats process_state_stats = 2; + } + + repeated UidStats uid_stats = 1; +} diff --git a/core/res/AndroidManifest.xml b/core/res/AndroidManifest.xml index d652b2ff4f4a..0be578addda8 100644 --- a/core/res/AndroidManifest.xml +++ b/core/res/AndroidManifest.xml @@ -724,6 +724,7 @@ <protected-broadcast android:name="android.intent.action.SHOW_FOREGROUND_SERVICE_MANAGER" /> <protected-broadcast android:name="android.service.autofill.action.DELAYED_FILL" /> <protected-broadcast android:name="android.app.action.PROVISIONING_COMPLETED" /> + <protected-broadcast android:name="android.app.action.LOST_MODE_LOCATION_UPDATE" /> <!-- ====================================================================== --> <!-- RUNTIME PERMISSIONS --> diff --git a/core/tests/coretests/src/android/net/SntpClientTest.java b/core/tests/coretests/src/android/net/SntpClientTest.java index ba7df1e218d9..267fc2b636d6 100644 --- a/core/tests/coretests/src/android/net/SntpClientTest.java +++ b/core/tests/coretests/src/android/net/SntpClientTest.java @@ -295,7 +295,8 @@ public class SntpClientTest { @Test public void testDnsResolutionFailure() throws Exception { - assertFalse(mClient.requestTime("ntp.server.doesnotexist.example", 5000, mNetwork)); + assertFalse(mClient.requestTime("ntp.server.doesnotexist.example", + SntpClient.STANDARD_NTP_PORT, 5000, mNetwork)); } @Test diff --git a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java index 1ae9649dfe06..e303934c4aad 100644 --- a/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java +++ b/core/tests/coretests/src/android/view/stylus/HandwritingInitiatorTest.java @@ -60,7 +60,7 @@ import org.junit.runner.RunWith; @RunWith(AndroidJUnit4.class) public class HandwritingInitiatorTest { private static final int TOUCH_SLOP = 8; - private static final long TAP_TIMEOUT = ViewConfiguration.getTapTimeout(); + private static final long TIMEOUT = ViewConfiguration.getLongPressTimeout(); private static final Rect sHwArea = new Rect(100, 200, 500, 500); private HandwritingInitiator mHandwritingInitiator; @@ -177,7 +177,7 @@ public class HandwritingInitiatorTest { } @Test - public void onTouchEvent_notStartHandwriting_when_stylusMove_afterTapTimeOut() { + public void onTouchEvent_notStartHandwriting_when_stylusMove_afterTimeOut() { mHandwritingInitiator.onInputConnectionCreated(mTestView); final int x1 = 10; final int y1 = 10; @@ -187,7 +187,7 @@ public class HandwritingInitiatorTest { final int x2 = x1 + TOUCH_SLOP * 2; final int y2 = y1; - final long time2 = time1 + TAP_TIMEOUT + 10L; + final long time2 = time1 + TIMEOUT + 10L; MotionEvent stylusEvent2 = createStylusEvent(ACTION_MOVE, x2, y2, time2); mHandwritingInitiator.onTouchEvent(stylusEvent2); diff --git a/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java b/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java index ec45a016507a..625f52a87ecf 100644 --- a/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java +++ b/core/tests/coretests/src/com/android/internal/os/LooperStatsTest.java @@ -232,7 +232,7 @@ public final class LooperStatsTest { assertThat(entry3.handlerClassName).isEqualTo( "com.android.internal.os.LooperStatsTest$TestHandlerSecond"); assertThat(entry3.messageName).startsWith( - "com.android.internal.os.LooperStatsTest$$ExternalSyntheticLambda5"); + "com.android.internal.os.LooperStatsTest$$ExternalSyntheticLambda"); assertThat(entry3.messageCount).isEqualTo(1); assertThat(entry3.recordedMessageCount).isEqualTo(1); assertThat(entry3.exceptionCount).isEqualTo(0); diff --git a/core/tests/mockingcoretests/src/android/util/TimingsTraceLogTest.java b/core/tests/mockingcoretests/src/android/util/TimingsTraceLogTest.java index 5dc44d21c6b7..8de919681006 100644 --- a/core/tests/mockingcoretests/src/android/util/TimingsTraceLogTest.java +++ b/core/tests/mockingcoretests/src/android/util/TimingsTraceLogTest.java @@ -123,7 +123,7 @@ public class TimingsTraceLogTest { public void testLogDuration() throws Exception { TimingsTraceLog log = new TimingsTraceLog(TAG, TRACE_TAG_APP, 10); log.logDuration("logro", 42); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), contains("logro took to complete: 42ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), contains("logro took to complete: 42ms"))); } @Test @@ -134,7 +134,7 @@ public class TimingsTraceLogTest { verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "test")); verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP)); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("test took to complete: \\dms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("test took to complete: \\dms"))); } @Test @@ -149,8 +149,8 @@ public class TimingsTraceLogTest { verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "L2")); verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP), times(2)); // L1 and L2 - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("L2 took to complete: \\d+ms"))); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("L1 took to complete: \\d+ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L2 took to complete: \\d+ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L1 took to complete: \\d+ms"))); } @Test @@ -170,9 +170,9 @@ public class TimingsTraceLogTest { verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "L3")); verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP), times(3)); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("L2 took to complete: \\d+ms"))); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("L1 took to complete: \\d+ms"))); - verify((MockedVoidMethod) () -> Slog.d(eq(TAG), matches("L3 took to complete: \\d+ms")), + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L2 took to complete: \\d+ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L1 took to complete: \\d+ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L3 took to complete: \\d+ms")), never()); verify((MockedVoidMethod) () -> Slog.w(TAG, "not tracing duration of 'L3' " diff --git a/data/etc/services.core.protolog.json b/data/etc/services.core.protolog.json index e898f570a6b8..4449c48d28bb 100644 --- a/data/etc/services.core.protolog.json +++ b/data/etc/services.core.protolog.json @@ -2257,6 +2257,12 @@ "group": "WM_DEBUG_WINDOW_TRANSITIONS", "at": "com\/android\/server\/wm\/TransitionController.java" }, + "264036181": { + "message": "Unable to retrieve task to start recording for display %d", + "level": "VERBOSE", + "group": "WM_DEBUG_CONTENT_RECORDING", + "at": "com\/android\/server\/wm\/ContentRecorder.java" + }, "269576220": { "message": "Resuming rotation after drag", "level": "DEBUG", @@ -2761,6 +2767,12 @@ "group": "WM_DEBUG_WALLPAPER", "at": "com\/android\/server\/wm\/WallpaperWindowToken.java" }, + "736003885": { + "message": "Unable to retrieve the task token to start recording for display %d", + "level": "VERBOSE", + "group": "WM_DEBUG_CONTENT_RECORDING", + "at": "com\/android\/server\/wm\/ContentRecorder.java" + }, "736692676": { "message": "Config is relaunching %s", "level": "VERBOSE", @@ -2791,6 +2803,12 @@ "group": "WM_DEBUG_RECENTS_ANIMATIONS", "at": "com\/android\/server\/wm\/RecentsAnimation.java" }, + "778774915": { + "message": "Unable to record task since feature is disabled %d", + "level": "VERBOSE", + "group": "WM_DEBUG_CONTENT_RECORDING", + "at": "com\/android\/server\/wm\/ContentRecorder.java" + }, "781471998": { "message": "moveWindowTokenToDisplay: Cannot move to the original display for token: %s", "level": "WARN", diff --git a/graphics/java/android/graphics/Typeface.java b/graphics/java/android/graphics/Typeface.java index 61f7facf0916..a2f5301e353f 100644 --- a/graphics/java/android/graphics/Typeface.java +++ b/graphics/java/android/graphics/Typeface.java @@ -329,7 +329,7 @@ public class Typeface { FontFamily.Builder familyBuilder = null; for (final FontFileResourceEntry fontFile : filesEntry.getEntries()) { final Font.Builder fontBuilder = new Font.Builder(mgr, fontFile.getFileName(), - false /* isAsset */, 0 /* cookie */) + false /* isAsset */, AssetManager.COOKIE_UNKNOWN) .setTtcIndex(fontFile.getTtcIndex()) .setFontVariationSettings(fontFile.getVariationSettings()); if (fontFile.getWeight() != Typeface.RESOLVE_BY_FONT_TABLE) { diff --git a/graphics/java/android/graphics/fonts/Font.java b/graphics/java/android/graphics/fonts/Font.java index cd7936d50dff..abd0be9c2872 100644 --- a/graphics/java/android/graphics/fonts/Font.java +++ b/graphics/java/android/graphics/fonts/Font.java @@ -179,7 +179,7 @@ public final class Font { */ public Builder(@NonNull AssetManager am, @NonNull String path) { try { - mBuffer = createBuffer(am, path, true /* is asset */, 0 /* cookie */); + mBuffer = createBuffer(am, path, true /* is asset */, AssetManager.COOKIE_UNKNOWN); } catch (IOException e) { mException = e; } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java index be713a59a816..e5a755c35add 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/pip/PipTransition.java @@ -166,8 +166,7 @@ public class PipTransition extends PipTransitionController { mExitTransition = null; mHasFadeOut = false; if (mFinishCallback != null) { - mFinishCallback.onTransitionFinished(null, null); - mFinishCallback = null; + callFinishCallback(null /* wct */); mFinishTransaction = null; throw new RuntimeException("Previous callback not called, aborting exit PIP."); } @@ -232,6 +231,11 @@ public class PipTransition extends PipTransitionController { return false; } + /** Helper to identify whether this handler is currently the one playing an animation */ + private boolean isAnimatingLocally() { + return mFinishTransaction != null; + } + @Nullable @Override public WindowContainerTransaction handleRequest(@NonNull IBinder transition, @@ -282,9 +286,11 @@ public class PipTransition extends PipTransitionController { if (enteringPip) { mPipTransitionState.setTransitionState(ENTERED_PIP); } - // If there is an expected exit transition, then the exit will be "merged" into this - // transition so don't fire the finish-callback in that case. - if (mExitTransition == null && mFinishCallback != null) { + // If we have an exit transition, but aren't playing a transition locally, it + // means we're expecting the exit transition will be "merged" into another transition + // (likely a remote like launcher), so don't fire the finish-callback here -- wait until + // the exit transition is merged. + if ((mExitTransition == null || isAnimatingLocally()) && mFinishCallback != null) { WindowContainerTransaction wct = new WindowContainerTransaction(); prepareFinishResizeTransaction(taskInfo, destinationBounds, direction, wct); @@ -305,12 +311,19 @@ public class PipTransition extends PipTransitionController { mSurfaceTransactionHelper.crop(mFinishTransaction, leash, finishBounds); } mFinishTransaction = null; - mFinishCallback.onTransitionFinished(wct, null /* callback */); - mFinishCallback = null; + callFinishCallback(wct); } finishResizeForMenu(destinationBounds); } + private void callFinishCallback(WindowContainerTransaction wct) { + // Need to unset mFinishCallback first because onTransitionFinished can re-enter this + // handler if there is a pending PiP animation. + final Transitions.TransitionFinishCallback finishCallback = mFinishCallback; + mFinishCallback = null; + finishCallback.onTransitionFinished(wct, null /* callback */); + } + @Override public void forceFinishTransition() { if (mFinishCallback == null) return; @@ -572,8 +585,7 @@ public class PipTransition extends PipTransitionController { mHasFadeOut = false; if (mFinishCallback != null) { - mFinishCallback.onTransitionFinished(null /* wct */, null /* callback */); - mFinishCallback = null; + callFinishCallback(null /* wct */); mFinishTransaction = null; throw new RuntimeException("Previous callback not called, aborting entering PIP."); } diff --git a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java index 177b4a8b5982..2da5becae8f5 100644 --- a/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java +++ b/libs/WindowManager/Shell/src/com/android/wm/shell/splitscreen/SplitScreenController.java @@ -18,6 +18,7 @@ package com.android.wm.shell.splitscreen; import static android.app.ActivityManager.START_SUCCESS; import static android.app.ActivityManager.START_TASK_TO_FRONT; +import static android.content.Intent.FLAG_ACTIVITY_NO_USER_ACTION; import static android.view.Display.DEFAULT_DISPLAY; import static android.view.RemoteAnimationTarget.MODE_OPENING; @@ -325,8 +326,8 @@ public class SplitScreenController implements DragAndDropPolicy.Starter, } } - public void startIntent(PendingIntent intent, Intent fillInIntent, @SplitPosition int position, - @Nullable Bundle options) { + public void startIntent(PendingIntent intent, @Nullable Intent fillInIntent, + @SplitPosition int position, @Nullable Bundle options) { if (!ENABLE_SHELL_TRANSITIONS) { startIntentLegacy(intent, fillInIntent, position, options); return; @@ -335,6 +336,15 @@ public class SplitScreenController implements DragAndDropPolicy.Starter, try { options = mStageCoordinator.resolveStartStage(STAGE_TYPE_UNDEFINED, position, options, null /* wct */); + + // Flag this as a no-user-action launch to prevent sending user leaving event to the + // current top activity since it's going to be put into another side of the split. This + // prevents the current top activity from going into pip mode due to user leaving event. + if (fillInIntent == null) { + fillInIntent = new Intent(); + } + fillInIntent.addFlags(FLAG_ACTIVITY_NO_USER_ACTION); + intent.send(mContext, 0, fillInIntent, null /* onFinished */, null /* handler */, null /* requiredPermission */, options); } catch (PendingIntent.CanceledException e) { @@ -342,7 +352,7 @@ public class SplitScreenController implements DragAndDropPolicy.Starter, } } - private void startIntentLegacy(PendingIntent intent, Intent fillInIntent, + private void startIntentLegacy(PendingIntent intent, @Nullable Intent fillInIntent, @SplitPosition int position, @Nullable Bundle options) { final WindowContainerTransaction evictWct = new WindowContainerTransaction(); mStageCoordinator.prepareEvictChildTasks(position, evictWct); @@ -393,6 +403,15 @@ public class SplitScreenController implements DragAndDropPolicy.Starter, final WindowContainerTransaction wct = new WindowContainerTransaction(); options = mStageCoordinator.resolveStartStage(STAGE_TYPE_UNDEFINED, position, options, wct); + + // Flag this as a no-user-action launch to prevent sending user leaving event to the current + // top activity since it's going to be put into another side of the split. This prevents the + // current top activity from going into pip mode due to user leaving event. + if (fillInIntent == null) { + fillInIntent = new Intent(); + } + fillInIntent.addFlags(FLAG_ACTIVITY_NO_USER_ACTION); + wct.sendPendingIntent(intent, fillInIntent, options); mSyncQueue.queue(transition, WindowManager.TRANSIT_OPEN, wct); } diff --git a/libs/hwui/HardwareBitmapUploader.cpp b/libs/hwui/HardwareBitmapUploader.cpp index dd272cd5ff7d..c24cabb287de 100644 --- a/libs/hwui/HardwareBitmapUploader.cpp +++ b/libs/hwui/HardwareBitmapUploader.cpp @@ -310,6 +310,11 @@ bool HardwareBitmapUploader::has1010102Support() { return has101012Support; } +bool HardwareBitmapUploader::hasAlpha8Support() { + static bool hasAlpha8Support = checkSupport(AHARDWAREBUFFER_FORMAT_R8_UNORM); + return hasAlpha8Support; +} + static FormatInfo determineFormat(const SkBitmap& skBitmap, bool usingGL) { FormatInfo formatInfo; switch (skBitmap.info().colorType()) { @@ -363,6 +368,13 @@ static FormatInfo determineFormat(const SkBitmap& skBitmap, bool usingGL) { } formatInfo.format = GL_RGBA; break; + case kAlpha_8_SkColorType: + formatInfo.isSupported = HardwareBitmapUploader::hasAlpha8Support(); + formatInfo.bufferFormat = AHARDWAREBUFFER_FORMAT_R8_UNORM; + formatInfo.format = GL_R8; + formatInfo.type = GL_UNSIGNED_BYTE; + formatInfo.vkFormat = VK_FORMAT_R8_UNORM; + break; default: ALOGW("unable to create hardware bitmap of colortype: %d", skBitmap.info().colorType()); formatInfo.valid = false; diff --git a/libs/hwui/HardwareBitmapUploader.h b/libs/hwui/HardwareBitmapUploader.h index 34f43cd8a198..81057a24c29c 100644 --- a/libs/hwui/HardwareBitmapUploader.h +++ b/libs/hwui/HardwareBitmapUploader.h @@ -30,11 +30,13 @@ public: #ifdef __ANDROID__ static bool hasFP16Support(); static bool has1010102Support(); + static bool hasAlpha8Support(); #else static bool hasFP16Support() { return true; } static bool has1010102Support() { return true; } + static bool hasAlpha8Support() { return true; } #endif }; diff --git a/libs/hwui/hwui/Bitmap.cpp b/libs/hwui/hwui/Bitmap.cpp index 1a89cfd5d0ad..67f47580a70f 100644 --- a/libs/hwui/hwui/Bitmap.cpp +++ b/libs/hwui/hwui/Bitmap.cpp @@ -104,6 +104,10 @@ sk_sp<Bitmap> Bitmap::allocateAshmemBitmap(size_t size, const SkImageInfo& info, sk_sp<Bitmap> Bitmap::allocateHardwareBitmap(const SkBitmap& bitmap) { #ifdef __ANDROID__ // Layoutlib does not support hardware acceleration + if (bitmap.colorType() == kAlpha_8_SkColorType && + !uirenderer::HardwareBitmapUploader::hasAlpha8Support()) { + return nullptr; + } return uirenderer::HardwareBitmapUploader::allocateHardwareBitmap(bitmap); #else return Bitmap::allocateHeapBitmap(bitmap.info()); diff --git a/location/java/android/location/GnssExcessPathInfo.java b/location/java/android/location/GnssExcessPathInfo.java new file mode 100644 index 000000000000..72b2374bad8f --- /dev/null +++ b/location/java/android/location/GnssExcessPathInfo.java @@ -0,0 +1,375 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.location; + +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.ExcessPathInfo.EXCESS_PATH_INFO_HAS_ATTENUATION; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.ExcessPathInfo.EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.ExcessPathInfo.EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH_UNC; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.ExcessPathInfo.EXCESS_PATH_INFO_HAS_REFLECTING_PLANE; + +import android.annotation.FloatRange; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.SystemApi; +import android.os.Parcel; +import android.os.Parcelable; + +import com.android.internal.util.Preconditions; + +import java.util.Objects; + +/** + * Contains the info of an excess path signal caused by reflection + * + * @hide + */ +@SystemApi +public final class GnssExcessPathInfo implements Parcelable { + + private static final int HAS_EXCESS_PATH_LENGTH_MASK = EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH; + private static final int HAS_EXCESS_PATH_LENGTH_UNC_MASK = + EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH_UNC; + private static final int HAS_REFLECTING_PLANE_MASK = EXCESS_PATH_INFO_HAS_REFLECTING_PLANE; + private static final int HAS_ATTENUATION_MASK = EXCESS_PATH_INFO_HAS_ATTENUATION; + + /* A bitmask of fields present in this object (see HAS_* constants defined above) */ + private final int mFlags; + private final float mExcessPathLengthMeters; + private final float mExcessPathLengthUncertaintyMeters; + @Nullable + private final GnssReflectingPlane mReflectingPlane; + private final float mAttenuationDb; + + private GnssExcessPathInfo( + int flags, + float excessPathLengthMeters, + float excessPathLengthUncertaintyMeters, + @Nullable GnssReflectingPlane reflectingPlane, + float attenuationDb) { + mFlags = flags; + mExcessPathLengthMeters = excessPathLengthMeters; + mExcessPathLengthUncertaintyMeters = excessPathLengthUncertaintyMeters; + mReflectingPlane = reflectingPlane; + mAttenuationDb = attenuationDb; + } + + /** + * Gets a bitmask of fields present in this object. + * + * <p>This API exists for JNI since it is easier for JNI to get one integer flag than looking up + * several has* methods. + * @hide + */ + public int getFlags() { + return mFlags; + } + + /** Returns {@code true} if {@link #getExcessPathLengthMeters()} is valid. */ + public boolean hasExcessPathLength() { + return (mFlags & HAS_EXCESS_PATH_LENGTH_MASK) != 0; + } + + /** + * Returns the excess path length to be subtracted from pseudorange before using it in + * calculating location. + * + * <p>{@link #hasExcessPathLength()} must be true when calling this method. Otherwise, an + * {@link UnsupportedOperationException} will be thrown. + */ + @FloatRange(from = 0.0f) + public float getExcessPathLengthMeters() { + if (!hasExcessPathLength()) { + throw new UnsupportedOperationException( + "getExcessPathLengthMeters() is not supported when hasExcessPathLength() is " + + "false"); + } + return mExcessPathLengthMeters; + } + + /** Returns {@code true} if {@link #getExcessPathLengthUncertaintyMeters()} is valid. */ + public boolean hasExcessPathLengthUncertainty() { + return (mFlags & HAS_EXCESS_PATH_LENGTH_UNC_MASK) != 0; + } + + /** + * Returns the error estimate (1-sigma) for the excess path length estimate. + * + * <p>{@link #hasExcessPathLengthUncertainty()} must be true when calling this method. + * Otherwise, an {@link UnsupportedOperationException} will be thrown. + */ + @FloatRange(from = 0.0f) + public float getExcessPathLengthUncertaintyMeters() { + if (!hasExcessPathLengthUncertainty()) { + throw new UnsupportedOperationException( + "getExcessPathLengthUncertaintyMeters() is not supported when " + + "hasExcessPathLengthUncertainty() is false"); + } + return mExcessPathLengthUncertaintyMeters; + } + + /** + * Returns {@code true} if {@link #getReflectingPlane()} is valid. + * + * <p>Returns false if the satellite signal goes through multiple reflections or if reflection + * plane serving is not supported. + */ + public boolean hasReflectingPlane() { + return (mFlags & HAS_REFLECTING_PLANE_MASK) != 0; + } + + /** + * Returns the reflecting plane characteristics at which the signal has bounced. + * + * <p>{@link #hasReflectingPlane()} must be true when calling this method. Otherwise, an + * {@link UnsupportedOperationException} will be thrown. + */ + @NonNull + public GnssReflectingPlane getReflectingPlane() { + if (!hasReflectingPlane()) { + throw new UnsupportedOperationException( + "getReflectingPlane() is not supported when hasReflectingPlane() is false"); + } + return mReflectingPlane; + } + + /** Returns {@code true} if {@link #getAttenuationDb()} is valid. */ + public boolean hasAttenuation() { + return (mFlags & HAS_ATTENUATION_MASK) != 0; + } + + /** + * Returns the expected reduction of signal strength of this path in non-negative dB. + * + * <p>{@link #hasAttenuation()} must be true when calling this method. Otherwise, an + * {@link UnsupportedOperationException} will be thrown. + */ + @FloatRange(from = 0.0f) + public float getAttenuationDb() { + if (!hasAttenuation()) { + throw new UnsupportedOperationException( + "getAttenuationDb() is not supported when hasAttenuation() is false"); + } + return mAttenuationDb; + } + + @Override + public int describeContents() { + return 0; + } + + @Override + public void writeToParcel(@NonNull Parcel parcel, int parcelFlags) { + parcel.writeInt(mFlags); + if (hasExcessPathLength()) { + parcel.writeFloat(mExcessPathLengthMeters); + } + if (hasExcessPathLengthUncertainty()) { + parcel.writeFloat(mExcessPathLengthUncertaintyMeters); + } + if (hasReflectingPlane()) { + mReflectingPlane.writeToParcel(parcel, parcelFlags); + } + if (hasAttenuation()) { + parcel.writeFloat(mAttenuationDb); + } + } + + public static final @NonNull Creator<GnssExcessPathInfo> CREATOR = + new Creator<GnssExcessPathInfo>() { + @Override + @NonNull + public GnssExcessPathInfo createFromParcel(@NonNull Parcel parcel) { + int flags = parcel.readInt(); + float excessPathLengthMeters = + (flags & HAS_EXCESS_PATH_LENGTH_MASK) != 0 + ? parcel.readFloat() : 0; + float excessPathLengthUncertaintyMeters = + (flags & HAS_EXCESS_PATH_LENGTH_UNC_MASK) != 0 + ? parcel.readFloat() : 0; + GnssReflectingPlane reflectingPlane = + (flags & HAS_REFLECTING_PLANE_MASK) != 0 + ? GnssReflectingPlane.CREATOR.createFromParcel(parcel) : null; + float attenuationDb = + (flags & HAS_ATTENUATION_MASK) != 0 + ? parcel.readFloat() : 0; + return new GnssExcessPathInfo(flags, excessPathLengthMeters, + excessPathLengthUncertaintyMeters, reflectingPlane, attenuationDb); + } + + @Override + public GnssExcessPathInfo[] newArray(int i) { + return new GnssExcessPathInfo[i]; + } + }; + + @Override + public boolean equals(Object obj) { + if (obj instanceof GnssExcessPathInfo) { + GnssExcessPathInfo that = (GnssExcessPathInfo) obj; + return this.mFlags == that.mFlags + && (!hasExcessPathLength() || Float.compare(this.mExcessPathLengthMeters, + that.mExcessPathLengthMeters) == 0) + && (!hasExcessPathLengthUncertainty() || Float.compare( + this.mExcessPathLengthUncertaintyMeters, + that.mExcessPathLengthUncertaintyMeters) == 0) + && (!hasReflectingPlane() || Objects.equals(this.mReflectingPlane, + that.mReflectingPlane)) + && (!hasAttenuation() || Float.compare(this.mAttenuationDb, + that.mAttenuationDb) == 0); + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(mFlags, + mExcessPathLengthMeters, + mExcessPathLengthUncertaintyMeters, + mReflectingPlane, + mAttenuationDb); + } + + @NonNull + @Override + public String toString() { + StringBuilder builder = new StringBuilder("GnssExcessPathInfo["); + if (hasExcessPathLength()) { + builder.append(" ExcessPathLengthMeters=").append(mExcessPathLengthMeters); + } + if (hasExcessPathLengthUncertainty()) { + builder.append(" ExcessPathLengthUncertaintyMeters=").append( + mExcessPathLengthUncertaintyMeters); + } + if (hasReflectingPlane()) { + builder.append(" ReflectingPlane=").append(mReflectingPlane); + } + if (hasAttenuation()) { + builder.append(" AttenuationDb=").append(mAttenuationDb); + } + builder.append(']'); + return builder.toString(); + } + + /** Builder for {@link GnssExcessPathInfo}. */ + public static final class Builder { + private int mFlags; + private float mExcessPathLengthMeters; + private float mExcessPathLengthUncertaintyMeters; + @Nullable + private GnssReflectingPlane mReflectingPlane; + private float mAttenuationDb; + + /** Constructor for {@link Builder}. */ + public Builder() {} + + /** + * Sets the excess path length to be subtracted from pseudorange before using it in + * calculating location. + */ + @NonNull + public Builder setExcessPathLengthMeters( + @FloatRange(from = 0.0f) float excessPathLengthMeters) { + Preconditions.checkArgumentInRange(excessPathLengthMeters, 0, Float.MAX_VALUE, + "excessPathLengthMeters"); + mExcessPathLengthMeters = excessPathLengthMeters; + mFlags |= HAS_EXCESS_PATH_LENGTH_MASK; + return this; + } + + /** + * Clears the excess path length. + * + * <p>This is to negate {@link #setExcessPathLengthMeters} call. + */ + @NonNull + public Builder clearExcessPathLengthMeters() { + mExcessPathLengthMeters = 0; + mFlags &= ~HAS_EXCESS_PATH_LENGTH_MASK; + return this; + } + + /** Sets the error estimate (1-sigma) for the excess path length estimate */ + @NonNull + public Builder setExcessPathLengthUncertaintyMeters( + @FloatRange(from = 0.0f) float excessPathLengthUncertaintyMeters) { + Preconditions.checkArgumentInRange(excessPathLengthUncertaintyMeters, 0, + Float.MAX_VALUE, "excessPathLengthUncertaintyMeters"); + mExcessPathLengthUncertaintyMeters = excessPathLengthUncertaintyMeters; + mFlags |= HAS_EXCESS_PATH_LENGTH_UNC_MASK; + return this; + } + + /** + * Clears the error estimate (1-sigma) for the excess path length estimate + * + * <p>This is to negate {@link #setExcessPathLengthUncertaintyMeters} call. + */ + @NonNull + public Builder clearExcessPathLengthUncertaintyMeters() { + mExcessPathLengthUncertaintyMeters = 0; + mFlags &= ~HAS_EXCESS_PATH_LENGTH_UNC_MASK; + return this; + } + + /** Sets the reflecting plane information */ + @NonNull + public Builder setReflectingPlane(@Nullable GnssReflectingPlane reflectingPlane) { + mReflectingPlane = reflectingPlane; + if (reflectingPlane != null) { + mFlags |= HAS_REFLECTING_PLANE_MASK; + } else { + mFlags &= ~HAS_REFLECTING_PLANE_MASK; + } + return this; + } + + /** + * Sets the attenuation value in dB. + */ + @NonNull + public Builder setAttenuationDb(@FloatRange(from = 0.0f) float attenuationDb) { + Preconditions.checkArgumentInRange(attenuationDb, 0, Float.MAX_VALUE, + "attenuationDb"); + mAttenuationDb = attenuationDb; + mFlags |= HAS_ATTENUATION_MASK; + return this; + } + + /** + * Clears the attenuation value in dB. + * + * <p>This is to negate {@link #setAttenuationDb(float)} call. + */ + @NonNull + public Builder clearAttenuationDb() { + mAttenuationDb = 0; + mFlags &= ~HAS_ATTENUATION_MASK; + return this; + } + + /** Builds a {@link GnssExcessPathInfo} instance as specified by this builder. */ + @NonNull + public GnssExcessPathInfo build() { + return new GnssExcessPathInfo( + mFlags, + mExcessPathLengthMeters, + mExcessPathLengthUncertaintyMeters, + mReflectingPlane, + mAttenuationDb); + } + } +} diff --git a/location/java/android/location/GnssReflectingPlane.java b/location/java/android/location/GnssReflectingPlane.java index 1acdd1ecce0b..115cbec5e4de 100644 --- a/location/java/android/location/GnssReflectingPlane.java +++ b/location/java/android/location/GnssReflectingPlane.java @@ -22,9 +22,14 @@ import android.annotation.SystemApi; import android.os.Parcel; import android.os.Parcelable; +import java.util.Objects; + /** * Holds the characteristics of the reflecting plane that a satellite signal has bounced from. * + * <p>Starting with Android T, this class supports {@link #equals} and {@link #hashCode}, which + * are not supported before that. + * * @hide */ @SystemApi @@ -107,24 +112,41 @@ public final class GnssReflectingPlane implements Parcelable { } }; + @Override + public void writeToParcel(@NonNull Parcel parcel, int flags) { + parcel.writeDouble(mLatitudeDegrees); + parcel.writeDouble(mLongitudeDegrees); + parcel.writeDouble(mAltitudeMeters); + parcel.writeDouble(mAzimuthDegrees); + } + @NonNull @Override public String toString() { - final String format = " %-29s = %s\n"; - StringBuilder builder = new StringBuilder("ReflectingPlane:\n"); - builder.append(String.format(format, "LatitudeDegrees = ", mLatitudeDegrees)); - builder.append(String.format(format, "LongitudeDegrees = ", mLongitudeDegrees)); - builder.append(String.format(format, "AltitudeMeters = ", mAltitudeMeters)); - builder.append(String.format(format, "AzimuthDegrees = ", mAzimuthDegrees)); + StringBuilder builder = new StringBuilder("ReflectingPlane["); + builder.append(" LatitudeDegrees=").append(mLatitudeDegrees); + builder.append(" LongitudeDegrees=").append(mLongitudeDegrees); + builder.append(" AltitudeMeters=").append(mAltitudeMeters); + builder.append(" AzimuthDegrees=").append(mAzimuthDegrees); + builder.append(']'); return builder.toString(); } @Override - public void writeToParcel(@NonNull Parcel parcel, int flags) { - parcel.writeDouble(mLatitudeDegrees); - parcel.writeDouble(mLongitudeDegrees); - parcel.writeDouble(mAltitudeMeters); - parcel.writeDouble(mAzimuthDegrees); + public boolean equals(Object obj) { + if (obj instanceof GnssReflectingPlane) { + GnssReflectingPlane that = (GnssReflectingPlane) obj; + return Double.compare(this.mLatitudeDegrees, that.mLatitudeDegrees) == 0 + && Double.compare(this.mLongitudeDegrees, that.mLongitudeDegrees) == 0 + && Double.compare(this.mAltitudeMeters, that.mAltitudeMeters) == 0 + && Double.compare(this.mAzimuthDegrees, that.mAzimuthDegrees) == 0; + } + return false; + } + + @Override + public int hashCode() { + return Objects.hash(mLatitudeDegrees, mLatitudeDegrees, mAltitudeMeters, mAzimuthDegrees); } /** Builder for {@link GnssReflectingPlane} */ diff --git a/location/java/android/location/GnssSingleSatCorrection.java b/location/java/android/location/GnssSingleSatCorrection.java index 262630b79cb0..a7fce0aaaf6c 100644 --- a/location/java/android/location/GnssSingleSatCorrection.java +++ b/location/java/android/location/GnssSingleSatCorrection.java @@ -16,6 +16,11 @@ package android.location; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.SINGLE_SAT_CORRECTION_HAS_COMBINED_ATTENUATION; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.SINGLE_SAT_CORRECTION_HAS_COMBINED_EXCESS_PATH_LENGTH; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.SINGLE_SAT_CORRECTION_HAS_COMBINED_EXCESS_PATH_LENGTH_UNC; +import static android.hardware.gnss.measurement_corrections.SingleSatCorrection.SINGLE_SAT_CORRECTION_HAS_SAT_IS_LOS_PROBABILITY; + import android.annotation.FloatRange; import android.annotation.IntRange; import android.annotation.NonNull; @@ -26,6 +31,8 @@ import android.os.Parcelable; import com.android.internal.util.Preconditions; +import java.util.ArrayList; +import java.util.List; import java.util.Objects; /** @@ -36,106 +43,47 @@ import java.util.Objects; @SystemApi public final class GnssSingleSatCorrection implements Parcelable { - /** - * Bit mask for {@link #mSingleSatCorrectionFlags} indicating the presence of {@link - * #mProbSatIsLos}. - * - * @hide - */ - public static final int HAS_PROB_SAT_IS_LOS_MASK = 1 << 0; - - /** - * Bit mask for {@link #mSingleSatCorrectionFlags} indicating the presence of {@link - * #mExcessPathLengthMeters}. - * - * @hide - */ - public static final int HAS_EXCESS_PATH_LENGTH_MASK = 1 << 1; - - /** - * Bit mask for {@link #mSingleSatCorrectionFlags} indicating the presence of {@link - * #mExcessPathLengthUncertaintyMeters}. - * - * @hide - */ - public static final int HAS_EXCESS_PATH_LENGTH_UNC_MASK = 1 << 2; - - /** - * Bit mask for {@link #mSingleSatCorrectionFlags} indicating the presence of {@link - * #mReflectingPlane}. - * - * @hide - */ - public static final int HAS_REFLECTING_PLANE_MASK = 1 << 3; + private static final int HAS_PROB_SAT_IS_LOS_MASK = + SINGLE_SAT_CORRECTION_HAS_SAT_IS_LOS_PROBABILITY; + private static final int HAS_COMBINED_EXCESS_PATH_LENGTH_MASK = + SINGLE_SAT_CORRECTION_HAS_COMBINED_EXCESS_PATH_LENGTH; + private static final int HAS_COMBINED_EXCESS_PATH_LENGTH_UNC_MASK = + SINGLE_SAT_CORRECTION_HAS_COMBINED_EXCESS_PATH_LENGTH_UNC; + private static final int HAS_COMBINED_ATTENUATION_MASK = + SINGLE_SAT_CORRECTION_HAS_COMBINED_ATTENUATION; - /** A bitmask of fields present in this object (see HAS_* constants defined above) */ + /* A bitmask of fields present in this object (see HAS_* constants defined above). */ private final int mSingleSatCorrectionFlags; - /** Defines the constellation of the given satellite as defined in {@link GnssStatus}. */ - @GnssStatus.ConstellationType private final int mConstellationType; - - /** - * Satellite vehicle ID number - * - * <p>Interpretation depends on {@link GnssStatus#getSvid(int)}. - */ - @IntRange(from = 0) private final int mSatId; - - /** - * Carrier frequency of the signal to be corrected, for example it can be the GPS center - * frequency for L1 = 1,575,420,000 Hz, varying GLO channels, etc. - * - * <p>For an L1, L5 receiver tracking a satellite on L1 and L5 at the same time, two correction - * objects will be reported for this same satellite, in one of the correction objects, all the - * values related to L1 will be filled, and in the other all of the values related to L5 will be - * filled. - */ - @FloatRange(from = 0.0f, fromInclusive = false) private final float mCarrierFrequencyHz; - - /** - * The probability that the satellite is estimated to be in Line-of-Sight condition at the given - * location. - */ - @FloatRange(from = 0.0f, to = 1.0f) private final float mProbSatIsLos; + private final float mCombinedExcessPathLengthMeters; + private final float mCombinedExcessPathLengthUncertaintyMeters; + private final float mCombinedAttenuationDb; - /** - * Excess path length to be subtracted from pseudorange before using it in calculating location. - */ - @FloatRange(from = 0.0f) - private final float mExcessPathLengthMeters; - - /** Error estimate (1-sigma) for the Excess path length estimate */ - @FloatRange(from = 0.0f) - private final float mExcessPathLengthUncertaintyMeters; - - /** - * Defines the reflecting plane location and azimuth information - * - * <p>The flag HAS_REFLECTING_PLANE will be used to set this value to invalid if the satellite - * signal goes through multiple reflections or if reflection plane serving is not supported. - */ - @Nullable - private final GnssReflectingPlane mReflectingPlane; + @NonNull + private final List<GnssExcessPathInfo> mGnssExcessPathInfoList; private GnssSingleSatCorrection(int singleSatCorrectionFlags, int constellationType, int satId, float carrierFrequencyHz, float probSatIsLos, float excessPathLengthMeters, - float excessPathLengthUncertaintyMeters, GnssReflectingPlane reflectingPlane) { + float excessPathLengthUncertaintyMeters, + float combinedAttenuationDb, + @NonNull List<GnssExcessPathInfo> gnssExcessPathInfoList) { mSingleSatCorrectionFlags = singleSatCorrectionFlags; mConstellationType = constellationType; mSatId = satId; mCarrierFrequencyHz = carrierFrequencyHz; mProbSatIsLos = probSatIsLos; - mExcessPathLengthMeters = excessPathLengthMeters; - mExcessPathLengthUncertaintyMeters = excessPathLengthUncertaintyMeters; - mReflectingPlane = reflectingPlane; + mCombinedExcessPathLengthMeters = excessPathLengthMeters; + mCombinedExcessPathLengthUncertaintyMeters = excessPathLengthUncertaintyMeters; + mCombinedAttenuationDb = combinedAttenuationDb; + mGnssExcessPathInfoList = gnssExcessPathInfoList; } /** - * Gets a bitmask of fields present in this object + * Gets a bitmask of fields present in this object. * * @hide */ @@ -193,29 +141,46 @@ public final class GnssSingleSatCorrection implements Parcelable { } /** - * Returns the Excess path length to be subtracted from pseudorange before using it in + * Returns the combined excess path length to be subtracted from pseudorange before using it in * calculating location. */ @FloatRange(from = 0.0f) public float getExcessPathLengthMeters() { - return mExcessPathLengthMeters; + return mCombinedExcessPathLengthMeters; } - /** Returns the error estimate (1-sigma) for the Excess path length estimate */ + /** Returns the error estimate (1-sigma) for the combined excess path length estimate. */ @FloatRange(from = 0.0f) public float getExcessPathLengthUncertaintyMeters() { - return mExcessPathLengthUncertaintyMeters; + return mCombinedExcessPathLengthUncertaintyMeters; } /** - * Returns the reflecting plane characteristics at which the signal has bounced + * Returns the combined expected reduction of signal strength for this satellite in + * non-negative dB. + */ + @FloatRange(from = 0.0f) + public float getCombinedAttenuationDb() { + return mCombinedAttenuationDb; + } + + /** + * Returns the reflecting plane characteristics at which the signal has bounced. * - * <p>The flag HAS_REFLECTING_PLANE will be used to set this value to invalid if the satellite - * signal goes through multiple reflections or if reflection plane serving is not supported + * @deprecated Combined excess path does not have a reflecting plane. */ @Nullable + @Deprecated public GnssReflectingPlane getReflectingPlane() { - return mReflectingPlane; + return null; + } + + /** + * Returns the list of {@link GnssExcessPathInfo} associated with this satellite signal. + */ + @NonNull + public List<GnssExcessPathInfo> getGnssExcessPathInfoList() { + return mGnssExcessPathInfoList; } /** Returns {@code true} if {@link #getProbabilityLineOfSight()} is valid. */ @@ -225,17 +190,27 @@ public final class GnssSingleSatCorrection implements Parcelable { /** Returns {@code true} if {@link #getExcessPathLengthMeters()} is valid. */ public boolean hasExcessPathLength() { - return (mSingleSatCorrectionFlags & HAS_EXCESS_PATH_LENGTH_MASK) != 0; + return (mSingleSatCorrectionFlags & HAS_COMBINED_EXCESS_PATH_LENGTH_MASK) != 0; } /** Returns {@code true} if {@link #getExcessPathLengthUncertaintyMeters()} is valid. */ public boolean hasExcessPathLengthUncertainty() { - return (mSingleSatCorrectionFlags & HAS_EXCESS_PATH_LENGTH_UNC_MASK) != 0; + return (mSingleSatCorrectionFlags & HAS_COMBINED_EXCESS_PATH_LENGTH_UNC_MASK) != 0; } - /** Returns {@code true} if {@link #getReflectingPlane()} is valid. */ + /** + * Returns {@code true} if {@link #getReflectingPlane()} is valid. + * + * @deprecated Combined excess path does not have a reflecting plane. + */ + @Deprecated public boolean hasReflectingPlane() { - return (mSingleSatCorrectionFlags & HAS_REFLECTING_PLANE_MASK) != 0; + return false; + } + + /** Returns {@code true} if {@link #getCombinedAttenuationDb()} is valid. */ + public boolean hasCombinedAttenuation() { + return (mSingleSatCorrectionFlags & HAS_COMBINED_ATTENUATION_MASK) != 0; } @Override @@ -253,14 +228,15 @@ public final class GnssSingleSatCorrection implements Parcelable { parcel.writeFloat(mProbSatIsLos); } if (hasExcessPathLength()) { - parcel.writeFloat(mExcessPathLengthMeters); + parcel.writeFloat(mCombinedExcessPathLengthMeters); } if (hasExcessPathLengthUncertainty()) { - parcel.writeFloat(mExcessPathLengthUncertaintyMeters); + parcel.writeFloat(mCombinedExcessPathLengthUncertaintyMeters); } - if (hasReflectingPlane()) { - mReflectingPlane.writeToParcel(parcel, flags); + if (hasCombinedAttenuation()) { + parcel.writeFloat(mCombinedAttenuationDb); } + parcel.writeTypedList(mGnssExcessPathInfoList); } public static final Creator<GnssSingleSatCorrection> CREATOR = @@ -274,18 +250,21 @@ public final class GnssSingleSatCorrection implements Parcelable { float carrierFrequencyHz = parcel.readFloat(); float probSatIsLos = (singleSatCorrectionFlags & HAS_PROB_SAT_IS_LOS_MASK) != 0 ? parcel.readFloat() : 0; - float excessPathLengthMeters = - (singleSatCorrectionFlags & HAS_EXCESS_PATH_LENGTH_MASK) != 0 + float combinedExcessPathLengthMeters = + (singleSatCorrectionFlags & HAS_COMBINED_EXCESS_PATH_LENGTH_MASK) != 0 ? parcel.readFloat() : 0; - float excessPathLengthUncertaintyMeters = - (singleSatCorrectionFlags & HAS_EXCESS_PATH_LENGTH_UNC_MASK) != 0 + float combinedExcessPathLengthUncertaintyMeters = + (singleSatCorrectionFlags & HAS_COMBINED_EXCESS_PATH_LENGTH_UNC_MASK) + != 0 ? parcel.readFloat() : 0; + float combinedAttenuationDb = + (singleSatCorrectionFlags & HAS_COMBINED_ATTENUATION_MASK) != 0 ? parcel.readFloat() : 0; - GnssReflectingPlane reflectingPlane = - (singleSatCorrectionFlags & HAS_REFLECTING_PLANE_MASK) != 0 - ? GnssReflectingPlane.CREATOR.createFromParcel(parcel) : null; + List<GnssExcessPathInfo> gnssExcessPathInfoList = parcel.createTypedArrayList( + GnssExcessPathInfo.CREATOR); return new GnssSingleSatCorrection(singleSatCorrectionFlags, constellationType, - satId, carrierFrequencyHz, probSatIsLos, excessPathLengthMeters, - excessPathLengthUncertaintyMeters, reflectingPlane); + satId, carrierFrequencyHz, probSatIsLos, combinedExcessPathLengthMeters, + combinedExcessPathLengthUncertaintyMeters, combinedAttenuationDb, + gnssExcessPathInfoList); } @Override @@ -296,56 +275,24 @@ public final class GnssSingleSatCorrection implements Parcelable { @Override public boolean equals(Object obj) { - if (this == obj) { - return true; - } - if (!(obj instanceof GnssSingleSatCorrection)) { - return false; - } - - GnssSingleSatCorrection other = (GnssSingleSatCorrection) obj; - if (mConstellationType != other.mConstellationType) { - return false; - } - if (mSatId != other.mSatId) { - return false; - } - if (Float.compare(mCarrierFrequencyHz, other.mCarrierFrequencyHz) != 0) { - return false; - } - - if (hasValidSatelliteLineOfSight() != other.hasValidSatelliteLineOfSight()) { - return false; - } - if (hasValidSatelliteLineOfSight() - && Float.compare(mProbSatIsLos, other.mProbSatIsLos) != 0) { - return false; - } - - if (hasExcessPathLength() != other.hasExcessPathLength()) { - return false; - } - if (hasExcessPathLength() - && Float.compare(mExcessPathLengthMeters, other.mExcessPathLengthMeters) != 0) { - return false; - } - - if (hasExcessPathLengthUncertainty() != other.hasExcessPathLengthUncertainty()) { - return false; - } - if (hasExcessPathLengthUncertainty() && Float.compare(mExcessPathLengthUncertaintyMeters, - other.mExcessPathLengthUncertaintyMeters) != 0) { - return false; - } - - if (hasReflectingPlane() != other.hasReflectingPlane()) { - return false; - } - if (hasReflectingPlane() - && !mReflectingPlane.equals(other.mReflectingPlane)) { - return false; - } - return true; + if (obj instanceof GnssSingleSatCorrection) { + GnssSingleSatCorrection that = (GnssSingleSatCorrection) obj; + return this.mSingleSatCorrectionFlags == that.mSingleSatCorrectionFlags + && this.mConstellationType == that.mConstellationType + && this.mSatId == that.mSatId + && Float.compare(mCarrierFrequencyHz, that.mCarrierFrequencyHz) == 0 + && (!hasValidSatelliteLineOfSight() || Float.compare(mProbSatIsLos, + that.mProbSatIsLos) == 0) + && (!hasExcessPathLength() || Float.compare(mCombinedExcessPathLengthMeters, + that.mCombinedExcessPathLengthMeters) == 0) + && (!hasExcessPathLengthUncertainty() || Float.compare( + mCombinedExcessPathLengthUncertaintyMeters, + that.mCombinedExcessPathLengthUncertaintyMeters) == 0) + && (!hasCombinedAttenuation() || Float.compare(mCombinedAttenuationDb, + that.mCombinedAttenuationDb) == 0) + && mGnssExcessPathInfoList.equals(that.mGnssExcessPathInfoList); + } + return false; } @Override @@ -355,9 +302,10 @@ public final class GnssSingleSatCorrection implements Parcelable { mSatId, mCarrierFrequencyHz, mProbSatIsLos, - mExcessPathLengthMeters, - mExcessPathLengthUncertaintyMeters, - mReflectingPlane); + mCombinedExcessPathLengthMeters, + mCombinedExcessPathLengthUncertaintyMeters, + mCombinedAttenuationDb, + mGnssExcessPathInfoList); } @NonNull @@ -371,14 +319,19 @@ public final class GnssSingleSatCorrection implements Parcelable { builder.append(" ProbSatIsLos=").append(mProbSatIsLos); } if (hasExcessPathLength()) { - builder.append(" ExcessPathLengthMeters=").append(mExcessPathLengthMeters); + builder.append(" CombinedExcessPathLengthMeters=").append( + mCombinedExcessPathLengthMeters); } if (hasExcessPathLengthUncertainty()) { - builder.append(" ExcessPathLengthUncertaintyMeters=").append( - mExcessPathLengthUncertaintyMeters); + builder.append(" CombinedExcessPathLengthUncertaintyMeters=").append( + mCombinedExcessPathLengthUncertaintyMeters); } - if (hasReflectingPlane()) { - builder.append(" ReflectingPlane=").append(mReflectingPlane); + if (hasCombinedAttenuation()) { + builder.append(" CombinedAttenuationDb=").append( + mCombinedAttenuationDb); + } + if (!mGnssExcessPathInfoList.isEmpty()) { + builder.append(' ').append(mGnssExcessPathInfoList.toString()); } builder.append(']'); return builder.toString(); @@ -386,21 +339,16 @@ public final class GnssSingleSatCorrection implements Parcelable { /** Builder for {@link GnssSingleSatCorrection} */ public static final class Builder { - - /** - * For documentation of below fields, see corresponding fields in {@link - * GnssSingleSatCorrection}. - */ private int mSingleSatCorrectionFlags; - private int mConstellationType; private int mSatId; private float mCarrierFrequencyHz; private float mProbSatIsLos; - private float mExcessPathLengthMeters; - private float mExcessPathLengthUncertaintyMeters; - @Nullable - private GnssReflectingPlane mReflectingPlane; + private float mCombinedExcessPathLengthMeters; + private float mCombinedExcessPathLengthUncertaintyMeters; + private float mCombinedAttenuationDb; + @NonNull + private List<GnssExcessPathInfo> mGnssExcessInfoList = new ArrayList<>(); /** Sets the constellation type. */ @NonNull public Builder setConstellationType( @@ -409,18 +357,18 @@ public final class GnssSingleSatCorrection implements Parcelable { return this; } - /** Sets the Satellite ID defined in the ICD of the given constellation. */ + /** Sets the satellite ID defined in the ICD of the given constellation. */ @NonNull public Builder setSatelliteId(@IntRange(from = 0) int satId) { Preconditions.checkArgumentNonnegative(satId, "satId should be non-negative."); mSatId = satId; return this; } - /** Sets the Carrier frequency in Hz. */ + /** Sets the carrier frequency in Hz. */ @NonNull public Builder setCarrierFrequencyHz( @FloatRange(from = 0.0f, fromInclusive = false) float carrierFrequencyHz) { - Preconditions.checkArgument( - carrierFrequencyHz >= 0, "carrierFrequencyHz should be non-negative."); + Preconditions.checkArgumentInRange( + carrierFrequencyHz, 0, Float.MAX_VALUE, "carrierFrequencyHz"); mCarrierFrequencyHz = carrierFrequencyHz; return this; } @@ -450,58 +398,90 @@ public final class GnssSingleSatCorrection implements Parcelable { } /** - * Sets the Excess path length to be subtracted from pseudorange before using it in + * Sets the combined excess path length to be subtracted from pseudorange before using it in * calculating location. */ - @NonNull public Builder setExcessPathLengthMeters( - @FloatRange(from = 0.0f) float excessPathLengthMeters) { - Preconditions.checkArgument(excessPathLengthMeters >= 0, - "excessPathLengthMeters should be non-negative."); - mExcessPathLengthMeters = excessPathLengthMeters; - mSingleSatCorrectionFlags |= HAS_EXCESS_PATH_LENGTH_MASK; + @NonNull + public Builder setExcessPathLengthMeters( + @FloatRange(from = 0.0f) float combinedExcessPathLengthMeters) { + Preconditions.checkArgumentInRange(combinedExcessPathLengthMeters, 0, Float.MAX_VALUE, + "excessPathLengthMeters"); + mCombinedExcessPathLengthMeters = combinedExcessPathLengthMeters; + mSingleSatCorrectionFlags |= HAS_COMBINED_EXCESS_PATH_LENGTH_MASK; return this; } /** - * Clears the Excess path length. + * Clears the combined excess path length. * * <p>This is to negate {@link #setExcessPathLengthMeters} call. */ @NonNull public Builder clearExcessPathLengthMeters() { - mExcessPathLengthMeters = 0; - mSingleSatCorrectionFlags &= ~HAS_EXCESS_PATH_LENGTH_MASK; + mCombinedExcessPathLengthMeters = 0; + mSingleSatCorrectionFlags &= ~HAS_COMBINED_EXCESS_PATH_LENGTH_MASK; return this; } - /** Sets the error estimate (1-sigma) for the Excess path length estimate */ + /** Sets the error estimate (1-sigma) for the combined excess path length estimate. */ @NonNull public Builder setExcessPathLengthUncertaintyMeters( - @FloatRange(from = 0.0f) float excessPathLengthUncertaintyMeters) { - Preconditions.checkArgument(excessPathLengthUncertaintyMeters >= 0, - "excessPathLengthUncertaintyMeters should be non-negative."); - mExcessPathLengthUncertaintyMeters = excessPathLengthUncertaintyMeters; - mSingleSatCorrectionFlags |= HAS_EXCESS_PATH_LENGTH_UNC_MASK; + @FloatRange(from = 0.0f) float combinedExcessPathLengthUncertaintyMeters) { + Preconditions.checkArgumentInRange(combinedExcessPathLengthUncertaintyMeters, 0, + Float.MAX_VALUE, "excessPathLengthUncertaintyMeters"); + mCombinedExcessPathLengthUncertaintyMeters = combinedExcessPathLengthUncertaintyMeters; + mSingleSatCorrectionFlags |= HAS_COMBINED_EXCESS_PATH_LENGTH_UNC_MASK; return this; } /** - * Clears the error estimate (1-sigma) for the Excess path length estimate + * Clears the error estimate (1-sigma) for the combined excess path length estimate. * * <p>This is to negate {@link #setExcessPathLengthUncertaintyMeters} call. */ @NonNull public Builder clearExcessPathLengthUncertaintyMeters() { - mExcessPathLengthUncertaintyMeters = 0; - mSingleSatCorrectionFlags &= ~HAS_EXCESS_PATH_LENGTH_UNC_MASK; + mCombinedExcessPathLengthUncertaintyMeters = 0; + mSingleSatCorrectionFlags &= ~HAS_COMBINED_EXCESS_PATH_LENGTH_UNC_MASK; return this; } - /** Sets the reflecting plane information */ + /** + * Sets the combined attenuation in Db. + */ + @NonNull public Builder setCombinedAttenuationDb( + @FloatRange(from = 0.0f) float combinedAttenuationDb) { + Preconditions.checkArgumentInRange(combinedAttenuationDb, 0, Float.MAX_VALUE, + "combinedAttenuationDb"); + mCombinedAttenuationDb = combinedAttenuationDb; + mSingleSatCorrectionFlags |= HAS_COMBINED_ATTENUATION_MASK; + return this; + } + + /** + * Clears the combined attenuation. + * + * <p>This is to negate {@link #setCombinedAttenuationDb} call. + */ + @NonNull public Builder clearCombinedAttenuationDb() { + mCombinedAttenuationDb = 0; + mSingleSatCorrectionFlags &= ~HAS_COMBINED_ATTENUATION_MASK; + return this; + } + + /** + * Sets the reflecting plane information. + * + * @deprecated Combined excess path does not have a reflecting plane. + */ + @Deprecated @NonNull public Builder setReflectingPlane(@Nullable GnssReflectingPlane reflectingPlane) { - mReflectingPlane = reflectingPlane; - if (reflectingPlane != null) { - mSingleSatCorrectionFlags |= HAS_REFLECTING_PLANE_MASK; - } else { - mSingleSatCorrectionFlags &= ~HAS_REFLECTING_PLANE_MASK; - } + return this; + } + + /** + * Sets the collection of {@link GnssExcessPathInfo}. + */ + @NonNull + public Builder setGnssExcessPathInfoList(@NonNull List<GnssExcessPathInfo> infoList) { + mGnssExcessInfoList = new ArrayList<>(infoList); return this; } @@ -512,9 +492,10 @@ public final class GnssSingleSatCorrection implements Parcelable { mSatId, mCarrierFrequencyHz, mProbSatIsLos, - mExcessPathLengthMeters, - mExcessPathLengthUncertaintyMeters, - mReflectingPlane); + mCombinedExcessPathLengthMeters, + mCombinedExcessPathLengthUncertaintyMeters, + mCombinedAttenuationDb, + mGnssExcessInfoList); } } } diff --git a/location/java/android/location/Location.java b/location/java/android/location/Location.java index f1605f1ffe5d..033056cb2a69 100644 --- a/location/java/android/location/Location.java +++ b/location/java/android/location/Location.java @@ -132,31 +132,31 @@ public class Location implements Parcelable { } /** - * Construct a new Location object that is copied from an existing one. + * Constructs a new location copied from the given location. */ - public Location(@NonNull Location l) { - set(l); + public Location(@NonNull Location location) { + set(location); } /** * Turns this location into a copy of the given location. */ - public void set(@NonNull Location l) { - mFieldsMask = l.mFieldsMask; - mProvider = l.mProvider; - mTimeMs = l.mTimeMs; - mElapsedRealtimeNs = l.mElapsedRealtimeNs; - mElapsedRealtimeUncertaintyNs = l.mElapsedRealtimeUncertaintyNs; - mLatitudeDegrees = l.mLatitudeDegrees; - mLongitudeDegrees = l.mLongitudeDegrees; - mHorizontalAccuracyMeters = l.mHorizontalAccuracyMeters; - mAltitudeMeters = l.mAltitudeMeters; - mAltitudeAccuracyMeters = l.mAltitudeAccuracyMeters; - mSpeedMetersPerSecond = l.mSpeedMetersPerSecond; - mSpeedAccuracyMetersPerSecond = l.mSpeedAccuracyMetersPerSecond; - mBearingDegrees = l.mBearingDegrees; - mBearingAccuracyDegrees = l.mBearingAccuracyDegrees; - mExtras = (l.mExtras == null) ? null : new Bundle(l.mExtras); + public void set(@NonNull Location location) { + mFieldsMask = location.mFieldsMask; + mProvider = location.mProvider; + mTimeMs = location.mTimeMs; + mElapsedRealtimeNs = location.mElapsedRealtimeNs; + mElapsedRealtimeUncertaintyNs = location.mElapsedRealtimeUncertaintyNs; + mLatitudeDegrees = location.mLatitudeDegrees; + mLongitudeDegrees = location.mLongitudeDegrees; + mHorizontalAccuracyMeters = location.mHorizontalAccuracyMeters; + mAltitudeMeters = location.mAltitudeMeters; + mAltitudeAccuracyMeters = location.mAltitudeAccuracyMeters; + mSpeedMetersPerSecond = location.mSpeedMetersPerSecond; + mSpeedAccuracyMetersPerSecond = location.mSpeedAccuracyMetersPerSecond; + mBearingDegrees = location.mBearingDegrees; + mBearingAccuracyDegrees = location.mBearingAccuracyDegrees; + mExtras = (location.mExtras == null) ? null : new Bundle(location.mExtras); } /** @@ -182,14 +182,13 @@ public class Location implements Parcelable { } /** - * Returns the approximate distance in meters between this - * location and the given location. Distance is defined using - * the WGS84 ellipsoid. + * Returns the approximate distance in meters between this location and the given location. + * Distance is defined using the WGS84 ellipsoid. * * @param dest the destination location * @return the approximate distance in meters */ - public @FloatRange float distanceTo(@NonNull Location dest) { + public @FloatRange(from = 0.0) float distanceTo(@NonNull Location dest) { BearingDistanceCache cache = sBearingDistanceCache.get(); // See if we already have the result if (mLatitudeDegrees != cache.mLat1 || mLongitudeDegrees != cache.mLon1 @@ -201,11 +200,10 @@ public class Location implements Parcelable { } /** - * Returns the approximate initial bearing in degrees East of true - * North when traveling along the shortest path between this - * location and the given location. The shortest path is defined - * using the WGS84 ellipsoid. Locations that are (nearly) - * antipodal may produce meaningless results. + * Returns the approximate initial bearing in degrees east of true north when traveling along + * the shortest path between this location and the given location. The shortest path is defined + * using the WGS84 ellipsoid. Locations that are (nearly) antipodal may produce meaningless + * results. * * @param dest the destination location * @return the initial bearing in degrees @@ -254,7 +252,7 @@ public class Location implements Parcelable { * not be used to order or compare locations. Prefer {@link #getElapsedRealtimeNanos} for that * purpose, as the elapsed realtime clock is guaranteed to be monotonic. * - * <p>On the other hand, this method may be useful for presenting a human readable time to the + * <p>On the other hand, this method may be useful for presenting a human-readable time to the * user, or as a heuristic for comparing location fixes across reboot or across devices. * * <p>All locations generated by the {@link LocationManager} are guaranteed to have this time @@ -263,25 +261,24 @@ public class Location implements Parcelable { * * @return the Unix epoch time of this location */ - public @IntRange long getTime() { + public @IntRange(from = 0) long getTime() { return mTimeMs; } /** * Sets the Unix epoch time of this location fix, in milliseconds since the start of the Unix - * epoch (00:00:00 January 1, 1970 UTC). + * epoch (00:00:00 January 1 1970 UTC). * * @param timeMs the Unix epoch time of this location - * @see #getTime for more information about times / clocks */ - public void setTime(@IntRange long timeMs) { + public void setTime(@IntRange(from = 0) long timeMs) { mTimeMs = timeMs; } /** * Return the time of this fix in nanoseconds of elapsed realtime since system boot. * - * <p>This value can be compared with {@link android.os.SystemClock#elapsedRealtimeNanos}, to + * <p>This value can be compared with {@link android.os.SystemClock#elapsedRealtimeNanos} to * reliably order or compare locations. This is reliable because elapsed realtime is guaranteed * to be monotonic and continues to increment even when the system is in deep sleep (unlike * {@link #getTime}). However, since elapsed realtime is with reference to system boot, it does @@ -292,7 +289,7 @@ public class Location implements Parcelable { * * @return elapsed realtime of this location in nanoseconds */ - public @IntRange long getElapsedRealtimeNanos() { + public @IntRange(from = 0) long getElapsedRealtimeNanos() { return mElapsedRealtimeNs; } @@ -302,7 +299,7 @@ public class Location implements Parcelable { * @return elapsed realtime of this location in milliseconds * @see #getElapsedRealtimeNanos() */ - public @IntRange long getElapsedRealtimeMillis() { + public @IntRange(from = 0) long getElapsedRealtimeMillis() { return NANOSECONDS.toMillis(mElapsedRealtimeNs); } @@ -312,7 +309,7 @@ public class Location implements Parcelable { * * @return age of this location in milliseconds */ - public @IntRange long getElapsedRealtimeAgeMillis() { + public @IntRange(from = 0) long getElapsedRealtimeAgeMillis() { return getElapsedRealtimeAgeMillis(SystemClock.elapsedRealtime()); } @@ -323,7 +320,8 @@ public class Location implements Parcelable { * @param referenceRealtimeMs reference realtime in milliseconds * @return age of this location in milliseconds */ - public @IntRange long getElapsedRealtimeAgeMillis(@IntRange long referenceRealtimeMs) { + public long getElapsedRealtimeAgeMillis( + @IntRange(from = 0) long referenceRealtimeMs) { return referenceRealtimeMs - getElapsedRealtimeMillis(); } @@ -332,7 +330,7 @@ public class Location implements Parcelable { * * @param elapsedRealtimeNs elapsed realtime in nanoseconds */ - public void setElapsedRealtimeNanos(@IntRange long elapsedRealtimeNs) { + public void setElapsedRealtimeNanos(@IntRange(from = 0) long elapsedRealtimeNs) { mElapsedRealtimeNs = elapsedRealtimeNs; } @@ -346,7 +344,7 @@ public class Location implements Parcelable { * * @return uncertainty in nanoseconds of the elapsed realtime of this location */ - public @FloatRange double getElapsedRealtimeUncertaintyNanos() { + public @FloatRange(from = 0.0) double getElapsedRealtimeUncertaintyNanos() { return mElapsedRealtimeUncertaintyNs; } @@ -358,20 +356,20 @@ public class Location implements Parcelable { * this location */ public void setElapsedRealtimeUncertaintyNanos( - @FloatRange double elapsedRealtimeUncertaintyNs) { + @FloatRange(from = 0.0) double elapsedRealtimeUncertaintyNs) { mElapsedRealtimeUncertaintyNs = elapsedRealtimeUncertaintyNs; mFieldsMask |= HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK; } /** - * True if this location has a elapsed realtime uncertainty, false otherwise. + * True if this location has an elapsed realtime uncertainty, false otherwise. */ public boolean hasElapsedRealtimeUncertaintyNanos() { return (mFieldsMask & HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK) != 0; } /** - * Removes the elapsed realtime uncertainy from this location. + * Removes the elapsed realtime uncertainty from this location. */ public void removeElapsedRealtimeUncertaintyNanos() { mFieldsMask &= ~HAS_ELAPSED_REALTIME_UNCERTAINTY_MASK; @@ -383,7 +381,7 @@ public class Location implements Parcelable { * * @return latitude of this location */ - public @FloatRange double getLatitude() { + public @FloatRange(from = -90.0, to = 90.0) double getLatitude() { return mLatitudeDegrees; } @@ -392,7 +390,7 @@ public class Location implements Parcelable { * * @param latitudeDegrees latitude in degrees */ - public void setLatitude(@FloatRange double latitudeDegrees) { + public void setLatitude(@FloatRange(from = -90.0, to = 90.0) double latitudeDegrees) { mLatitudeDegrees = latitudeDegrees; } @@ -402,7 +400,7 @@ public class Location implements Parcelable { * * @return longitude of this location */ - public @FloatRange double getLongitude() { + public @FloatRange(from = -180.0, to = 180.0) double getLongitude() { return mLongitudeDegrees; } @@ -411,7 +409,7 @@ public class Location implements Parcelable { * * @param longitudeDegrees longitude in degrees */ - public void setLongitude(@FloatRange double longitudeDegrees) { + public void setLongitude(@FloatRange(from = -180.0, to = 180.0) double longitudeDegrees) { mLongitudeDegrees = longitudeDegrees; } @@ -423,12 +421,12 @@ public class Location implements Parcelable { * reported location, there is a 68% chance that the true location falls within this circle. * This accuracy value is only valid for horizontal positioning, and not vertical positioning. * - * <p>This is only valid if {@link #hasSpeed()} is true. All locations generated by the + * <p>This is only valid if {@link #hasAccuracy()} is true. All locations generated by the * {@link LocationManager} include horizontal accuracy. * * @return horizontal accuracy of this location */ - public @FloatRange float getAccuracy() { + public @FloatRange(from = 0.0) float getAccuracy() { return mHorizontalAccuracyMeters; } @@ -437,7 +435,7 @@ public class Location implements Parcelable { * * @param horizontalAccuracyMeters horizontal altitude in meters */ - public void setAccuracy(@FloatRange float horizontalAccuracyMeters) { + public void setAccuracy(@FloatRange(from = 0.0) float horizontalAccuracyMeters) { mHorizontalAccuracyMeters = horizontalAccuracyMeters; mFieldsMask |= HAS_HORIZONTAL_ACCURACY_MASK; } @@ -500,7 +498,7 @@ public class Location implements Parcelable { * * @return vertical accuracy of this location */ - public @FloatRange float getVerticalAccuracyMeters() { + public @FloatRange(from = 0.0) float getVerticalAccuracyMeters() { return mAltitudeAccuracyMeters; } @@ -509,7 +507,7 @@ public class Location implements Parcelable { * * @param altitudeAccuracyMeters altitude accuracy in meters */ - public void setVerticalAccuracyMeters(@FloatRange float altitudeAccuracyMeters) { + public void setVerticalAccuracyMeters(@FloatRange(from = 0.0) float altitudeAccuracyMeters) { mAltitudeAccuracyMeters = altitudeAccuracyMeters; mFieldsMask |= HAS_ALTITUDE_ACCURACY_MASK; } @@ -538,17 +536,16 @@ public class Location implements Parcelable { * * @return speed at the time of this location */ - public @FloatRange float getSpeed() { + public @FloatRange(from = 0.0) float getSpeed() { return mSpeedMetersPerSecond; } /** - * Set the speed at the time of this location, in meters per second. Prefer not to set negative - * speeds. + * Set the speed at the time of this location, in meters per second. * * @param speedMetersPerSecond speed in meters per second */ - public void setSpeed(@FloatRange float speedMetersPerSecond) { + public void setSpeed(@FloatRange(from = 0.0) float speedMetersPerSecond) { mSpeedMetersPerSecond = speedMetersPerSecond; mFieldsMask |= HAS_SPEED_MASK; } @@ -576,7 +573,7 @@ public class Location implements Parcelable { * * @return vertical accuracy of this location */ - public @FloatRange float getSpeedAccuracyMetersPerSecond() { + public @FloatRange(from = 0.0) float getSpeedAccuracyMetersPerSecond() { return mSpeedAccuracyMetersPerSecond; } @@ -585,7 +582,8 @@ public class Location implements Parcelable { * * @param speedAccuracyMeterPerSecond speed accuracy in meters per second */ - public void setSpeedAccuracyMetersPerSecond(@FloatRange float speedAccuracyMeterPerSecond) { + public void setSpeedAccuracyMetersPerSecond( + @FloatRange(from = 0.0) float speedAccuracyMeterPerSecond) { mSpeedAccuracyMetersPerSecond = speedAccuracyMeterPerSecond; mFieldsMask |= HAS_SPEED_ACCURACY_MASK; } @@ -613,7 +611,7 @@ public class Location implements Parcelable { * * @return bearing at the time of this location */ - public @FloatRange(from = 0f, to = 360f, toInclusive = false) float getBearing() { + public @FloatRange(from = 0.0, to = 360.0, toInclusive = false) float getBearing() { return mBearingDegrees; } @@ -663,7 +661,7 @@ public class Location implements Parcelable { * * @return bearing accuracy in degrees of this location */ - public @FloatRange float getBearingAccuracyDegrees() { + public @FloatRange(from = 0.0) float getBearingAccuracyDegrees() { return mBearingAccuracyDegrees; } @@ -672,7 +670,7 @@ public class Location implements Parcelable { * * @param bearingAccuracyDegrees bearing accuracy in degrees */ - public void setBearingAccuracyDegrees(@FloatRange float bearingAccuracyDegrees) { + public void setBearingAccuracyDegrees(@FloatRange(from = 0.0) float bearingAccuracyDegrees) { mBearingAccuracyDegrees = bearingAccuracyDegrees; mFieldsMask |= HAS_BEARING_ACCURACY_MASK; } @@ -692,9 +690,11 @@ public class Location implements Parcelable { } /** - * Returns true if the Location came from a mock provider. + * Returns true if this is a mock location. If this location comes from the Android framework, + * this indicates that the location was provided by a test location provider, and thus may not + * be related to the actual location of the device. * - * @return true if this Location came from a mock provider, false otherwise + * @return true if this location came from a mock provider, false otherwise * @deprecated Prefer {@link #isMock()} instead. */ @Deprecated @@ -703,9 +703,9 @@ public class Location implements Parcelable { } /** - * Flag this Location as having come from a mock provider or not. + * Flag this location as having come from a mock provider or not. * - * @param isFromMockProvider true if this Location came from a mock provider, false otherwise + * @param isFromMockProvider true if this location came from a mock provider, false otherwise * @deprecated Prefer {@link #setMock(boolean)} instead. * @hide */ @@ -745,7 +745,7 @@ public class Location implements Parcelable { * will be present for any location. * * <ul> - * <li> satellites - the number of satellites used to derive the GNSS fix + * <li> satellites - the number of satellites used to derive a GNSS fix * </ul> */ public @Nullable Bundle getExtras() { @@ -899,7 +899,13 @@ public class Location implements Parcelable { return s.toString(); } - /** Dumps location. */ + /** + * Dumps location information to the given Printer. + * + * @deprecated Prefer to use {@link #toString()} along with whatever custom formatting is + * required instead of this method. It is not this class's job to manage print representations. + */ + @Deprecated public void dump(@NonNull Printer pw, @Nullable String prefix) { pw.println(prefix + this); } @@ -1209,10 +1215,10 @@ public class Location implements Parcelable { * @throws IllegalArgumentException if results is null or has length < 1 */ public static void distanceBetween( - @FloatRange double startLatitude, - @FloatRange double startLongitude, - @FloatRange double endLatitude, - @FloatRange double endLongitude, + @FloatRange(from = -90.0, to = 90.0) double startLatitude, + @FloatRange(from = -180.0, to = 180.0) double startLongitude, + @FloatRange(from = -90.0, to = 90.0) double endLatitude, + @FloatRange(from = -180.0, to = 180.0) double endLongitude, float[] results) { if (results == null || results.length < 1) { throw new IllegalArgumentException("results is null or has length < 1"); diff --git a/media/java/android/media/IAudioService.aidl b/media/java/android/media/IAudioService.aidl index bdbb740a849b..c186700a4326 100755 --- a/media/java/android/media/IAudioService.aidl +++ b/media/java/android/media/IAudioService.aidl @@ -39,6 +39,7 @@ import android.media.IRecordingConfigDispatcher; import android.media.IRingtonePlayer; import android.media.IStrategyPreferredDevicesDispatcher; import android.media.ISpatializerCallback; +import android.media.ISpatializerHeadTrackerAvailableCallback; import android.media.ISpatializerHeadTrackingModeCallback; import android.media.ISpatializerHeadToSoundStagePoseCallback; import android.media.ISpatializerOutputCallback; @@ -414,6 +415,11 @@ interface IAudioService { boolean isHeadTrackerEnabled(in AudioDeviceAttributes device); + boolean isHeadTrackerAvailable(); + + void registerSpatializerHeadTrackerAvailableCallback( + in ISpatializerHeadTrackerAvailableCallback cb, boolean register); + void setSpatializerEnabled(boolean enabled); boolean canBeSpatialized(in AudioAttributes aa, in AudioFormat af); diff --git a/media/java/android/media/ISpatializerHeadTrackerAvailableCallback.aidl b/media/java/android/media/ISpatializerHeadTrackerAvailableCallback.aidl new file mode 100644 index 000000000000..dc5ee1d4e985 --- /dev/null +++ b/media/java/android/media/ISpatializerHeadTrackerAvailableCallback.aidl @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.media; + +/** + * AIDL for the AudioService to signal whether audio device used by Spatializer has head tracker. + * + * {@hide} + */ +oneway interface ISpatializerHeadTrackerAvailableCallback { + + void dispatchSpatializerHeadTrackerAvailable(boolean available); +} diff --git a/media/java/android/media/MediaFormat.java b/media/java/android/media/MediaFormat.java index 4956dbefa240..7d3f91653cea 100644 --- a/media/java/android/media/MediaFormat.java +++ b/media/java/android/media/MediaFormat.java @@ -793,8 +793,11 @@ public final class MediaFormat { * By default, the decoder will output the same number of channels as present in the encoded * stream, if supported. Set this value to limit the number of output channels, and use * the downmix information in the stream, if available. - * <p>Values larger than the number of channels in the content to decode are ignored. + * <p>Values larger than the number of channels in the content to decode behave just + * like the actual channel count of the content (e.g. passing 99 for the decoding of 5.1 content + * will behave like using 6). * <p>This key is only used during decoding. + * @deprecated Use the non-AAC-specific key {@link #KEY_MAX_OUTPUT_CHANNEL_COUNT} instead */ public static final String KEY_AAC_MAX_OUTPUT_CHANNEL_COUNT = "aac-max-output-channel_count"; diff --git a/media/java/android/media/Spatializer.java b/media/java/android/media/Spatializer.java index be0ef37345ed..74ca4b858ff6 100644 --- a/media/java/android/media/Spatializer.java +++ b/media/java/android/media/Spatializer.java @@ -185,6 +185,45 @@ public class Spatializer { return false; } + /** + * Returns whether a head tracker is currently available for the audio device used by the + * spatializer effect. + * @return true if a head tracker is available and the effect is enabled, false otherwise. + * @see OnHeadTrackerAvailableListener + * @see #addOnHeadTrackerAvailableListener(Executor, OnHeadTrackerAvailableListener) + */ + public boolean isHeadTrackerAvailable() { + try { + return mAm.getService().isHeadTrackerAvailable(); + } catch (RemoteException e) { + e.rethrowFromSystemServer(); + } + return false; + } + + /** + * Adds a listener to be notified of changes to the availability of a head tracker. + * @param executor the {@code Executor} handling the callback + * @param listener the listener to receive availability updates + * @see #removeOnHeadTrackerAvailableListener(OnHeadTrackerAvailableListener) + */ + public void addOnHeadTrackerAvailableListener(@NonNull @CallbackExecutor Executor executor, + @NonNull OnHeadTrackerAvailableListener listener) { + mHeadTrackerListenerMgr.addListener(executor, listener, + "addOnHeadTrackerAvailableListener", + () -> new SpatializerHeadTrackerAvailableDispatcherStub()); + } + + /** + * Removes a previously registered listener for the availability of a head tracker. + * @param listener the listener previously registered with + * {@link #addOnHeadTrackerAvailableListener(Executor, OnHeadTrackerAvailableListener)} + */ + public void removeOnHeadTrackerAvailableListener( + @NonNull OnHeadTrackerAvailableListener listener) { + mHeadTrackerListenerMgr.removeListener(listener, "removeOnHeadTrackerAvailableListener"); + } + /** @hide */ @IntDef(flag = false, value = { SPATIALIZER_IMMERSIVE_LEVEL_OTHER, @@ -401,6 +440,22 @@ public class Spatializer { @HeadTrackingModeSet int mode); } + /** + * Interface to be notified of changes to the availability of a head tracker on the audio + * device to be used by the spatializer effect. + */ + public interface OnHeadTrackerAvailableListener { + /** + * Called when the availability of the head tracker changed. + * @param spatializer the {@code Spatializer} instance for which the head tracker + * availability was updated + * @param available true if the audio device that would output audio processed by + * the {@code Spatializer} has a head tracker associated with it, false + * otherwise. + */ + void onHeadTrackerAvailableChanged(@NonNull Spatializer spatializer, + boolean available); + } /** * @hide @@ -827,8 +882,12 @@ public class Spatializer { /** * @hide - * Returns the id of the output stream used for the spatializer effect playback + * Returns the id of the output stream used for the spatializer effect playback. + * This getter or associated listener {@link OnSpatializerOutputChangedListener} can be used for + * handling spatializer output-specific configurations (e.g. disabling speaker post-processing + * to avoid double-processing of the spatialized path). * @return id of the output stream, or 0 if no spatializer playback is active + * @see #setOnSpatializerOutputChangedListener(Executor, OnSpatializerOutputChangedListener) */ @SystemApi(client = SystemApi.Client.PRIVILEGED_APPS) @RequiresPermission(android.Manifest.permission.MODIFY_DEFAULT_AUDIO_EFFECTS) @@ -865,6 +924,8 @@ public class Spatializer { mOutputDispatcher = new SpatializerOutputDispatcherStub(); try { mAm.getService().registerSpatializerOutputCallback(mOutputDispatcher); + // immediately report the current output + mOutputDispatcher.dispatchSpatializerOutputChanged(getOutput()); } catch (RemoteException e) { mOutputListener = null; mOutputDispatcher = null; @@ -935,6 +996,36 @@ public class Spatializer { } //----------------------------------------------------------------------------- + // head tracker availability callback management and stub + /** + * manages the OnHeadTrackerAvailableListener listeners and the + * SpatializerHeadTrackerAvailableDispatcherStub + */ + private final CallbackUtil.LazyListenerManager<OnHeadTrackerAvailableListener> + mHeadTrackerListenerMgr = new CallbackUtil.LazyListenerManager(); + + private final class SpatializerHeadTrackerAvailableDispatcherStub + extends ISpatializerHeadTrackerAvailableCallback.Stub + implements CallbackUtil.DispatcherStub { + @Override + public void register(boolean register) { + try { + mAm.getService().registerSpatializerHeadTrackerAvailableCallback(this, register); + } catch (RemoteException e) { + e.rethrowFromSystemServer(); + } + } + + @Override + @SuppressLint("GuardedBy") // lock applied inside callListeners method + public void dispatchSpatializerHeadTrackerAvailable(boolean available) { + mHeadTrackerListenerMgr.callListeners( + (listener) -> listener.onHeadTrackerAvailableChanged( + Spatializer.this, available)); + } + } + + //----------------------------------------------------------------------------- // head pose callback management and stub private final Object mPoseListenerLock = new Object(); /** diff --git a/media/java/android/media/projection/IMediaProjection.aidl b/media/java/android/media/projection/IMediaProjection.aidl index 19fc0521d7aa..b136d5bc4db3 100644 --- a/media/java/android/media/projection/IMediaProjection.aidl +++ b/media/java/android/media/projection/IMediaProjection.aidl @@ -17,6 +17,7 @@ package android.media.projection; import android.media.projection.IMediaProjectionCallback; +import android.window.WindowContainerToken; /** {@hide} */ interface IMediaProjection { @@ -28,4 +29,16 @@ interface IMediaProjection { int applyVirtualDisplayFlags(int flags); void registerCallback(IMediaProjectionCallback callback); void unregisterCallback(IMediaProjectionCallback callback); + + /** + * Returns the {@link android.window.WindowContainerToken} identifying the task to record, or + * {@code null} if there is none. + */ + WindowContainerToken getTaskRecordingWindowContainerToken(); + + /** + * Updates the {@link android.window.WindowContainerToken} identifying the task to record, or + * {@code null} if there is none. + */ + void setTaskRecordingWindowContainerToken(in WindowContainerToken token); } diff --git a/media/java/android/media/projection/MediaProjection.java b/media/java/android/media/projection/MediaProjection.java index 4dde5e8d39a2..b5f95938f845 100644 --- a/media/java/android/media/projection/MediaProjection.java +++ b/media/java/android/media/projection/MediaProjection.java @@ -25,13 +25,14 @@ import android.hardware.display.DisplayManager; import android.hardware.display.VirtualDisplay; import android.hardware.display.VirtualDisplayConfig; import android.os.Handler; -import android.os.IBinder; import android.os.RemoteException; import android.util.ArrayMap; import android.util.Log; import android.view.ContentRecordingSession; +import android.view.IWindowManager; import android.view.Surface; import android.view.WindowManagerGlobal; +import android.window.WindowContainerToken; import java.util.Map; @@ -171,16 +172,34 @@ public final class MediaProjection { @NonNull VirtualDisplayConfig.Builder virtualDisplayConfig, @Nullable VirtualDisplay.Callback callback, @Nullable Handler handler) { try { - final Context windowContext = mContext.createWindowContext( - mContext.getDisplayNoVerify(), - TYPE_APPLICATION, null /* options */); - final IBinder windowContextToken = windowContext.getWindowContextToken(); + final IWindowManager wmService = WindowManagerGlobal.getWindowManagerService(); + final WindowContainerToken taskWindowContainerToken = + mImpl.getTaskRecordingWindowContainerToken(); + Context windowContext = null; + ContentRecordingSession session; + if (taskWindowContainerToken == null) { + windowContext = mContext.createWindowContext(mContext.getDisplayNoVerify(), + TYPE_APPLICATION, null /* options */); + session = ContentRecordingSession.createDisplaySession( + windowContext.getWindowContextToken()); + } else { + session = ContentRecordingSession.createTaskSession( + taskWindowContainerToken.asBinder()); + } virtualDisplayConfig.setWindowManagerMirroring(true); final DisplayManager dm = mContext.getSystemService(DisplayManager.class); final VirtualDisplay virtualDisplay = dm.createVirtualDisplay(this, - virtualDisplayConfig.build(), - callback, handler, windowContext); - setSession(windowContextToken, virtualDisplay); + virtualDisplayConfig.build(), callback, handler, windowContext); + if (virtualDisplay == null) { + // Since WM handling a new display and DM creating a new VirtualDisplay is async, + // WM may have tried to start task recording and encountered an error that required + // stopping recording entirely. The VirtualDisplay would then be null when the + // MediaProjection is no longer active. + return null; + } + session.setDisplayId(virtualDisplay.getDisplay().getDisplayId()); + // Successfully set up, so save the current session details. + wmService.setContentRecordingSession(session); return virtualDisplay; } catch (RemoteException e) { // Can not capture if WMS is not accessible, so bail out. @@ -189,28 +208,6 @@ public final class MediaProjection { } /** - * Updates the {@link ContentRecordingSession} describing the recording taking place on this - * {@link VirtualDisplay}. - * - * @throws RemoteException if updating the session on the server failed. - */ - private void setSession(@NonNull IBinder windowContextToken, - @Nullable VirtualDisplay virtualDisplay) - throws RemoteException { - if (virtualDisplay == null) { - // Not able to set up a new VirtualDisplay. - return; - } - // Identify the VirtualDisplay that will be hosting the recording. - ContentRecordingSession session = ContentRecordingSession.createDisplaySession( - windowContextToken); - session.setDisplayId(virtualDisplay.getDisplay().getDisplayId()); - // TODO(b/216625226) handle task recording. - // Successfully set up, so save the current session details. - WindowManagerGlobal.getWindowManagerService().setContentRecordingSession(session); - } - - /** * Stops projection. */ public void stop() { diff --git a/media/java/android/media/tv/AitInfo.java b/media/java/android/media/tv/AitInfo.java index 8e80a62be3de..c88a2b5048df 100644 --- a/media/java/android/media/tv/AitInfo.java +++ b/media/java/android/media/tv/AitInfo.java @@ -17,7 +17,7 @@ package android.media.tv; import android.annotation.NonNull; -import android.media.tv.interactive.TvInteractiveAppInfo; +import android.media.tv.interactive.TvInteractiveAppServiceInfo; import android.os.Parcel; import android.os.Parcelable; @@ -50,7 +50,7 @@ public final class AitInfo implements Parcelable { /** * Constructs AIT info. */ - public AitInfo(@TvInteractiveAppInfo.InteractiveAppType int type, int version) { + public AitInfo(@TvInteractiveAppServiceInfo.InteractiveAppType int type, int version) { mType = type; mVersion = version; } @@ -58,7 +58,7 @@ public final class AitInfo implements Parcelable { /** * Gets interactive app type. */ - @TvInteractiveAppInfo.InteractiveAppType + @TvInteractiveAppServiceInfo.InteractiveAppType public int getType() { return mType; } diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppClient.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppClient.aidl index a3e58d16f655..c8c6f66aa0ed 100644 --- a/media/java/android/media/tv/interactive/ITvInteractiveAppClient.aidl +++ b/media/java/android/media/tv/interactive/ITvInteractiveAppClient.aidl @@ -44,5 +44,7 @@ oneway interface ITvInteractiveAppClient { void onRequestStreamVolume(int seq); void onRequestTrackInfoList(int seq); void onRequestCurrentTvInputId(int seq); + void onRequestSigning( + in String id, in String algorithm, in String alias, in byte[] data, int seq); void onAdRequest(in AdRequest request, int Seq); } diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppManager.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppManager.aidl index aaabe342d9f1..eb012721445c 100644 --- a/media/java/android/media/tv/interactive/ITvInteractiveAppManager.aidl +++ b/media/java/android/media/tv/interactive/ITvInteractiveAppManager.aidl @@ -23,7 +23,7 @@ import android.media.tv.TvTrackInfo; import android.media.tv.interactive.AppLinkInfo; import android.media.tv.interactive.ITvInteractiveAppClient; import android.media.tv.interactive.ITvInteractiveAppManagerCallback; -import android.media.tv.interactive.TvInteractiveAppInfo; +import android.media.tv.interactive.TvInteractiveAppServiceInfo; import android.net.Uri; import android.os.Bundle; import android.view.Surface; @@ -33,7 +33,7 @@ import android.view.Surface; * @hide */ interface ITvInteractiveAppManager { - List<TvInteractiveAppInfo> getTvInteractiveAppServiceList(int userId); + List<TvInteractiveAppServiceInfo> getTvInteractiveAppServiceList(int userId); void prepare(String tiasId, int type, int userId); void registerAppLinkInfo(String tiasId, in AppLinkInfo info, int userId); void unregisterAppLinkInfo(String tiasId, in AppLinkInfo info, int userId); @@ -50,6 +50,8 @@ interface ITvInteractiveAppManager { void sendStreamVolume(in IBinder sessionToken, float volume, int userId); void sendTrackInfoList(in IBinder sessionToken, in List<TvTrackInfo> tracks, int userId); void sendCurrentTvInputId(in IBinder sessionToken, in String inputId, int userId); + void sendSigningResult(in IBinder sessionToken, in String signingId, in byte[] result, + int userId); void createSession(in ITvInteractiveAppClient client, in String iAppServiceId, int type, int seq, int userId); void releaseSession(in IBinder sessionToken, int userId); diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl index 23be4c64fcc4..f410c0fac488 100644 --- a/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl +++ b/media/java/android/media/tv/interactive/ITvInteractiveAppManagerCallback.aidl @@ -16,7 +16,7 @@ package android.media.tv.interactive; -import android.media.tv.interactive.TvInteractiveAppInfo; +import android.media.tv.interactive.TvInteractiveAppServiceInfo; /** * Interface to receive callbacks from ITvInteractiveAppManager regardless of sessions. @@ -26,6 +26,6 @@ interface ITvInteractiveAppManagerCallback { void onInteractiveAppServiceAdded(in String iAppServiceId); void onInteractiveAppServiceRemoved(in String iAppServiceId); void onInteractiveAppServiceUpdated(in String iAppServiceId); - void onTvInteractiveAppInfoUpdated(in TvInteractiveAppInfo tvIAppInfo); + void onTvInteractiveAppServiceInfoUpdated(in TvInteractiveAppServiceInfo tvIAppInfo); void onStateChanged(in String iAppServiceId, int type, int state, int err); }
\ No newline at end of file diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppSession.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppSession.aidl index c449d2475428..c784b09e87fc 100644 --- a/media/java/android/media/tv/interactive/ITvInteractiveAppSession.aidl +++ b/media/java/android/media/tv/interactive/ITvInteractiveAppSession.aidl @@ -42,6 +42,7 @@ oneway interface ITvInteractiveAppSession { void sendStreamVolume(float volume); void sendTrackInfoList(in List<TvTrackInfo> tracks); void sendCurrentTvInputId(in String inputId); + void sendSigningResult(in String signingId, in byte[] result); void release(); void notifyTuned(in Uri channelUri); void notifyTrackSelected(int type, in String trackId); diff --git a/media/java/android/media/tv/interactive/ITvInteractiveAppSessionCallback.aidl b/media/java/android/media/tv/interactive/ITvInteractiveAppSessionCallback.aidl index 385f0d4f766a..f74b2bac957b 100644 --- a/media/java/android/media/tv/interactive/ITvInteractiveAppSessionCallback.aidl +++ b/media/java/android/media/tv/interactive/ITvInteractiveAppSessionCallback.aidl @@ -43,5 +43,6 @@ oneway interface ITvInteractiveAppSessionCallback { void onRequestStreamVolume(); void onRequestTrackInfoList(); void onRequestCurrentTvInputId(); + void onRequestSigning(in String id, in String algorithm, in String alias, in byte[] data); void onAdRequest(in AdRequest request); } diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppManager.java b/media/java/android/media/tv/interactive/TvInteractiveAppManager.java index 9eb4a6c393ab..90f32593ed78 100755 --- a/media/java/android/media/tv/interactive/TvInteractiveAppManager.java +++ b/media/java/android/media/tv/interactive/TvInteractiveAppManager.java @@ -249,7 +249,7 @@ public final class TvInteractiveAppManager { * * @see #sendAppLinkCommand(String, Bundle) * @see #ACTION_APP_LINK_COMMAND - * @see android.media.tv.interactive.TvInteractiveAppInfo#getId() + * @see TvInteractiveAppServiceInfo#getId() */ public static final String INTENT_KEY_INTERACTIVE_APP_SERVICE_ID = "interactive_app_id"; @@ -269,7 +269,7 @@ public final class TvInteractiveAppManager { * * @see #sendAppLinkCommand(String, Bundle) * @see #ACTION_APP_LINK_COMMAND - * @see android.media.tv.interactive.TvInteractiveAppInfo#getSupportedTypes() + * @see android.media.tv.interactive.TvInteractiveAppServiceInfo#getSupportedTypes() * @see android.media.tv.interactive.TvInteractiveAppView#createBiInteractiveApp(Uri, Bundle) */ public static final String INTENT_KEY_BI_INTERACTIVE_APP_TYPE = "bi_interactive_app_type"; @@ -285,6 +285,16 @@ public final class TvInteractiveAppManager { */ public static final String INTENT_KEY_BI_INTERACTIVE_APP_URI = "bi_interactive_app_uri"; + /** + * Intent key for command type. It's used to send app command to TV app. The value of this key + * could vary according to TV apps. + * <p>Type: String + * + * @see #sendAppLinkCommand(String, Bundle) + * @see #ACTION_APP_LINK_COMMAND + */ + public static final String INTENT_KEY_COMMAND_TYPE = "command_type"; + private final ITvInteractiveAppManager mService; private final int mUserId; @@ -478,6 +488,19 @@ public final class TvInteractiveAppManager { } @Override + public void onRequestSigning( + String id, String algorithm, String alias, byte[] data, int seq) { + synchronized (mSessionCallbackRecordMap) { + SessionCallbackRecord record = mSessionCallbackRecordMap.get(seq); + if (record == null) { + Log.e(TAG, "Callback not found for seq " + seq); + return; + } + record.postRequestSigning(id, algorithm, alias, data); + } + } + + @Override public void onSessionStateChanged(int state, int err, int seq) { synchronized (mSessionCallbackRecordMap) { SessionCallbackRecord record = mSessionCallbackRecordMap.get(seq); @@ -543,11 +566,11 @@ public final class TvInteractiveAppManager { } @Override - public void onTvInteractiveAppInfoUpdated(TvInteractiveAppInfo iAppInfo) { + public void onTvInteractiveAppServiceInfoUpdated(TvInteractiveAppServiceInfo iAppInfo) { // TODO: add public API updateInteractiveAppInfo() synchronized (mLock) { for (TvInteractiveAppCallbackRecord record : mCallbackRecords) { - record.postTvInteractiveAppInfoUpdated(iAppInfo); + record.postTvInteractiveAppServiceInfoUpdated(iAppInfo); } } } @@ -611,16 +634,17 @@ public final class TvInteractiveAppManager { * This is called when the information about an existing TV Interactive App service has been * updated. * - * <p>Because the system automatically creates a <code>TvInteractiveAppInfo</code> object - * for each TV Interactive App service based on the information collected from the + * <p>Because the system automatically creates a <code>TvInteractiveAppServiceInfo</code> + * object for each TV Interactive App service based on the information collected from the * <code>AndroidManifest.xml</code>, this method is only called back when such information * has changed dynamically. * - * @param iAppInfo The <code>TvInteractiveAppInfo</code> object that contains new + * @param iAppInfo The <code>TvInteractiveAppServiceInfo</code> object that contains new * information. * @hide */ - public void onTvInteractiveAppInfoUpdated(@NonNull TvInteractiveAppInfo iAppInfo) { + public void onTvInteractiveAppServiceInfoUpdated( + @NonNull TvInteractiveAppServiceInfo iAppInfo) { } /** @@ -634,7 +658,7 @@ public final class TvInteractiveAppManager { */ public void onTvInteractiveAppServiceStateChanged( @NonNull String iAppServiceId, - @TvInteractiveAppInfo.InteractiveAppType int type, + @TvInteractiveAppServiceInfo.InteractiveAppType int type, @ServiceState int state, @ErrorCode int err) { } @@ -680,11 +704,12 @@ public final class TvInteractiveAppManager { }); } - public void postTvInteractiveAppInfoUpdated(final TvInteractiveAppInfo iAppInfo) { + public void postTvInteractiveAppServiceInfoUpdated( + final TvInteractiveAppServiceInfo iAppInfo) { mExecutor.execute(new Runnable() { @Override public void run() { - mCallback.onTvInteractiveAppInfoUpdated(iAppInfo); + mCallback.onTvInteractiveAppServiceInfoUpdated(iAppInfo); } }); } @@ -737,11 +762,11 @@ public final class TvInteractiveAppManager { /** * Returns the complete list of TV Interactive App service on the system. * - * @return List of {@link TvInteractiveAppInfo} for each TV Interactive App service that + * @return List of {@link TvInteractiveAppServiceInfo} for each TV Interactive App service that * describes its meta information. */ @NonNull - public List<TvInteractiveAppInfo> getTvInteractiveAppServiceList() { + public List<TvInteractiveAppServiceInfo> getTvInteractiveAppServiceList() { try { return mService.getTvInteractiveAppServiceList(mUserId); } catch (RemoteException e) { @@ -1022,6 +1047,18 @@ public final class TvInteractiveAppManager { } } + void sendSigningResult(@NonNull String signingId, @NonNull byte[] result) { + if (mToken == null) { + Log.w(TAG, "The session has been already released"); + return; + } + try { + mService.sendSigningResult(mToken, signingId, result, mUserId); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + /** * Sets the {@link android.view.Surface} for this session. * @@ -1655,6 +1692,15 @@ public final class TvInteractiveAppManager { }); } + void postRequestSigning(String id, String algorithm, String alias, byte[] data) { + mHandler.post(new Runnable() { + @Override + public void run() { + mSessionCallback.onRequestSigning(mSession, id, algorithm, alias, data); + } + }); + } + void postAdRequest(final AdRequest request) { mHandler.post(new Runnable() { @Override @@ -1792,12 +1838,27 @@ public final class TvInteractiveAppManager { * called. * * @param session A {@link TvInteractiveAppService.Session} associated with this callback. - * @hide */ public void onRequestCurrentTvInputId(Session session) { } /** + * This is called when + * {@link TvInteractiveAppService.Session#requestSigning(String, String, String, byte[])} is + * called. + * + * @param session A {@link TvInteractiveAppService.Session} associated with this callback. + * @param signingId the ID to identify the request. + * @param algorithm the standard name of the signature algorithm requested, such as + * MD5withRSA, SHA256withDSA, etc. + * @param alias the alias of the corresponding {@link java.security.KeyStore}. + * @param data the original bytes to be signed. + */ + public void onRequestSigning( + Session session, String signingId, String algorithm, String alias, byte[] data) { + } + + /** * This is called when {@link TvInteractiveAppService.Session#notifySessionStateChanged} is * called. * diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppService.java b/media/java/android/media/tv/interactive/TvInteractiveAppService.java index d22fd83872e1..100c6d3947bb 100755 --- a/media/java/android/media/tv/interactive/TvInteractiveAppService.java +++ b/media/java/android/media/tv/interactive/TvInteractiveAppService.java @@ -242,7 +242,7 @@ public abstract class TvInteractiveAppService extends Service { /** * Prepares TV Interactive App service for the given type. */ - public abstract void onPrepare(@TvInteractiveAppInfo.InteractiveAppType int type); + public abstract void onPrepare(@TvInteractiveAppServiceInfo.InteractiveAppType int type); /** * Called when a request to register an Android application link info record is received. @@ -277,7 +277,7 @@ public abstract class TvInteractiveAppService extends Service { @Nullable public abstract Session onCreateSession( @NonNull String iAppServiceId, - @TvInteractiveAppInfo.InteractiveAppType int type); + @TvInteractiveAppServiceInfo.InteractiveAppType int type); /** * Notifies the system when the state of the interactive app RTE has been changed. @@ -289,7 +289,7 @@ public abstract class TvInteractiveAppService extends Service { * {@link TvInteractiveAppManager#SERVICE_STATE_ERROR}. */ public final void notifyStateChanged( - @TvInteractiveAppInfo.InteractiveAppType int type, + @TvInteractiveAppServiceInfo.InteractiveAppType int type, @TvInteractiveAppManager.ServiceState int state, @TvInteractiveAppManager.ErrorCode int error) { SomeArgs args = SomeArgs.obtain(); @@ -452,6 +452,17 @@ public abstract class TvInteractiveAppService extends Service { } /** + * Receives signing result. + * @param signingId the ID to identify the request. It's the same as the corresponding ID in + * {@link Session#requestSigning(String, String, String, byte[])} + * @param result the signed result. + * + * @see #requestSigning(String, String, String, byte[]) + */ + public void onSigningResult(@NonNull String signingId, @NonNull byte[] result) { + } + + /** * Called when the application sets the surface. * * <p>The TV Interactive App service should render interactive app UI onto the given @@ -877,6 +888,47 @@ public abstract class TvInteractiveAppService extends Service { } /** + * Requests signing of the given data. + * + * <p>This is used when the corresponding server of the broadcast-independent interactive + * app requires signing during handshaking, and the interactive app service doesn't have + * the built-in private key. The private key is provided by the content providers and + * pre-built in the related app, such as TV app. + * + * @param signingId the ID to identify the request. When a result is received, this ID can + * be used to correlate the result with the request. + * @param algorithm the standard name of the signature algorithm requested, such as + * MD5withRSA, SHA256withDSA, etc. The name is from standards like + * FIPS PUB 186-4 and PKCS #1. + * @param alias the alias of the corresponding {@link java.security.KeyStore}. + * @param data the original bytes to be signed. + * + * @see #onSigningResult(String, byte[]) + * @see TvInteractiveAppView#createBiInteractiveApp(Uri, Bundle) + * @see TvInteractiveAppView#BI_INTERACTIVE_APP_KEY_ALIAS + */ + @CallSuper + public void requestSigning(@NonNull String signingId, @NonNull String algorithm, + @NonNull String alias, @NonNull byte[] data) { + executeOrPostRunnableOnMainThread(new Runnable() { + @MainThread + @Override + public void run() { + try { + if (DEBUG) { + Log.d(TAG, "requestSigning"); + } + if (mSessionCallback != null) { + mSessionCallback.onRequestSigning(signingId, algorithm, alias, data); + } + } catch (RemoteException e) { + Log.w(TAG, "error in requestSigning", e); + } + } + }); + } + + /** * Sends an advertisement request to be processed by the related TV input. * * @param request The advertisement request @@ -945,6 +997,10 @@ public abstract class TvInteractiveAppService extends Service { onCurrentTvInputId(inputId); } + void sendSigningResult(String signingId, byte[] result) { + onSigningResult(signingId, result); + } + void release() { onRelease(); if (mSurface != null) { @@ -1413,6 +1469,11 @@ public abstract class TvInteractiveAppService extends Service { } @Override + public void sendSigningResult(@NonNull String signingId, @NonNull byte[] result) { + mSessionImpl.sendSigningResult(signingId, result); + } + + @Override public void release() { mSessionImpl.scheduleMediaViewCleanup(); mSessionImpl.release(); diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppInfo.aidl b/media/java/android/media/tv/interactive/TvInteractiveAppServiceInfo.aidl index 5e1501677b3b..49600a05cb7f 100644 --- a/media/java/android/media/tv/interactive/TvInteractiveAppInfo.aidl +++ b/media/java/android/media/tv/interactive/TvInteractiveAppServiceInfo.aidl @@ -16,4 +16,4 @@ package android.media.tv.interactive; -parcelable TvInteractiveAppInfo;
\ No newline at end of file +parcelable TvInteractiveAppServiceInfo;
\ No newline at end of file diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppInfo.java b/media/java/android/media/tv/interactive/TvInteractiveAppServiceInfo.java index 6103db001b19..9c1b2425c013 100644 --- a/media/java/android/media/tv/interactive/TvInteractiveAppInfo.java +++ b/media/java/android/media/tv/interactive/TvInteractiveAppServiceInfo.java @@ -45,9 +45,9 @@ import java.util.List; /** * This class is used to specify meta information of a TV interactive app. */ -public final class TvInteractiveAppInfo implements Parcelable { +public final class TvInteractiveAppServiceInfo implements Parcelable { private static final boolean DEBUG = false; - private static final String TAG = "TvInteractiveAppInfo"; + private static final String TAG = "TvInteractiveAppServiceInfo"; private static final String XML_START_TAG_NAME = "tv-interactive-app"; @@ -71,7 +71,7 @@ public final class TvInteractiveAppInfo implements Parcelable { private final String mId; private int mTypes; - public TvInteractiveAppInfo(@NonNull Context context, @NonNull ComponentName component) { + public TvInteractiveAppServiceInfo(@NonNull Context context, @NonNull ComponentName component) { if (context == null) { throw new IllegalArgumentException("context cannot be null."); } @@ -94,28 +94,28 @@ public final class TvInteractiveAppInfo implements Parcelable { mId = id; mTypes = toTypesFlag(types); } - private TvInteractiveAppInfo(ResolveInfo service, String id, int types) { + private TvInteractiveAppServiceInfo(ResolveInfo service, String id, int types) { mService = service; mId = id; mTypes = types; } - private TvInteractiveAppInfo(@NonNull Parcel in) { + private TvInteractiveAppServiceInfo(@NonNull Parcel in) { mService = ResolveInfo.CREATOR.createFromParcel(in); mId = in.readString(); mTypes = in.readInt(); } - public static final @NonNull Creator<TvInteractiveAppInfo> CREATOR = - new Creator<TvInteractiveAppInfo>() { + public static final @NonNull Creator<TvInteractiveAppServiceInfo> CREATOR = + new Creator<TvInteractiveAppServiceInfo>() { @Override - public TvInteractiveAppInfo createFromParcel(Parcel in) { - return new TvInteractiveAppInfo(in); + public TvInteractiveAppServiceInfo createFromParcel(Parcel in) { + return new TvInteractiveAppServiceInfo(in); } @Override - public TvInteractiveAppInfo[] newArray(int size) { - return new TvInteractiveAppInfo[size]; + public TvInteractiveAppServiceInfo[] newArray(int size) { + return new TvInteractiveAppServiceInfo[size]; } }; diff --git a/media/java/android/media/tv/interactive/TvInteractiveAppView.java b/media/java/android/media/tv/interactive/TvInteractiveAppView.java index 773e54f30744..8fc5d807c7df 100755 --- a/media/java/android/media/tv/interactive/TvInteractiveAppView.java +++ b/media/java/android/media/tv/interactive/TvInteractiveAppView.java @@ -46,6 +46,7 @@ import android.view.View; import android.view.ViewGroup; import android.view.ViewRootImpl; +import java.security.KeyStore; import java.util.List; import java.util.concurrent.Executor; @@ -61,6 +62,28 @@ public class TvInteractiveAppView extends ViewGroup { private static final int UNSET_TVVIEW_SUCCESS = 3; private static final int UNSET_TVVIEW_FAIL = 4; + /** + * Used to share client {@link java.security.cert.Certificate} with + * {@link TvInteractiveAppService}. + * @see #createBiInteractiveApp(Uri, Bundle) + * @see java.security.cert.Certificate + */ + public static final String BI_INTERACTIVE_APP_KEY_CERTIFICATE = "certificate"; + /** + * Used to share the {@link KeyStore} alias with {@link TvInteractiveAppService}. + * @see #createBiInteractiveApp(Uri, Bundle) + * @see KeyStore#aliases() + */ + public static final String BI_INTERACTIVE_APP_KEY_ALIAS = "alias"; + /** + * Used to share the {@link java.security.PrivateKey} with {@link TvInteractiveAppService}. + * <p>The private key is optional. It is used to encrypt data when necessary. + * + * @see #createBiInteractiveApp(Uri, Bundle) + * @see java.security.PrivateKey + */ + public static final String BI_INTERACTIVE_APP_KEY_PRIVATE_KEY = "private_key"; + private final TvInteractiveAppManager mTvInteractiveAppManager; private final Handler mHandler = new Handler(); private final Object mCallbackLock = new Object(); @@ -148,12 +171,14 @@ public class TvInteractiveAppView extends ViewGroup { /** * Sets the callback to be invoked when an event is dispatched to this TvInteractiveAppView. * - * @param callback The callback to receive events. A value of {@code null} removes the existing - * callback. + * @param callback the callback to receive events. MUST NOT be {@code null}. + * + * @see #clearCallback() */ public void setCallback( @NonNull @CallbackExecutor Executor executor, @NonNull TvInteractiveAppCallback callback) { + com.android.internal.util.AnnotationValidations.validate(NonNull.class, null, callback); synchronized (mCallbackLock) { mCallbackExecutor = executor; mCallback = callback; @@ -162,6 +187,8 @@ public class TvInteractiveAppView extends ViewGroup { /** * Clears the callback. + * + * @see #setCallback(Executor, TvInteractiveAppCallback) */ public void clearCallback() { synchronized (mCallbackLock) { @@ -389,13 +416,13 @@ public class TvInteractiveAppView extends ViewGroup { * Prepares the interactive application. * * @param iAppServiceId the interactive app service ID, which can be found in - * {@link TvInteractiveAppInfo#getId()}. + * {@link TvInteractiveAppServiceInfo#getId()}. * * @see android.media.tv.interactive.TvInteractiveAppManager#getTvInteractiveAppServiceList() */ public void prepareInteractiveApp( @NonNull String iAppServiceId, - @TvInteractiveAppInfo.InteractiveAppType int type) { + @TvInteractiveAppServiceInfo.InteractiveAppType int type) { // TODO: document and handle the cases that this method is called multiple times. if (DEBUG) { Log.d(TAG, "prepareInteractiveApp"); @@ -509,6 +536,27 @@ public class TvInteractiveAppView extends ViewGroup { } } + /** + * Sends signing result to related TV interactive app. + * + * <p>This is used when the corresponding server of the broadcast-independent interactive + * app requires signing during handshaking, and the interactive app service doesn't have + * the built-in private key. The private key is provided by the content providers and + * pre-built in the related app, such as TV app. + * + * @param signingId the ID to identify the request. It's the same as the corresponding ID in + * {@link TvInteractiveAppService.Session#requestSigning(String, String, String, byte[])} + * @param result the signed result. + */ + public void sendSigningResult(@NonNull String signingId, @NonNull byte[] result) { + if (DEBUG) { + Log.d(TAG, "sendSigningResult"); + } + if (mSession != null) { + mSession.sendSigningResult(signingId, result); + } + } + private void resetInternal() { mSessionCallback = null; if (mSession != null) { @@ -721,6 +769,22 @@ public class TvInteractiveAppView extends ViewGroup { public void onRequestCurrentTvInputId(@NonNull String iAppServiceId) { } + /** + * This is called when + * {@link TvInteractiveAppService.Session#requestSigning(String, String, String, byte[])} is + * called. + * + * @param iAppServiceId The ID of the TV interactive app service bound to this view. + * @param signingId the ID to identify the request. + * @param algorithm the standard name of the signature algorithm requested, such as + * MD5withRSA, SHA256withDSA, etc. + * @param alias the alias of the corresponding {@link java.security.KeyStore}. + * @param data the original bytes to be signed. + */ + public void onRequestSigning(@NonNull String iAppServiceId, @NonNull String signingId, + @NonNull String algorithm, @NonNull String alias, @NonNull byte[] data) { + } + } /** @@ -1027,5 +1091,20 @@ public class TvInteractiveAppView extends ViewGroup { mCallback.onRequestCurrentTvInputId(mIAppServiceId); } } + + @Override + public void onRequestSigning( + Session session, String id, String algorithm, String alias, byte[] data) { + if (DEBUG) { + Log.d(TAG, "onRequestSigning"); + } + if (this != mSessionCallback) { + Log.w(TAG, "onRequestSigning - session not created"); + return; + } + if (mCallback != null) { + mCallback.onRequestSigning(mIAppServiceId, id, algorithm, alias, data); + } + } } } diff --git a/packages/ConnectivityT/framework-t/Android.bp b/packages/ConnectivityT/framework-t/Android.bp index 217a1f67c336..bc278528570f 100644 --- a/packages/ConnectivityT/framework-t/Android.bp +++ b/packages/ConnectivityT/framework-t/Android.bp @@ -131,8 +131,8 @@ filegroup { "src/android/net/EthernetNetworkUpdateRequest.java", "src/android/net/EthernetNetworkUpdateRequest.aidl", "src/android/net/IEthernetManager.aidl", - "src/android/net/IEthernetNetworkManagementListener.aidl", "src/android/net/IEthernetServiceListener.aidl", + "src/android/net/INetworkInterfaceOutcomeReceiver.aidl", "src/android/net/ITetheredInterfaceCallback.aidl", ], path: "src", diff --git a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java index 2b6570a6ecb0..74fe4bd46cde 100644 --- a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java +++ b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStats.java @@ -17,6 +17,7 @@ package android.app.usage; import android.annotation.IntDef; +import android.annotation.Nullable; import android.content.Context; import android.net.INetworkStatsService; import android.net.INetworkStatsSession; @@ -474,10 +475,11 @@ public final class NetworkStats implements AutoCloseable { /** * Fills the recycled bucket with data of the next bin in the enumeration. - * @param bucketOut Bucket to be filled with data. + * @param bucketOut Bucket to be filled with data. If null, the method does + * nothing and returning false. * @return true if successfully filled the bucket, false otherwise. */ - public boolean getNextBucket(Bucket bucketOut) { + public boolean getNextBucket(@Nullable Bucket bucketOut) { if (mSummary != null) { return getNextSummaryBucket(bucketOut); } else { @@ -651,7 +653,7 @@ public final class NetworkStats implements AutoCloseable { * @param bucketOut Next item will be set here. * @return true if a next item could be set. */ - private boolean getNextSummaryBucket(Bucket bucketOut) { + private boolean getNextSummaryBucket(@Nullable Bucket bucketOut) { if (bucketOut != null && mEnumerationIndex < mSummary.size()) { mRecycledSummaryEntry = mSummary.getValues(mEnumerationIndex++, mRecycledSummaryEntry); fillBucketFromSummaryEntry(bucketOut); @@ -678,7 +680,7 @@ public final class NetworkStats implements AutoCloseable { * @param bucketOut Next item will be set here. * @return true if a next item could be set. */ - private boolean getNextHistoryBucket(Bucket bucketOut) { + private boolean getNextHistoryBucket(@Nullable Bucket bucketOut) { if (bucketOut != null && mHistory != null) { if (mEnumerationIndex < mHistory.size()) { mRecycledHistoryEntry = mHistory.getValues(mEnumerationIndex++, diff --git a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java index bf518b2d5a29..f41475bea190 100644 --- a/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java +++ b/packages/ConnectivityT/framework-t/src/android/app/usage/NetworkStatsManager.java @@ -290,7 +290,7 @@ public class NetworkStatsManager { * statistics collection. */ @WorkerThread - public Bucket querySummaryForDevice(int networkType, String subscriberId, + public Bucket querySummaryForDevice(int networkType, @Nullable String subscriberId, long startTime, long endTime) throws SecurityException, RemoteException { NetworkTemplate template; try { @@ -335,8 +335,8 @@ public class NetworkStatsManager { * statistics collection. */ @WorkerThread - public Bucket querySummaryForUser(int networkType, String subscriberId, long startTime, - long endTime) throws SecurityException, RemoteException { + public Bucket querySummaryForUser(int networkType, @Nullable String subscriberId, + long startTime, long endTime) throws SecurityException, RemoteException { NetworkTemplate template; try { template = createTemplate(networkType, subscriberId); @@ -384,7 +384,7 @@ public class NetworkStatsManager { * statistics collection. */ @WorkerThread - public NetworkStats querySummary(int networkType, String subscriberId, long startTime, + public NetworkStats querySummary(int networkType, @Nullable String subscriberId, long startTime, long endTime) throws SecurityException, RemoteException { NetworkTemplate template; try { @@ -508,15 +508,17 @@ public class NetworkStatsManager { * * @see #queryDetailsForUidTagState(int, String, long, long, int, int, int) */ + @NonNull @WorkerThread - public NetworkStats queryDetailsForUid(int networkType, String subscriberId, + public NetworkStats queryDetailsForUid(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid) throws SecurityException { return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid, NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL); } /** @hide */ - public NetworkStats queryDetailsForUid(NetworkTemplate template, + @NonNull + public NetworkStats queryDetailsForUid(@NonNull NetworkTemplate template, long startTime, long endTime, int uid) throws SecurityException { return queryDetailsForUidTagState(template, startTime, endTime, uid, NetworkStats.Bucket.TAG_NONE, NetworkStats.Bucket.STATE_ALL); @@ -524,23 +526,59 @@ public class NetworkStatsManager { /** * Query network usage statistics details for a given uid and tag. + * + * This may take a long time, and apps should avoid calling this on their main thread. + * Only usable for uids belonging to calling user. Result is not aggregated over time. + * This means buckets' start and end timestamps are going to be between 'startTime' and + * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag + * the same as the 'tag' parameter, and the state the same as the 'state' parameter. + * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL}, + * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and + * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}. + * <p>Only includes buckets that atomically occur in the inclusive time range. Doesn't + * interpolate across partial buckets. Since bucket length is in the order of hours, this + * method cannot be used to measure data usage on a fine grained time scale. * This may take a long time, and apps should avoid calling this on their main thread. * - * @see #queryDetailsForUidTagState(int, String, long, long, int, int, int) + * @param networkType As defined in {@link ConnectivityManager}, e.g. + * {@link ConnectivityManager#TYPE_MOBILE}, {@link ConnectivityManager#TYPE_WIFI} + * etc. + * @param subscriberId If applicable, the subscriber id of the network interface. + * <p>Starting with API level 29, the {@code subscriberId} is guarded by + * additional restrictions. Calling apps that do not meet the new + * requirements to access the {@code subscriberId} can provide a {@code + * null} value when querying for the mobile network type to receive usage + * for all mobile networks. For additional details see {@link + * TelephonyManager#getSubscriberId()}. + * <p>Starting with API level 31, calling apps can provide a + * {@code subscriberId} with wifi network type to receive usage for + * wifi networks which is under the given subscription if applicable. + * Otherwise, pass {@code null} when querying all wifi networks. + * @param startTime Start of period. Defined in terms of "Unix time", see + * {@link java.lang.System#currentTimeMillis}. + * @param endTime End of period. Defined in terms of "Unix time", see + * {@link java.lang.System#currentTimeMillis}. + * @param uid UID of app + * @param tag TAG of interest. Use {@link NetworkStats.Bucket#TAG_NONE} for aggregated data + * across all the tags. + * @return Statistics which is described above. + * @throws SecurityException if permissions are insufficient to read network statistics. */ + @NonNull @WorkerThread - public NetworkStats queryDetailsForUidTag(int networkType, String subscriberId, + public NetworkStats queryDetailsForUidTag(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag) throws SecurityException { return queryDetailsForUidTagState(networkType, subscriberId, startTime, endTime, uid, tag, NetworkStats.Bucket.STATE_ALL); } /** - * Query network usage statistics details for a given uid, tag, and state. Only usable for uids - * belonging to calling user. Result is not aggregated over time. This means buckets' start and - * end timestamps are going to be between 'startTime' and 'endTime' parameters. The uid is going - * to be the same as the 'uid' parameter, the tag the same as the 'tag' parameter, and the state - * the same as the 'state' parameter. + * Query network usage statistics details for a given uid, tag, and state. + * + * Only usable for uids belonging to calling user. Result is not aggregated over time. + * This means buckets' start and end timestamps are going to be between 'startTime' and + * 'endTime' parameters. The uid is going to be the same as the 'uid' parameter, the tag + * the same as the 'tag' parameter, and the state the same as the 'state' parameter. * defaultNetwork is going to be {@link NetworkStats.Bucket#DEFAULT_NETWORK_ALL}, * metered is going to be {@link NetworkStats.Bucket#METERED_ALL}, and * roaming is going to be {@link NetworkStats.Bucket#ROAMING_ALL}. @@ -572,11 +610,12 @@ public class NetworkStatsManager { * across all the tags. * @param state state of interest. Use {@link NetworkStats.Bucket#STATE_ALL} to aggregate * traffic from all states. - * @return Statistics object or null if an error happened during statistics collection. + * @return Statistics which is described above. * @throws SecurityException if permissions are insufficient to read network statistics. */ + @NonNull @WorkerThread - public NetworkStats queryDetailsForUidTagState(int networkType, String subscriberId, + public NetworkStats queryDetailsForUidTagState(int networkType, @Nullable String subscriberId, long startTime, long endTime, int uid, int tag, int state) throws SecurityException { NetworkTemplate template; template = createTemplate(networkType, subscriberId); @@ -669,7 +708,7 @@ public class NetworkStatsManager { * statistics collection. */ @WorkerThread - public NetworkStats queryDetails(int networkType, String subscriberId, long startTime, + public NetworkStats queryDetails(int networkType, @Nullable String subscriberId, long startTime, long endTime) throws SecurityException, RemoteException { NetworkTemplate template; try { @@ -698,7 +737,7 @@ public class NetworkStatsManager { * * @hide */ - @SystemApi + @SystemApi(client = MODULE_LIBRARIES) @RequiresPermission(anyOf = { NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) @@ -724,7 +763,7 @@ public class NetworkStatsManager { * * @hide */ - @SystemApi + @SystemApi(client = MODULE_LIBRARIES) @RequiresPermission(anyOf = { NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, android.Manifest.permission.NETWORK_STACK}) @@ -785,10 +824,28 @@ public class NetworkStatsManager { /** * Registers to receive notifications about data usage on specified networks. * - * @see #registerUsageCallback(int, String, long, UsageCallback, Handler) + * <p>The callbacks will continue to be called as long as the process is live or + * {@link #unregisterUsageCallback} is called. + * + * @param networkType Type of network to monitor. Either + {@link ConnectivityManager#TYPE_MOBILE} or {@link ConnectivityManager#TYPE_WIFI}. + * @param subscriberId If applicable, the subscriber id of the network interface. + * <p>Starting with API level 29, the {@code subscriberId} is guarded by + * additional restrictions. Calling apps that do not meet the new + * requirements to access the {@code subscriberId} can provide a {@code + * null} value when registering for the mobile network type to receive + * notifications for all mobile networks. For additional details see {@link + * TelephonyManager#getSubscriberId()}. + * <p>Starting with API level 31, calling apps can provide a + * {@code subscriberId} with wifi network type to receive usage for + * wifi networks which is under the given subscription if applicable. + * Otherwise, pass {@code null} when querying all wifi networks. + * @param thresholdBytes Threshold in bytes to be notified on. + * @param callback The {@link UsageCallback} that the system will call when data usage + * has exceeded the specified threshold. */ - public void registerUsageCallback(int networkType, String subscriberId, long thresholdBytes, - UsageCallback callback) { + public void registerUsageCallback(int networkType, @Nullable String subscriberId, + long thresholdBytes, @NonNull UsageCallback callback) { registerUsageCallback(networkType, subscriberId, thresholdBytes, callback, null /* handler */); } @@ -818,8 +875,8 @@ public class NetworkStatsManager { * @param handler to dispatch callback events through, otherwise if {@code null} it uses * the calling thread. */ - public void registerUsageCallback(int networkType, String subscriberId, long thresholdBytes, - UsageCallback callback, @Nullable Handler handler) { + public void registerUsageCallback(int networkType, @Nullable String subscriberId, + long thresholdBytes, @NonNull UsageCallback callback, @Nullable Handler handler) { NetworkTemplate template = createTemplate(networkType, subscriberId); if (DBG) { Log.d(TAG, "registerUsageCallback called with: {" @@ -839,7 +896,7 @@ public class NetworkStatsManager { * * @param callback The {@link UsageCallback} used when registering. */ - public void unregisterUsageCallback(UsageCallback callback) { + public void unregisterUsageCallback(@NonNull UsageCallback callback) { if (callback == null || callback.request == null || callback.request.requestId == DataUsageRequest.REQUEST_ID_UNSET) { throw new IllegalArgumentException("Invalid UsageCallback"); @@ -880,7 +937,7 @@ public class NetworkStatsManager { /** * Called when data usage has reached the given threshold. */ - public abstract void onThresholdReached(int networkType, String subscriberId); + public abstract void onThresholdReached(int networkType, @Nullable String subscriberId); /** * @hide used for internal bookkeeping @@ -924,7 +981,7 @@ public class NetworkStatsManager { @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_STATS_PROVIDER, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) - @NonNull public void registerNetworkStatsProvider( + public void registerNetworkStatsProvider( @NonNull String tag, @NonNull NetworkStatsProvider provider) { try { @@ -950,7 +1007,7 @@ public class NetworkStatsManager { @RequiresPermission(anyOf = { android.Manifest.permission.NETWORK_STATS_PROVIDER, NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK}) - @NonNull public void unregisterNetworkStatsProvider(@NonNull NetworkStatsProvider provider) { + public void unregisterNetworkStatsProvider(@NonNull NetworkStatsProvider provider) { try { provider.getProviderCallbackBinderOrThrow().unregister(); } catch (RemoteException e) { @@ -958,7 +1015,7 @@ public class NetworkStatsManager { } } - private static NetworkTemplate createTemplate(int networkType, String subscriberId) { + private static NetworkTemplate createTemplate(int networkType, @Nullable String subscriberId) { final NetworkTemplate template; switch (networkType) { case ConnectivityManager.TYPE_MOBILE: diff --git a/packages/ConnectivityT/framework-t/src/android/net/EthernetManager.java b/packages/ConnectivityT/framework-t/src/android/net/EthernetManager.java index 793f28d5aa59..9a4ad5f57dc2 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/EthernetManager.java +++ b/packages/ConnectivityT/framework-t/src/android/net/EthernetManager.java @@ -30,6 +30,7 @@ import android.compat.annotation.UnsupportedAppUsage; import android.content.Context; import android.content.pm.PackageManager; import android.os.Build; +import android.os.OutcomeReceiver; import android.os.RemoteException; import com.android.internal.annotations.GuardedBy; @@ -40,7 +41,7 @@ import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Objects; import java.util.concurrent.Executor; -import java.util.function.BiConsumer; +import java.util.function.IntConsumer; /** * A class that manages and configures Ethernet interfaces. @@ -53,15 +54,31 @@ public class EthernetManager { private static final String TAG = "EthernetManager"; private final IEthernetManager mService; - @GuardedBy("mListeners") - private final ArrayList<ListenerInfo> mListeners = new ArrayList<>(); + @GuardedBy("mListenerLock") + private final ArrayList<ListenerInfo<InterfaceStateListener>> mIfaceListeners = + new ArrayList<>(); + @GuardedBy("mListenerLock") + private final ArrayList<ListenerInfo<IntConsumer>> mEthernetStateListeners = + new ArrayList<>(); + final Object mListenerLock = new Object(); private final IEthernetServiceListener.Stub mServiceListener = new IEthernetServiceListener.Stub() { @Override + public void onEthernetStateChanged(int state) { + synchronized (mListenerLock) { + for (ListenerInfo<IntConsumer> li : mEthernetStateListeners) { + li.executor.execute(() -> { + li.listener.accept(state); + }); + } + } + } + + @Override public void onInterfaceStateChanged(String iface, int state, int role, IpConfiguration configuration) { - synchronized (mListeners) { - for (ListenerInfo li : mListeners) { + synchronized (mListenerLock) { + for (ListenerInfo<InterfaceStateListener> li : mIfaceListeners) { li.executor.execute(() -> li.listener.onInterfaceStateChanged(iface, state, role, configuration)); @@ -70,13 +87,29 @@ public class EthernetManager { } }; - private static class ListenerInfo { + /** + * Indicates that Ethernet is disabled. + * + * @hide + */ + @SystemApi(client = MODULE_LIBRARIES) + public static final int ETHERNET_STATE_DISABLED = 0; + + /** + * Indicates that Ethernet is enabled. + * + * @hide + */ + @SystemApi(client = MODULE_LIBRARIES) + public static final int ETHERNET_STATE_ENABLED = 1; + + private static class ListenerInfo<T> { @NonNull public final Executor executor; @NonNull - public final InterfaceStateListener listener; + public final T listener; - private ListenerInfo(@NonNull Executor executor, @NonNull InterfaceStateListener listener) { + private ListenerInfo(@NonNull Executor executor, @NonNull T listener) { this.executor = executor; this.listener = listener; } @@ -289,16 +322,22 @@ public class EthernetManager { if (listener == null || executor == null) { throw new NullPointerException("listener and executor must not be null"); } - synchronized (mListeners) { - mListeners.add(new ListenerInfo(executor, listener)); - if (mListeners.size() == 1) { - try { - mService.addListener(mServiceListener); - } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); - } - } + synchronized (mListenerLock) { + maybeAddServiceListener(); + mIfaceListeners.add(new ListenerInfo<InterfaceStateListener>(executor, listener)); + } + } + + @GuardedBy("mListenerLock") + private void maybeAddServiceListener() { + if (!mIfaceListeners.isEmpty() || !mEthernetStateListeners.isEmpty()) return; + + try { + mService.addListener(mServiceListener); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); } + } /** @@ -323,15 +362,20 @@ public class EthernetManager { @SystemApi(client = MODULE_LIBRARIES) public void removeInterfaceStateListener(@NonNull InterfaceStateListener listener) { Objects.requireNonNull(listener); - synchronized (mListeners) { - mListeners.removeIf(l -> l.listener == listener); - if (mListeners.isEmpty()) { - try { - mService.removeListener(mServiceListener); - } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); - } - } + synchronized (mListenerLock) { + mIfaceListeners.removeIf(l -> l.listener == listener); + maybeRemoveServiceListener(); + } + } + + @GuardedBy("mListenerLock") + private void maybeRemoveServiceListener() { + if (!mIfaceListeners.isEmpty() || !mEthernetStateListeners.isEmpty()) return; + + try { + mService.removeListener(mServiceListener); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); } } @@ -443,41 +487,45 @@ public class EthernetManager { return new TetheredInterfaceRequest(mService, cbInternal); } - private static final class InternalNetworkManagementListener - extends IEthernetNetworkManagementListener.Stub { + private static final class NetworkInterfaceOutcomeReceiver + extends INetworkInterfaceOutcomeReceiver.Stub { @NonNull private final Executor mExecutor; @NonNull - private final BiConsumer<Network, EthernetNetworkManagementException> mListener; + private final OutcomeReceiver<String, EthernetNetworkManagementException> mCallback; - InternalNetworkManagementListener( + NetworkInterfaceOutcomeReceiver( @NonNull final Executor executor, - @NonNull final BiConsumer<Network, EthernetNetworkManagementException> listener) { + @NonNull final OutcomeReceiver<String, EthernetNetworkManagementException> + callback) { Objects.requireNonNull(executor, "Pass a non-null executor"); - Objects.requireNonNull(listener, "Pass a non-null listener"); + Objects.requireNonNull(callback, "Pass a non-null callback"); mExecutor = executor; - mListener = listener; + mCallback = callback; } @Override - public void onComplete( - @Nullable final Network network, - @Nullable final EthernetNetworkManagementException e) { - mExecutor.execute(() -> mListener.accept(network, e)); + public void onResult(@NonNull String iface) { + mExecutor.execute(() -> mCallback.onResult(iface)); + } + + @Override + public void onError(@NonNull EthernetNetworkManagementException e) { + mExecutor.execute(() -> mCallback.onError(e)); } } - private InternalNetworkManagementListener getInternalNetworkManagementListener( + private NetworkInterfaceOutcomeReceiver makeNetworkInterfaceOutcomeReceiver( @Nullable final Executor executor, - @Nullable final BiConsumer<Network, EthernetNetworkManagementException> listener) { - if (null != listener) { - Objects.requireNonNull(executor, "Pass a non-null executor, or a null listener"); + @Nullable final OutcomeReceiver<String, EthernetNetworkManagementException> callback) { + if (null != callback) { + Objects.requireNonNull(executor, "Pass a non-null executor, or a null callback"); } - final InternalNetworkManagementListener proxy; - if (null == listener) { + final NetworkInterfaceOutcomeReceiver proxy; + if (null == callback) { proxy = null; } else { - proxy = new InternalNetworkManagementListener(executor, listener); + proxy = new NetworkInterfaceOutcomeReceiver(executor, callback); } return proxy; } @@ -492,14 +540,17 @@ public class EthernetManager { * Similarly, use {@link NetworkCapabilities.Builder} to build a {@code NetworkCapabilities} * object for this network to put inside the {@code request}. * - * If non-null, the listener will be called exactly once after this is called, unless - * a synchronous exception was thrown. + * This function accepts an {@link OutcomeReceiver} that is called once the operation has + * finished execution. * * @param iface the name of the interface to act upon. * @param request the {@link EthernetNetworkUpdateRequest} used to set an ethernet network's * {@link StaticIpConfiguration} and {@link NetworkCapabilities} values. - * @param executor an {@link Executor} to execute the listener on. Optional if listener is null. - * @param listener an optional {@link BiConsumer} to listen for completion of the operation. + * @param executor an {@link Executor} to execute the callback on. Optional if callback is null. + * @param callback an optional {@link OutcomeReceiver} to listen for completion of the + * operation. On success, {@link OutcomeReceiver#onResult} is called with the + * interface name. On error, {@link OutcomeReceiver#onError} is called with more + * information about the error. * @throws SecurityException if the process doesn't hold * {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}. * @throws UnsupportedOperationException if called on a non-automotive device or on an @@ -515,11 +566,11 @@ public class EthernetManager { @NonNull String iface, @NonNull EthernetNetworkUpdateRequest request, @Nullable @CallbackExecutor Executor executor, - @Nullable BiConsumer<Network, EthernetNetworkManagementException> listener) { + @Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) { Objects.requireNonNull(iface, "iface must be non-null"); Objects.requireNonNull(request, "request must be non-null"); - final InternalNetworkManagementListener proxy = getInternalNetworkManagementListener( - executor, listener); + final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver( + executor, callback); try { mService.updateConfiguration(iface, request, proxy); } catch (RemoteException e) { @@ -528,20 +579,20 @@ public class EthernetManager { } /** - * Set an ethernet network's link state up. + * Enable a network interface. * - * When the link is successfully turned up, the listener will be called with the resulting - * network. If any error or unexpected condition happens while the system tries to turn the - * interface up, the listener will be called with an appropriate exception. - * The listener is guaranteed to be called exactly once for each call to this method, but this - * may take an unbounded amount of time depending on the actual network conditions. + * Enables a previously disabled network interface. + * This function accepts an {@link OutcomeReceiver} that is called once the operation has + * finished execution. * - * @param iface the name of the interface to act upon. - * @param executor an {@link Executor} to execute the listener on. Optional if listener is null. - * @param listener an optional {@link BiConsumer} to listen for completion of the operation. + * @param iface the name of the interface to enable. + * @param executor an {@link Executor} to execute the callback on. Optional if callback is null. + * @param callback an optional {@link OutcomeReceiver} to listen for completion of the + * operation. On success, {@link OutcomeReceiver#onResult} is called with the + * interface name. On error, {@link OutcomeReceiver#onError} is called with more + * information about the error. * @throws SecurityException if the process doesn't hold * {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}. - * @throws UnsupportedOperationException if called on a non-automotive device. * @hide */ @SystemApi @@ -550,13 +601,13 @@ public class EthernetManager { android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}) @RequiresFeature(PackageManager.FEATURE_AUTOMOTIVE) - public void connectNetwork( + public void enableInterface( @NonNull String iface, @Nullable @CallbackExecutor Executor executor, - @Nullable BiConsumer<Network, EthernetNetworkManagementException> listener) { + @Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) { Objects.requireNonNull(iface, "iface must be non-null"); - final InternalNetworkManagementListener proxy = getInternalNetworkManagementListener( - executor, listener); + final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver( + executor, callback); try { mService.connectNetwork(iface, proxy); } catch (RemoteException e) { @@ -565,19 +616,21 @@ public class EthernetManager { } /** - * Set an ethernet network's link state down. + * Disable a network interface. * - * When the link is successfully turned down, the listener will be called with the network that - * was torn down, if any. If any error or unexpected condition happens while the system tries to - * turn the interface down, the listener will be called with an appropriate exception. - * The listener is guaranteed to be called exactly once for each call to this method. + * Disables the use of a network interface to fulfill network requests. If the interface + * currently serves a request, the network will be torn down. + * This function accepts an {@link OutcomeReceiver} that is called once the operation has + * finished execution. * - * @param iface the name of the interface to act upon. - * @param executor an {@link Executor} to execute the listener on. Optional if listener is null. - * @param listener an optional {@link BiConsumer} to listen for completion of the operation. + * @param iface the name of the interface to disable. + * @param executor an {@link Executor} to execute the callback on. Optional if callback is null. + * @param callback an optional {@link OutcomeReceiver} to listen for completion of the + * operation. On success, {@link OutcomeReceiver#onResult} is called with the + * interface name. On error, {@link OutcomeReceiver#onError} is called with more + * information about the error. * @throws SecurityException if the process doesn't hold * {@link android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}. - * @throws UnsupportedOperationException if called on a non-automotive device. * @hide */ @SystemApi @@ -586,17 +639,74 @@ public class EthernetManager { android.Manifest.permission.NETWORK_STACK, android.Manifest.permission.MANAGE_ETHERNET_NETWORKS}) @RequiresFeature(PackageManager.FEATURE_AUTOMOTIVE) - public void disconnectNetwork( + public void disableInterface( @NonNull String iface, @Nullable @CallbackExecutor Executor executor, - @Nullable BiConsumer<Network, EthernetNetworkManagementException> listener) { + @Nullable OutcomeReceiver<String, EthernetNetworkManagementException> callback) { Objects.requireNonNull(iface, "iface must be non-null"); - final InternalNetworkManagementListener proxy = getInternalNetworkManagementListener( - executor, listener); + final NetworkInterfaceOutcomeReceiver proxy = makeNetworkInterfaceOutcomeReceiver( + executor, callback); try { mService.disconnectNetwork(iface, proxy); } catch (RemoteException e) { throw e.rethrowFromSystemServer(); } } + + /** + * Change ethernet setting. + * + * @param enabled enable or disable ethernet settings. + * + * @hide + */ + @RequiresPermission(anyOf = { + NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK, + android.Manifest.permission.NETWORK_STACK, + android.Manifest.permission.NETWORK_SETTINGS}) + @SystemApi(client = MODULE_LIBRARIES) + public void setEthernetEnabled(boolean enabled) { + try { + mService.setEthernetEnabled(enabled); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } + } + + /** + * Listen to changes in the state of ethernet. + * + * @param executor to run callbacks on. + * @param listener to listen ethernet state changed. + * + * @hide + */ + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) + @SystemApi(client = MODULE_LIBRARIES) + public void addEthernetStateListener(@NonNull Executor executor, + @NonNull IntConsumer listener) { + Objects.requireNonNull(executor); + Objects.requireNonNull(listener); + synchronized (mListenerLock) { + maybeAddServiceListener(); + mEthernetStateListeners.add(new ListenerInfo<IntConsumer>(executor, listener)); + } + } + + /** + * Removes a listener. + * + * @param listener to listen ethernet state changed. + * + * @hide + */ + @RequiresPermission(android.Manifest.permission.ACCESS_NETWORK_STATE) + @SystemApi(client = MODULE_LIBRARIES) + public void removeEthernetStateListener(@NonNull IntConsumer listener) { + Objects.requireNonNull(listener); + synchronized (mListenerLock) { + mEthernetStateListeners.removeIf(l -> l.listener == listener); + maybeRemoveServiceListener(); + } + } } diff --git a/packages/ConnectivityT/framework-t/src/android/net/EthernetNetworkUpdateRequest.java b/packages/ConnectivityT/framework-t/src/android/net/EthernetNetworkUpdateRequest.java index 43f4c40f2d27..1691942c3675 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/EthernetNetworkUpdateRequest.java +++ b/packages/ConnectivityT/framework-t/src/android/net/EthernetNetworkUpdateRequest.java @@ -33,17 +33,20 @@ import java.util.Objects; */ @SystemApi public final class EthernetNetworkUpdateRequest implements Parcelable { - @NonNull + @Nullable private final IpConfiguration mIpConfig; @Nullable private final NetworkCapabilities mNetworkCapabilities; /** - * @return the new {@link IpConfiguration}. + * Setting the {@link IpConfiguration} is optional in {@link EthernetNetworkUpdateRequest}. + * When set to null, the existing IpConfiguration is not updated. + * + * @return the new {@link IpConfiguration} or null. */ - @NonNull + @Nullable public IpConfiguration getIpConfiguration() { - return new IpConfiguration(mIpConfig); + return mIpConfig == null ? null : new IpConfiguration(mIpConfig); } /** @@ -57,9 +60,8 @@ public final class EthernetNetworkUpdateRequest implements Parcelable { return mNetworkCapabilities == null ? null : new NetworkCapabilities(mNetworkCapabilities); } - private EthernetNetworkUpdateRequest(@NonNull final IpConfiguration ipConfig, + private EthernetNetworkUpdateRequest(@Nullable final IpConfiguration ipConfig, @Nullable final NetworkCapabilities networkCapabilities) { - Objects.requireNonNull(ipConfig); mIpConfig = ipConfig; mNetworkCapabilities = networkCapabilities; } @@ -90,7 +92,8 @@ public final class EthernetNetworkUpdateRequest implements Parcelable { */ public Builder(@NonNull final EthernetNetworkUpdateRequest request) { Objects.requireNonNull(request); - mBuilderIpConfig = new IpConfiguration(request.mIpConfig); + mBuilderIpConfig = null == request.mIpConfig + ? null : new IpConfiguration(request.mIpConfig); mBuilderNetworkCapabilities = null == request.mNetworkCapabilities ? null : new NetworkCapabilities(request.mNetworkCapabilities); } @@ -101,8 +104,8 @@ public final class EthernetNetworkUpdateRequest implements Parcelable { * @return The builder to facilitate chaining. */ @NonNull - public Builder setIpConfiguration(@NonNull final IpConfiguration ipConfig) { - mBuilderIpConfig = new IpConfiguration(ipConfig); + public Builder setIpConfiguration(@Nullable final IpConfiguration ipConfig) { + mBuilderIpConfig = ipConfig == null ? null : new IpConfiguration(ipConfig); return this; } @@ -119,9 +122,16 @@ public final class EthernetNetworkUpdateRequest implements Parcelable { /** * Build {@link EthernetNetworkUpdateRequest} return the current update request. + * + * @throws IllegalStateException when both mBuilderNetworkCapabilities and mBuilderIpConfig + * are null. */ @NonNull public EthernetNetworkUpdateRequest build() { + if (mBuilderIpConfig == null && mBuilderNetworkCapabilities == null) { + throw new IllegalStateException( + "Cannot construct an empty EthernetNetworkUpdateRequest"); + } return new EthernetNetworkUpdateRequest(mBuilderIpConfig, mBuilderNetworkCapabilities); } } diff --git a/packages/ConnectivityT/framework-t/src/android/net/IEthernetManager.aidl b/packages/ConnectivityT/framework-t/src/android/net/IEthernetManager.aidl index 544d02ba76ff..44e27e26f5d2 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/IEthernetManager.aidl +++ b/packages/ConnectivityT/framework-t/src/android/net/IEthernetManager.aidl @@ -18,8 +18,9 @@ package android.net; import android.net.IpConfiguration; import android.net.IEthernetServiceListener; -import android.net.IEthernetNetworkManagementListener; +import android.net.EthernetNetworkManagementException; import android.net.EthernetNetworkUpdateRequest; +import android.net.INetworkInterfaceOutcomeReceiver; import android.net.ITetheredInterfaceCallback; /** @@ -39,7 +40,8 @@ interface IEthernetManager void requestTetheredInterface(in ITetheredInterfaceCallback callback); void releaseTetheredInterface(in ITetheredInterfaceCallback callback); void updateConfiguration(String iface, in EthernetNetworkUpdateRequest request, - in IEthernetNetworkManagementListener listener); - void connectNetwork(String iface, in IEthernetNetworkManagementListener listener); - void disconnectNetwork(String iface, in IEthernetNetworkManagementListener listener); + in INetworkInterfaceOutcomeReceiver listener); + void connectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener); + void disconnectNetwork(String iface, in INetworkInterfaceOutcomeReceiver listener); + void setEthernetEnabled(boolean enabled); } diff --git a/packages/ConnectivityT/framework-t/src/android/net/IEthernetServiceListener.aidl b/packages/ConnectivityT/framework-t/src/android/net/IEthernetServiceListener.aidl index 6d2ba03f78d4..751605bb3849 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/IEthernetServiceListener.aidl +++ b/packages/ConnectivityT/framework-t/src/android/net/IEthernetServiceListener.aidl @@ -21,6 +21,7 @@ import android.net.IpConfiguration; /** @hide */ oneway interface IEthernetServiceListener { + void onEthernetStateChanged(int state); void onInterfaceStateChanged(String iface, int state, int role, in IpConfiguration configuration); } diff --git a/packages/ConnectivityT/framework-t/src/android/net/IEthernetNetworkManagementListener.aidl b/packages/ConnectivityT/framework-t/src/android/net/INetworkInterfaceOutcomeReceiver.aidl index 93edccfdafd9..85795ead7aea 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/IEthernetNetworkManagementListener.aidl +++ b/packages/ConnectivityT/framework-t/src/android/net/INetworkInterfaceOutcomeReceiver.aidl @@ -17,9 +17,9 @@ package android.net; import android.net.EthernetNetworkManagementException; -import android.net.Network; /** @hide */ -oneway interface IEthernetNetworkManagementListener { - void onComplete(in Network network, in EthernetNetworkManagementException exception); +oneway interface INetworkInterfaceOutcomeReceiver { + void onResult(in String iface); + void onError(in EthernetNetworkManagementException e); }
\ No newline at end of file diff --git a/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java b/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java index 06f2a621bcae..bcfeab96081a 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java +++ b/packages/ConnectivityT/framework-t/src/android/net/NetworkStats.java @@ -16,6 +16,8 @@ package android.net; +import static android.annotation.SystemApi.Client.MODULE_LIBRARIES; + import static com.android.net.module.util.NetworkStatsUtils.multiplySafeByRational; import android.annotation.IntDef; @@ -124,7 +126,6 @@ public final class NetworkStats implements Parcelable, Iterable<NetworkStats.Ent public @Nullable static final String[] INTERFACES_ALL = null; /** {@link #tag} value for total data across all tags. */ - // TODO: Rename TAG_NONE to TAG_ALL. public static final int TAG_NONE = 0; /** {@link #metered} value to account for all metered states. */ @@ -390,77 +391,102 @@ public final class NetworkStats implements Parcelable, Iterable<NetworkStats.Ent /** * @return the uid of this entry. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public int getUid() { return uid; } /** * @return the set state of this entry. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) @State public int getSet() { return set; } /** * @return the tag value of this entry. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public int getTag() { return tag; } /** * @return the metered state. + * @hide */ - @Meteredness public int getMetered() { + @Meteredness + @SystemApi(client = MODULE_LIBRARIES) + public int getMetered() { return metered; } /** * @return the roaming state. + * @hide */ - @Roaming public int getRoaming() { + @Roaming + @SystemApi(client = MODULE_LIBRARIES) + public int getRoaming() { return roaming; } /** * @return the default network state. + * @hide */ - @DefaultNetwork public int getDefaultNetwork() { + @DefaultNetwork + @SystemApi(client = MODULE_LIBRARIES) + public int getDefaultNetwork() { return defaultNetwork; } /** * @return the number of received bytes. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public long getRxBytes() { return rxBytes; } /** * @return the number of received packets. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public long getRxPackets() { return rxPackets; } /** * @return the number of transmitted bytes. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public long getTxBytes() { return txBytes; } /** * @return the number of transmitted packets. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public long getTxPackets() { return txPackets; } /** * @return the count of network operations performed for this entry. + * @hide */ + @SystemApi(client = MODULE_LIBRARIES) public long getOperations() { return operations; } @@ -682,7 +708,7 @@ public final class NetworkStats implements Parcelable, Iterable<NetworkStats.Ent * The remove() method is not implemented and will throw UnsupportedOperationException. * @hide */ - @SystemApi + @SystemApi(client = MODULE_LIBRARIES) @NonNull public Iterator<Entry> iterator() { return new Iterator<Entry>() { int mIndex = 0; diff --git a/packages/ConnectivityT/framework-t/src/android/net/TrafficStats.java b/packages/ConnectivityT/framework-t/src/android/net/TrafficStats.java index bc836d857e3e..dc4ac552a4bb 100644 --- a/packages/ConnectivityT/framework-t/src/android/net/TrafficStats.java +++ b/packages/ConnectivityT/framework-t/src/android/net/TrafficStats.java @@ -205,7 +205,7 @@ public class TrafficStats { * server context. * @hide */ - @SystemApi(client = SystemApi.Client.MODULE_LIBRARIES) + @SystemApi(client = MODULE_LIBRARIES) @SuppressLint("VisiblySynchronized") public static synchronized void init(@NonNull final Context context) { if (sStatsService != null) { @@ -376,7 +376,7 @@ public class TrafficStats { * * @hide */ - @SystemApi + @SystemApi(client = MODULE_LIBRARIES) public static void setThreadStatsTagDownload() { setThreadStatsTag(TAG_SYSTEM_DOWNLOAD); } @@ -468,7 +468,7 @@ public class TrafficStats { * * @see #setThreadStatsTag(int) */ - public static void tagSocket(Socket socket) throws SocketException { + public static void tagSocket(@NonNull Socket socket) throws SocketException { SocketTagger.get().tag(socket); } @@ -483,7 +483,7 @@ public class TrafficStats { * calling {@code untagSocket()} before sending the socket to another * process. */ - public static void untagSocket(Socket socket) throws SocketException { + public static void untagSocket(@NonNull Socket socket) throws SocketException { SocketTagger.get().untag(socket); } @@ -496,14 +496,14 @@ public class TrafficStats { * * @see #setThreadStatsTag(int) */ - public static void tagDatagramSocket(DatagramSocket socket) throws SocketException { + public static void tagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException { SocketTagger.get().tag(socket); } /** * Remove any statistics parameters from the given {@link DatagramSocket}. */ - public static void untagDatagramSocket(DatagramSocket socket) throws SocketException { + public static void untagDatagramSocket(@NonNull DatagramSocket socket) throws SocketException { SocketTagger.get().untag(socket); } @@ -516,7 +516,7 @@ public class TrafficStats { * * @see #setThreadStatsTag(int) */ - public static void tagFileDescriptor(FileDescriptor fd) throws IOException { + public static void tagFileDescriptor(@NonNull FileDescriptor fd) throws IOException { SocketTagger.get().tag(fd); } @@ -524,7 +524,7 @@ public class TrafficStats { * Remove any statistics parameters from the given {@link FileDescriptor} * socket. */ - public static void untagFileDescriptor(FileDescriptor fd) throws IOException { + public static void untagFileDescriptor(@NonNull FileDescriptor fd) throws IOException { SocketTagger.get().untag(fd); } diff --git a/packages/SettingsLib/SearchWidget/res/values-or/strings.xml b/packages/SettingsLib/SearchWidget/res/values-or/strings.xml index cf824deecd79..322571adc89c 100644 --- a/packages/SettingsLib/SearchWidget/res/values-or/strings.xml +++ b/packages/SettingsLib/SearchWidget/res/values-or/strings.xml @@ -17,5 +17,5 @@ <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="search_menu" msgid="1914043873178389845">"ସେଟିଂସ୍ ସନ୍ଧାନ କରନ୍ତୁ"</string> + <string name="search_menu" msgid="1914043873178389845">"ସେଟିଂସ ସନ୍ଧାନ କରନ୍ତୁ"</string> </resources> diff --git a/packages/SettingsLib/SettingsTheme/res/color-v31/settingslib_text_color_primary.xml b/packages/SettingsLib/SettingsTheme/res/color-v31/settingslib_text_color_primary.xml new file mode 100644 index 000000000000..221d2db00031 --- /dev/null +++ b/packages/SettingsLib/SettingsTheme/res/color-v31/settingslib_text_color_primary.xml @@ -0,0 +1,22 @@ +<?xml version="1.0" encoding="utf-8"?> +<!-- Copyright (C) 2022 The Android Open Source Project + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. +--> + +<selector xmlns:android="http://schemas.android.com/apk/res/android"> + <item android:state_enabled="false" + android:alpha="?android:attr/disabledAlpha" + android:color="@color/settingslib_text_color_primary_device_default"/> + <item android:color="@color/settingslib_text_color_primary_device_default"/> +</selector> diff --git a/packages/SettingsLib/SettingsTheme/res/values-v31/styles.xml b/packages/SettingsLib/SettingsTheme/res/values-v31/styles.xml index 9d3991119338..cba1a9cf0003 100644 --- a/packages/SettingsLib/SettingsTheme/res/values-v31/styles.xml +++ b/packages/SettingsLib/SettingsTheme/res/values-v31/styles.xml @@ -17,7 +17,7 @@ <resources> <style name="TextAppearance.PreferenceTitle.SettingsLib" parent="@android:style/TextAppearance.Material.Subhead"> - <item name="android:textColor">@color/settingslib_text_color_primary_device_default</item> + <item name="android:textColor">@color/settingslib_text_color_primary</item> <item name="android:fontFamily">@string/settingslib_config_headlineFontFamily</item> <item name="android:textSize">20sp</item> </style> diff --git a/packages/SettingsLib/res/values/strings.xml b/packages/SettingsLib/res/values/strings.xml index 579e3d7a6d39..31036ec152d9 100644 --- a/packages/SettingsLib/res/values/strings.xml +++ b/packages/SettingsLib/res/values/strings.xml @@ -1038,23 +1038,6 @@ <!-- Developer settings: text for the WebView provider selection toast shown if an invalid provider was chosen (i.e. the setting list was stale). [CHAR LIMIT=NONE] --> <string name="select_webview_provider_toast_text">This choice is no longer valid. Try again.</string> - <!-- Developer settings screen, convert userdata to file encryption option name --> - <string name="convert_to_file_encryption">Convert to file encryption</string> - <!-- Developer settings screen, convert userdata to file encryption summary when option is available --> - <string name="convert_to_file_encryption_enabled">Convert\u2026</string> - <!-- Developer settings screen, convert userdata to file encryption summary when option is already done --> - <string name="convert_to_file_encryption_done">Already file encrypted</string> - <!-- Title used on dialog with final prompt for converting to file encryption --> - <string name="title_convert_fbe">Converting to file based encryption</string> - <!-- Warning displayed on dialog with final prompt for converting to file encryption --> - <string name="convert_to_fbe_warning"> - Convert data partition to file based encryption.\n - !!Warning!! This will erase all your data.\n - This feature is alpha, and may not work correctly.\n - Press \'Wipe and convert\u2026\' to continue.</string> - <!-- Button on dialog that triggers convertion to file encryption --> - <string name="button_convert_fbe">Wipe and convert\u2026</string> - <!-- Name of feature to change color setting for the display [CHAR LIMIT=60] --> <string name="picture_color_mode">Picture color mode</string> @@ -1582,4 +1565,11 @@ <string name="keyboard_layout_dialog_title">Choose keyboard layout</string> <!-- Label of the default keyboard layout. [CHAR LIMIT=35] --> <string name="keyboard_layout_default_label">Default</string> + + <!-- Special access > Title for managing turn screen on settings. [CHAR LIMIT=50] --> + <string name="turn_screen_on_title">Turn screen on</string> + <!-- Label for a setting which controls whether an app can turn the screen on [CHAR LIMIT=45] --> + <string name="allow_turn_screen_on">Allow turning the screen on</string> + <!-- Description for a setting which controls whether an app can turn the screen on [CHAR LIMIT=NONE] --> + <string name="allow_turn_screen_on_description">Allow an app to turn the screen on. If granted, the app may turn on the screen at any time without your explicit intent.</string> </resources> diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java index 7f300cafaa08..2a28891e9158 100644 --- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java +++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/CachedBluetoothDevice.java @@ -753,7 +753,10 @@ public class CachedBluetoothDevice implements Comparable<CachedBluetoothDevice> ParcelUuid[] uuids = mDevice.getUuids(); if (uuids == null) return false; - ParcelUuid[] localUuids = mLocalAdapter.getUuids(); + List<ParcelUuid> uuidsList = mLocalAdapter.getUuidsList(); + ParcelUuid[] localUuids = new ParcelUuid[uuidsList.size()]; + uuidsList.toArray(localUuids); + if (localUuids == null) return false; /* diff --git a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java index e7a6b327bacd..31cc6a4ba412 100644 --- a/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java +++ b/packages/SettingsLib/src/com/android/settingslib/bluetooth/LocalBluetoothAdapter.java @@ -126,7 +126,10 @@ public class LocalBluetoothAdapter { } public ParcelUuid[] getUuids() { - return mAdapter.getUuids(); + List<ParcelUuid> uuidsList = mAdapter.getUuidsList(); + ParcelUuid[] uuidsArray = new ParcelUuid[uuidsList.size()]; + uuidsList.toArray(uuidsArray); + return uuidsArray; } public boolean isDiscovering() { diff --git a/packages/SettingsLib/src/com/android/settingslib/users/AvatarPhotoController.java b/packages/SettingsLib/src/com/android/settingslib/users/AvatarPhotoController.java index 0cb2c0b22a4c..63a9f0c5c7f4 100644 --- a/packages/SettingsLib/src/com/android/settingslib/users/AvatarPhotoController.java +++ b/packages/SettingsLib/src/com/android/settingslib/users/AvatarPhotoController.java @@ -78,6 +78,11 @@ class AvatarPhotoController { static final int REQUEST_CODE_TAKE_PHOTO = 1002; static final int REQUEST_CODE_CROP_PHOTO = 1003; + /** + * Delay to allow the photo picker exit animation to complete before the crop activity opens. + */ + private static final long DELAY_BEFORE_CROP_MILLIS = 150; + private static final String IMAGES_DIR = "multi_user"; private static final String PRE_CROP_PICTURE_FILE_NAME = "PreCropEditUserPhoto.jpg"; private static final String CROP_PICTURE_FILE_NAME = "CropEditUserPhoto.jpg"; @@ -131,13 +136,15 @@ class AvatarPhotoController { mAvatarUi.returnUriResult(pictureUri); return true; case REQUEST_CODE_TAKE_PHOTO: - case REQUEST_CODE_CHOOSE_PHOTO: if (mTakePictureUri.equals(pictureUri)) { cropPhoto(pictureUri); } else { - copyAndCropPhoto(pictureUri); + copyAndCropPhoto(pictureUri, false); } return true; + case REQUEST_CODE_CHOOSE_PHOTO: + copyAndCropPhoto(pictureUri, true); + return true; } return false; } @@ -154,7 +161,7 @@ class AvatarPhotoController { mAvatarUi.startActivityForResult(intent, REQUEST_CODE_CHOOSE_PHOTO); } - private void copyAndCropPhoto(final Uri pictureUri) { + private void copyAndCropPhoto(final Uri pictureUri, boolean delayBeforeCrop) { try { ThreadUtils.postOnBackgroundThread(() -> { final ContentResolver cr = mContextInjector.getContentResolver(); @@ -165,11 +172,17 @@ class AvatarPhotoController { Log.w(TAG, "Failed to copy photo", e); return; } - ThreadUtils.postOnMainThread(() -> { + Runnable cropRunnable = () -> { if (!mAvatarUi.isFinishing()) { cropPhoto(mPreCropPictureUri); } - }); + }; + if (delayBeforeCrop) { + ThreadUtils.postOnMainThreadDelayed(cropRunnable, DELAY_BEFORE_CROP_MILLIS); + } else { + ThreadUtils.postOnMainThread(cropRunnable); + } + }).get(); } catch (InterruptedException | ExecutionException e) { Log.e(TAG, "Error performing copy-and-crop", e); diff --git a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java index 69f1c17f97b1..2c1d5da5e941 100644 --- a/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java +++ b/packages/SettingsLib/src/com/android/settingslib/utils/ThreadUtils.java @@ -84,6 +84,13 @@ public class ThreadUtils { getUiThreadHandler().post(runnable); } + /** + * Posts the runnable on the main thread with a delay. + */ + public static void postOnMainThreadDelayed(Runnable runnable, long delayMillis) { + getUiThreadHandler().postDelayed(runnable, delayMillis); + } + private static synchronized ExecutorService getThreadExecutor() { if (sThreadExecutor == null) { sThreadExecutor = Executors.newFixedThreadPool( diff --git a/packages/SettingsProvider/res/values-or/strings.xml b/packages/SettingsProvider/res/values-or/strings.xml index 486d8ffaa500..85add41b1ee1 100644 --- a/packages/SettingsProvider/res/values-or/strings.xml +++ b/packages/SettingsProvider/res/values-or/strings.xml @@ -19,7 +19,7 @@ <resources xmlns:android="http://schemas.android.com/apk/res/android" xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2"> - <string name="app_label" msgid="4567566098528588863">"ସେଟିଙ୍ଗ ଷ୍ଟୋରେଜ୍"</string> + <string name="app_label" msgid="4567566098528588863">"ସେଟିଂସ ଷ୍ଟୋରେଜ୍"</string> <string name="wifi_softap_config_change" msgid="5688373762357941645">"ହଟସ୍ପଟ୍ ସେଟିଂସ୍ ବଦଳାଯାଇଛି"</string> <string name="wifi_softap_config_change_summary" msgid="8946397286141531087">"ବିବରଣୀ ଦେଖିବାକୁ ଟାପ୍ କରନ୍ତୁ"</string> </resources> diff --git a/packages/SystemUI/res/layout/ongoing_privacy_chip.xml b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml index ad2bc79a5c96..5aa608084510 100644 --- a/packages/SystemUI/res/layout/ongoing_privacy_chip.xml +++ b/packages/SystemUI/res/layout/ongoing_privacy_chip.xml @@ -37,7 +37,5 @@ android:layout_gravity="center" android:minWidth="@dimen/ongoing_appops_chip_min_width" android:maxWidth="@dimen/ongoing_appops_chip_max_width" - android:clipChildren="false" - android:clipToPadding="false" /> </com.android.systemui.privacy.OngoingPrivacyChip>
\ No newline at end of file diff --git a/packages/SystemUI/res/values-sw600dp-land/dimens.xml b/packages/SystemUI/res/values-sw600dp-land/dimens.xml index 02a4070415dd..740697ba98af 100644 --- a/packages/SystemUI/res/values-sw600dp-land/dimens.xml +++ b/packages/SystemUI/res/values-sw600dp-land/dimens.xml @@ -54,6 +54,14 @@ the shade (in alpha) --> <dimen name="lockscreen_shade_scrim_transition_distance">80dp</dimen> + <!-- The notifications scrim transition should start when the other scrims' transition is at + 95%. --> + <dimen name="lockscreen_shade_notifications_scrim_transition_delay">76dp</dimen> + + <!-- The notifications scrim transition duration is 66.6% of the duration of the other scrims' + transition. --> + <dimen name="lockscreen_shade_notifications_scrim_transition_distance">53.28dp</dimen> + <!-- Distance that the full shade transition takes in order for the keyguard content on NotificationPanelViewController to fully fade (e.g. Clock & Smartspace) --> <dimen name="lockscreen_shade_npvc_keyguard_content_alpha_transition_distance">80dp</dimen> diff --git a/packages/SystemUI/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml index ffae6015c732..6871310ebd6b 100644 --- a/packages/SystemUI/res/values/dimens.xml +++ b/packages/SystemUI/res/values/dimens.xml @@ -941,6 +941,9 @@ <!-- Three privacy items. This value must not be exceeded --> <dimen name="ongoing_appops_chip_max_width">76dp</dimen> <dimen name="ongoing_appops_dot_diameter">6dp</dimen> + <dimen name="ongoing_appops_chip_min_animation_width">10dp</dimen> + <dimen name="ongoing_appops_chip_animation_in_status_bar_translation_x">15dp</dimen> + <dimen name="ongoing_appops_chip_animation_out_status_bar_translation_x">7dp</dimen> <!-- Total minimum padding to enforce to ensure that the dot can always show --> <dimen name="ongoing_appops_dot_min_padding">20dp</dimen> @@ -1138,6 +1141,12 @@ the shade (in alpha) --> <dimen name="lockscreen_shade_scrim_transition_distance">@dimen/lockscreen_shade_full_transition_distance</dimen> + <!-- Distance that it takes in order for the notifications scrim fade in to start. --> + <dimen name="lockscreen_shade_notifications_scrim_transition_delay">0dp</dimen> + + <!-- Distance that it takes for the notifications scrim to fully fade if after it started. --> + <dimen name="lockscreen_shade_notifications_scrim_transition_distance">@dimen/lockscreen_shade_scrim_transition_distance</dimen> + <!-- Distance that the full shade transition takes in order for the keyguard content on NotificationPanelViewController to fully fade (e.g. Clock & Smartspace) --> <dimen name="lockscreen_shade_npvc_keyguard_content_alpha_transition_distance">@dimen/lockscreen_shade_full_transition_distance</dimen> diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt index a27b9cd357f4..b811c51c952b 100644 --- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt +++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthRippleController.kt @@ -116,7 +116,7 @@ class AuthRippleController @Inject constructor( } fun showRipple(biometricSourceType: BiometricSourceType?) { - if (!keyguardUpdateMonitor.isKeyguardVisible || + if (!(keyguardUpdateMonitor.isKeyguardVisible || keyguardUpdateMonitor.isDreaming) || keyguardUpdateMonitor.userNeedsStrongAuth()) { return } diff --git a/packages/SystemUI/src/com/android/systemui/media/MediaHierarchyManager.kt b/packages/SystemUI/src/com/android/systemui/media/MediaHierarchyManager.kt index 7a4dee294dd6..d472aeee1073 100644 --- a/packages/SystemUI/src/com/android/systemui/media/MediaHierarchyManager.kt +++ b/packages/SystemUI/src/com/android/systemui/media/MediaHierarchyManager.kt @@ -812,7 +812,7 @@ class MediaHierarchyManager @Inject constructor( @TransformationType fun calculateTransformationType(): Int { if (isTransitioningToFullShade) { - if (inSplitShade) { + if (inSplitShade && areGuidedTransitionHostsVisible()) { return TRANSFORMATION_TYPE_TRANSITION } return TRANSFORMATION_TYPE_FADE @@ -829,6 +829,11 @@ class MediaHierarchyManager @Inject constructor( return TRANSFORMATION_TYPE_TRANSITION } + private fun areGuidedTransitionHostsVisible(): Boolean { + return getHost(previousLocation)?.visible == true && + getHost(desiredLocation)?.visible == true + } + /** * @return the current transformation progress if we're in a guided transformation and -1 * otherwise diff --git a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogController.kt b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogController.kt index 61071235db0b..8147877a8a29 100644 --- a/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogController.kt +++ b/packages/SystemUI/src/com/android/systemui/privacy/PrivacyDialogController.kt @@ -150,24 +150,27 @@ class PrivacyDialogController( packageName: String, userId: Int, permGroupName: CharSequence, - attributionTag: CharSequence? + attributionTag: CharSequence?, + isAttributionSupported: Boolean ): Intent { lateinit var intent: Intent - if (attributionTag != null) { + if (attributionTag != null && isAttributionSupported) { intent = Intent(Intent.ACTION_MANAGE_PERMISSION_USAGE) intent.setPackage(packageName) intent.putExtra(Intent.EXTRA_PERMISSION_GROUP_NAME, permGroupName.toString()) intent.putExtra(Intent.EXTRA_ATTRIBUTION_TAGS, arrayOf(attributionTag.toString())) intent.putExtra(Intent.EXTRA_SHOWING_ATTRIBUTION, true) val resolveInfo = packageManager.resolveActivity( - intent, PackageManager.ResolveInfoFlags.of(0)) - ?: return getDefaultManageAppPermissionsIntent(packageName, userId) - intent.component = ComponentName(packageName, resolveInfo.activityInfo.name) - return intent - } else { - return getDefaultManageAppPermissionsIntent(packageName, userId) + intent, PackageManager.ResolveInfoFlags.of(0)) + if (resolveInfo != null && resolveInfo.activityInfo != null && + resolveInfo.activityInfo.permission == + android.Manifest.permission.START_VIEW_PERMISSION_USAGE) { + intent.component = ComponentName(packageName, resolveInfo.activityInfo.name) + return intent + } } + return getDefaultManageAppPermissionsIntent(packageName, userId) } fun getDefaultManageAppPermissionsIntent(packageName: String, userId: Int): Intent { @@ -226,9 +229,15 @@ class PrivacyDialogController( userInfo?.isManagedProfile ?: false, it.isPhoneCall, it.permissionGroupName, - getManagePermissionIntent(it.packageName, userId, - it.permissionGroupName, - it.attributionTag) + getManagePermissionIntent( + it.packageName, + userId, + it.permissionGroupName, + it.attributionTag, + // attributionLabel is set only when subattribution policies + // are supported and satisfied + it.attributionLabel != null + ) ) } } else { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt index ab4d0dd355f3..de3e89d6dc8c 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/LockscreenShadeTransitionController.kt @@ -116,6 +116,16 @@ class LockscreenShadeTransitionController @Inject constructor( private var scrimTransitionDistance = 0 /** + * Distance that it takes in order for the notifications scrim fade in to start. + */ + private var notificationsScrimTransitionDelay = 0 + + /** + * Distance that it takes for the notifications scrim to fully fade if after it started. + */ + private var notificationsScrimTransitionDistance = 0 + + /** * Distance that the full shade transition takes in order for the notification shelf to fully * expand. */ @@ -225,6 +235,10 @@ class LockscreenShadeTransitionController @Inject constructor( R.dimen.lockscreen_shade_transition_by_tap_distance) scrimTransitionDistance = context.resources.getDimensionPixelSize( R.dimen.lockscreen_shade_scrim_transition_distance) + notificationsScrimTransitionDelay = context.resources.getDimensionPixelSize( + R.dimen.lockscreen_shade_notifications_scrim_transition_delay) + notificationsScrimTransitionDistance = context.resources.getDimensionPixelSize( + R.dimen.lockscreen_shade_notifications_scrim_transition_distance) notificationShelfTransitionDistance = context.resources.getDimensionPixelSize( R.dimen.lockscreen_shade_notif_shelf_transition_distance) qsTransitionDistance = context.resources.getDimensionPixelSize( @@ -405,6 +419,7 @@ class LockscreenShadeTransitionController @Inject constructor( false /* animate */, 0 /* delay */) mediaHierarchyManager.setTransitionToFullShadeAmount(field) + transitionToShadeAmountScrim(field) transitionToShadeAmountCommon(field) transitionToShadeAmountKeyguard(field) } @@ -417,10 +432,15 @@ class LockscreenShadeTransitionController @Inject constructor( var qSDragProgress = 0f private set - private fun transitionToShadeAmountCommon(dragDownAmount: Float) { + private fun transitionToShadeAmountScrim(dragDownAmount: Float) { val scrimProgress = MathUtils.saturate(dragDownAmount / scrimTransitionDistance) - scrimController.setTransitionToFullShadeProgress(scrimProgress) + val notificationsScrimDragAmount = dragDownAmount - notificationsScrimTransitionDelay + val notificationsScrimProgress = MathUtils.saturate( + notificationsScrimDragAmount / notificationsScrimTransitionDistance) + scrimController.setTransitionToFullShadeProgress(scrimProgress, notificationsScrimProgress) + } + private fun transitionToShadeAmountCommon(dragDownAmount: Float) { if (depthControllerTransitionDistance > 0) { val depthProgress = MathUtils.saturate(dragDownAmount / depthControllerTransitionDistance) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt index 9795dcf1fcd8..b74140da99d2 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemEventChipAnimationController.kt @@ -16,9 +16,12 @@ package com.android.systemui.statusbar.events +import android.animation.Animator +import android.animation.AnimatorListenerAdapter +import android.animation.AnimatorSet import android.animation.ValueAnimator import android.content.Context -import android.graphics.Point +import android.graphics.Rect import android.view.Gravity import android.view.LayoutInflater import android.view.View @@ -30,6 +33,7 @@ import com.android.systemui.R import com.android.systemui.statusbar.phone.StatusBarContentInsetsProvider import com.android.systemui.statusbar.window.StatusBarWindowController import javax.inject.Inject +import kotlin.math.roundToInt /** * Controls the view for system event animations. @@ -38,7 +42,7 @@ class SystemEventChipAnimationController @Inject constructor( private val context: Context, private val statusBarWindowController: StatusBarWindowController, private val contentInsetsProvider: StatusBarContentInsetsProvider -) : SystemStatusChipAnimationCallback { +) : SystemStatusAnimationCallback { private lateinit var animationWindowView: FrameLayout @@ -49,90 +53,169 @@ class SystemEventChipAnimationController @Inject constructor( private var chipRight = 0 private var chipLeft = 0 private var chipWidth = 0 - private var dotCenter = Point(0, 0) + private var chipMinWidth = context.resources.getDimensionPixelSize( + R.dimen.ongoing_appops_chip_min_animation_width) private var dotSize = context.resources.getDimensionPixelSize( R.dimen.ongoing_appops_dot_diameter) - // If the chip animates away to a persistent dot, then we modify the CHIP_OUT animation - private var isAnimatingToDot = false + // Use during animation so that multiple animators can update the drawing rect + private var animRect = Rect() // TODO: move to dagger private var initialized = false - override fun onChipAnimationStart( - viewCreator: ViewCreator, - @SystemAnimationState state: Int - ) { - if (!initialized) init() - - if (state == ANIMATING_IN) { - animationDirection = if (animationWindowView.isLayoutRtl) RIGHT else LEFT - - // Initialize the animated view - val insets = contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation() - currentAnimatedView = viewCreator(context).also { - animationWindowView.addView( - it.view, - layoutParamsDefault( - if (animationWindowView.isLayoutRtl) insets.first - else insets.second)) - it.view.alpha = 0f - // For some reason, the window view's measured width is always 0 here, so use the - // parent (status bar) - it.view.measure( - View.MeasureSpec.makeMeasureSpec( - (animationWindowView.parent as View).width, AT_MOST), - View.MeasureSpec.makeMeasureSpec(animationWindowView.height, AT_MOST)) - chipWidth = it.chipWidth - } + /** + * Give the chip controller a chance to inflate and configure the chip view before we start + * animating + */ + fun prepareChipAnimation(viewCreator: ViewCreator) { + if (!initialized) { + init() + } + animationDirection = if (animationWindowView.isLayoutRtl) RIGHT else LEFT - // decide which direction we're animating from, and then set some screen coordinates - val contentRect = contentInsetsProvider.getStatusBarContentAreaForCurrentRotation() - when (animationDirection) { - LEFT -> { - chipRight = contentRect.right - chipLeft = contentRect.right - chipWidth - } - else /* RIGHT */ -> { - chipLeft = contentRect.left - chipRight = contentRect.left + chipWidth - } - } + // Initialize the animated view + val insets = contentInsetsProvider.getStatusBarContentInsetsForCurrentRotation() + currentAnimatedView = viewCreator(context).also { + animationWindowView.addView( + it.view, + layoutParamsDefault( + if (animationWindowView.isLayoutRtl) insets.first + else insets.second)) + it.view.alpha = 0f + // For some reason, the window view's measured width is always 0 here, so use the + // parent (status bar) + it.view.measure( + View.MeasureSpec.makeMeasureSpec( + (animationWindowView.parent as View).width, AT_MOST), + View.MeasureSpec.makeMeasureSpec(animationWindowView.height, AT_MOST)) + chipWidth = it.chipWidth + } - currentAnimatedView?.apply { - updateAnimatedViewBoundsForAmount(0.1f, this) + // decide which direction we're animating from, and then set some screen coordinates + val contentRect = contentInsetsProvider.getStatusBarContentAreaForCurrentRotation() + when (animationDirection) { + LEFT -> { + chipRight = contentRect.right + chipLeft = contentRect.right - chipWidth } - } else { - // We are animating away - currentAnimatedView!!.view.apply { - alpha = 1f + else /* RIGHT */ -> { + chipLeft = contentRect.left + chipRight = contentRect.left + chipWidth } } } - override fun onChipAnimationEnd(@SystemAnimationState state: Int) { - if (state == ANIMATING_IN) { - // Finished animating in - currentAnimatedView?.apply { - updateAnimatedViewBoundsForAmount(1f, this) + override fun onSystemEventAnimationBegin(): Animator { + initializeAnimRect() + + val alphaIn = ValueAnimator.ofFloat(0f, 1f).apply { + startDelay = 117 + duration = 83 + interpolator = null + addUpdateListener { currentAnimatedView?.view?.alpha = animatedValue as Float } + } + val moveIn = ValueAnimator.ofInt(chipMinWidth, chipWidth).apply { + startDelay = 117 + duration = 383 + interpolator = STATUS_BAR_X_MOVE_IN + addUpdateListener { + updateAnimatedViewBoundsWidth(animatedValue as Int) } + } + val animSet = AnimatorSet() + animSet.playTogether(alphaIn, moveIn) + return animSet + } + + override fun onSystemEventAnimationFinish(hasPersistentDot: Boolean): Animator { + initializeAnimRect() + val finish = if (hasPersistentDot) { + createMoveOutAnimationForDot() } else { - // Finished animating away - currentAnimatedView!!.view.apply { - visibility = View.INVISIBLE + createMoveOutAnimationDefault() + } + + finish.addListener(object : AnimatorListenerAdapter() { + override fun onAnimationEnd(animation: Animator?) { + animationWindowView.removeView(currentAnimatedView!!.view) + } + }) + + return finish + } + + private fun createMoveOutAnimationForDot(): Animator { + val width1 = ValueAnimator.ofInt(chipWidth, chipMinWidth).apply { + duration = 150 + interpolator = STATUS_CHIP_WIDTH_TO_DOT_KEYFRAME_1 + addUpdateListener { + updateAnimatedViewBoundsWidth(it.animatedValue as Int) + } + } + + val width2 = ValueAnimator.ofInt(chipMinWidth, dotSize).apply { + startDelay = 150 + duration = 333 + interpolator = STATUS_CHIP_WIDTH_TO_DOT_KEYFRAME_2 + addUpdateListener { + updateAnimatedViewBoundsWidth(it.animatedValue as Int) } - animationWindowView.removeView(currentAnimatedView!!.view) } + + val keyFrame1Height = dotSize * 2 + val v = currentAnimatedView!!.view + val chipVerticalCenter = v.top + v.measuredHeight / 2 + val height1 = ValueAnimator.ofInt( + currentAnimatedView!!.view.measuredHeight, keyFrame1Height).apply { + startDelay = 133 + duration = 100 + interpolator = STATUS_CHIP_HEIGHT_TO_DOT_KEYFRAME_1 + addUpdateListener { + updateAnimatedViewBoundsHeight(it.animatedValue as Int, chipVerticalCenter) + } + } + + val height2 = ValueAnimator.ofInt(keyFrame1Height, dotSize).apply { + startDelay = 233 + duration = 250 + interpolator = STATUS_CHIP_HEIGHT_TO_DOT_KEYFRAME_2 + addUpdateListener { + updateAnimatedViewBoundsHeight(it.animatedValue as Int, chipVerticalCenter) + } + } + + // Move the chip view to overlap exactly with the privacy dot. The chip displays by default + // exactly adjacent to the dot, so we can just move over by the diameter of the dot itself + val moveOut = ValueAnimator.ofInt(0, dotSize).apply { + startDelay = 50 + duration = 183 + interpolator = STATUS_CHIP_MOVE_TO_DOT + addUpdateListener { + // If RTL, we can just invert the move + val amt = if (animationDirection == LEFT) { + animatedValue as Int + } else { + -(animatedValue as Int) + } + updateAnimatedBoundsX(amt) + } + } + + val animSet = AnimatorSet() + animSet.playTogether(width1, width2, height1, height2, moveOut) + return animSet } - override fun onChipAnimationUpdate( - animator: ValueAnimator, - @SystemAnimationState state: Int - ) { - currentAnimatedView?.apply { - val amt = (animator.animatedValue as Float).amt() - view.alpha = (animator.animatedValue as Float) - updateAnimatedViewBoundsForAmount(amt, this) + private fun createMoveOutAnimationDefault(): Animator { + val moveOut = ValueAnimator.ofInt(chipWidth, chipMinWidth).apply { + duration = 383 + addUpdateListener { + currentAnimatedView?.apply { + updateAnimatedViewBoundsWidth(it.animatedValue as Int) + } + } } + return moveOut } private fun init() { @@ -144,7 +227,6 @@ class SystemEventChipAnimationController @Inject constructor( statusBarWindowController.addViewToWindow(animationWindowView, lp) animationWindowView.clipToPadding = false animationWindowView.clipChildren = false - animationWindowView.measureAllChildren = true } private fun layoutParamsDefault(marginEnd: Int): FrameLayout.LayoutParams = @@ -153,29 +235,55 @@ class SystemEventChipAnimationController @Inject constructor( it.marginEnd = marginEnd } - private fun updateAnimatedViewBoundsForAmount(amt: Float, chip: BackgroundAnimatableView) { + private fun initializeAnimRect() = animRect.set( + chipLeft, + currentAnimatedView!!.view.top, + chipRight, + currentAnimatedView!!.view.bottom) + + /** + * To be called during an animation, sets the width and updates the current animated chip view + */ + private fun updateAnimatedViewBoundsWidth(width: Int) { when (animationDirection) { LEFT -> { - chip.setBoundsForAnimation( - (chipRight - (chipWidth * amt)).toInt(), - chip.view.top, - chipRight, - chip.view.bottom) - } - else /* RIGHT */ -> { - chip.setBoundsForAnimation( - chipLeft, - chip.view.top, - (chipLeft + (chipWidth * amt)).toInt(), - chip.view.bottom) + animRect.set((chipRight - width), animRect.top, chipRight, animRect.bottom) + } else /* RIGHT */ -> { + animRect.set(chipLeft, animRect.top, (chipLeft + width), animRect.bottom) } } + + updateCurrentAnimatedView() } - private fun start() = if (animationWindowView.isLayoutRtl) right() else left() - private fun right() = contentInsetsProvider.getStatusBarContentAreaForCurrentRotation().right - private fun left() = contentInsetsProvider.getStatusBarContentAreaForCurrentRotation().left - private fun Float.amt() = 0.01f.coerceAtLeast(this) + /** + * To be called during an animation, updates the animation rect and sends the update to the chip + */ + private fun updateAnimatedViewBoundsHeight(height: Int, verticalCenter: Int) { + animRect.set( + animRect.left, + verticalCenter - (height.toFloat() / 2).roundToInt(), + animRect.right, + verticalCenter + (height.toFloat() / 2).roundToInt()) + + updateCurrentAnimatedView() + } + + /** + * To be called during an animation, updates the animation rect offset and updates the chip + */ + private fun updateAnimatedBoundsX(translation: Int) { + currentAnimatedView?.view?.translationX = translation.toFloat() + } + + /** + * To be called during an animation. Sets the chip rect to animRect + */ + private fun updateCurrentAnimatedView() { + currentAnimatedView?.setBoundsForAnimation( + animRect.left, animRect.top, animRect.right, animRect.bottom + ) + } } /** diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt index 947f3eb2ee12..36233e4e3eab 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/events/SystemStatusAnimationScheduler.kt @@ -19,14 +19,12 @@ package com.android.systemui.statusbar.events import android.animation.Animator import android.animation.AnimatorListenerAdapter import android.animation.AnimatorSet -import android.animation.ValueAnimator import android.annotation.IntDef import android.os.Process import android.provider.DeviceConfig import android.util.Log +import android.view.animation.PathInterpolator import com.android.systemui.Dumpable -import com.android.systemui.animation.Interpolators.STANDARD_ACCELERATE -import com.android.systemui.animation.Interpolators.STANDARD_DECELERATE import com.android.systemui.dagger.SysUISingleton import com.android.systemui.dagger.qualifiers.Main @@ -38,6 +36,7 @@ import com.android.systemui.util.concurrency.DelayableExecutor import com.android.systemui.util.time.SystemClock import java.io.FileDescriptor import java.io.PrintWriter +import java.lang.IllegalStateException import javax.inject.Inject @@ -116,7 +115,10 @@ class SystemStatusAnimationScheduler @Inject constructor( scheduledEvent?.updateFromEvent(event) if (event.forceVisible) { hasPersistentDot = true - notifyTransitionToPersistentDot() + // If we missed the chance to show the persistent dot, do it now + if (animationState == IDLE) { + notifyTransitionToPersistentDot() + } } } else { if (DEBUG) { @@ -162,68 +164,90 @@ class SystemStatusAnimationScheduler @Inject constructor( return } - // Schedule the animation to start after a debounce period - cancelExecutionRunnable = executor.executeDelayed({ - cancelExecutionRunnable = null - animationState = ANIMATING_IN - statusBarWindowController.setForceStatusBarVisible(true) - - val entranceAnimator = ValueAnimator.ofFloat(1f, 0f) - entranceAnimator.duration = ENTRANCE_ANIM_LENGTH - entranceAnimator.addListener(systemAnimatorAdapter) - entranceAnimator.addUpdateListener(systemUpdateListener) - entranceAnimator.interpolator = STANDARD_ACCELERATE - - val chipAnimator = ValueAnimator.ofFloat(0f, 1f) - chipAnimator.duration = CHIP_ANIM_LENGTH - chipAnimator.addListener( - ChipAnimatorAdapter(RUNNING_CHIP_ANIM, scheduledEvent!!.viewCreator)) - chipAnimator.addUpdateListener(chipUpdateListener) - chipAnimator.interpolator = STANDARD_DECELERATE - - val aSet2 = AnimatorSet() - aSet2.playSequentially(entranceAnimator, chipAnimator) - aSet2.start() - - executor.executeDelayed({ - animationState = ANIMATING_OUT - - val systemAnimator = ValueAnimator.ofFloat(0f, 1f) - systemAnimator.duration = ENTRANCE_ANIM_LENGTH - systemAnimator.addListener(systemAnimatorAdapter) - systemAnimator.addUpdateListener(systemUpdateListener) - systemAnimator.interpolator = STANDARD_DECELERATE - systemAnimator.addListener(object : AnimatorListenerAdapter() { - override fun onAnimationEnd(animation: Animator?) { - statusBarWindowController.setForceStatusBarVisible(false) + chipAnimationController.prepareChipAnimation(scheduledEvent!!.viewCreator) + animationState = ANIMATION_QUEUED + executor.executeDelayed({ + runChipAnimation() + }, DEBOUNCE_DELAY) + } + + /** + * 1. Define a total budget for the chip animation (1500ms) + * 2. Send out callbacks to listeners so that they can generate animations locally + * 3. Update the scheduler state so that clients know where we are + * 4. Maybe: provide scaffolding such as: dot location, margins, etc + * 5. Maybe: define a maximum animation length and enforce it. Probably only doable if we + * collect all of the animators and run them together. + */ + private fun runChipAnimation() { + statusBarWindowController.setForceStatusBarVisible(true) + animationState = ANIMATING_IN + + val animSet = collectStartAnimations() + if (animSet.totalDuration > 500) { + throw IllegalStateException("System animation total length exceeds budget. " + + "Expected: 500, actual: ${animSet.totalDuration}") + } + animSet.addListener(object : AnimatorListenerAdapter() { + override fun onAnimationEnd(animation: Animator?) { + animationState = RUNNING_CHIP_ANIM + } + }) + animSet.start() + + executor.executeDelayed({ + val animSet2 = collectFinishAnimations() + animationState = ANIMATING_OUT + animSet2.addListener(object : AnimatorListenerAdapter() { + override fun onAnimationEnd(animation: Animator?) { + animationState = if (hasPersistentDot) { + SHOWING_PERSISTENT_DOT + } else { + IDLE } - }) - - val chipAnimator = ValueAnimator.ofFloat(1f, 0f) - chipAnimator.duration = CHIP_ANIM_LENGTH - val endState = if (hasPersistentDot) { - SHOWING_PERSISTENT_DOT - } else { - IDLE + + statusBarWindowController.setForceStatusBarVisible(false) } - chipAnimator.addListener( - ChipAnimatorAdapter(endState, scheduledEvent!!.viewCreator)) - chipAnimator.addUpdateListener(chipUpdateListener) - chipAnimator.interpolator = STANDARD_ACCELERATE + }) + animSet2.start() + scheduledEvent = null + }, DISPLAY_LENGTH) + } - val aSet2 = AnimatorSet() + private fun collectStartAnimations(): AnimatorSet { + val animators = mutableListOf<Animator>() + listeners.forEach { listener -> + listener.onSystemEventAnimationBegin()?.let { anim -> + animators.add(anim) + } + } + animators.add(chipAnimationController.onSystemEventAnimationBegin()) + val animSet = AnimatorSet().also { + it.playTogether(animators) + } - aSet2.play(chipAnimator).before(systemAnimator) - if (hasPersistentDot) { - val dotAnim = notifyTransitionToPersistentDot() - if (dotAnim != null) aSet2.playTogether(systemAnimator, dotAnim) - } + return animSet + } - aSet2.start() + private fun collectFinishAnimations(): AnimatorSet { + val animators = mutableListOf<Animator>() + listeners.forEach { listener -> + listener.onSystemEventAnimationFinish(hasPersistentDot)?.let { anim -> + animators.add(anim) + } + } + animators.add(chipAnimationController.onSystemEventAnimationFinish(hasPersistentDot)) + if (hasPersistentDot) { + val dotAnim = notifyTransitionToPersistentDot() + if (dotAnim != null) { + animators.add(dotAnim) + } + } + val animSet = AnimatorSet().also { + it.playTogether(animators) + } - scheduledEvent = null - }, DISPLAY_LENGTH) - }, DELAY) + return animSet } private fun notifyTransitionToPersistentDot(): Animator? { @@ -257,18 +281,6 @@ class SystemStatusAnimationScheduler @Inject constructor( return null } - private fun notifySystemStart() { - listeners.forEach { it.onSystemChromeAnimationStart() } - } - - private fun notifySystemFinish() { - listeners.forEach { it.onSystemChromeAnimationEnd() } - } - - private fun notifySystemAnimationUpdate(anim: ValueAnimator) { - listeners.forEach { it.onSystemChromeAnimationUpdate(anim) } - } - override fun addCallback(listener: SystemStatusAnimationCallback) { Assert.isMainThread() @@ -287,24 +299,6 @@ class SystemStatusAnimationScheduler @Inject constructor( } } - private val systemUpdateListener = ValueAnimator.AnimatorUpdateListener { - anim -> notifySystemAnimationUpdate(anim) - } - - private val systemAnimatorAdapter = object : AnimatorListenerAdapter() { - override fun onAnimationEnd(p0: Animator?) { - notifySystemFinish() - } - - override fun onAnimationStart(p0: Animator?) { - notifySystemStart() - } - } - - private val chipUpdateListener = ValueAnimator.AnimatorUpdateListener { - anim -> chipAnimationController.onChipAnimationUpdate(anim, animationState) - } - override fun dump(fd: FileDescriptor, pw: PrintWriter, args: Array<out String>) { pw.println("Scheduled event: $scheduledEvent") pw.println("Has persistent privacy dot: $hasPersistentDot") @@ -318,24 +312,6 @@ class SystemStatusAnimationScheduler @Inject constructor( } } } - - inner class ChipAnimatorAdapter( - @SystemAnimationState val endState: Int, - val viewCreator: ViewCreator - ) : AnimatorListenerAdapter() { - override fun onAnimationEnd(p0: Animator?) { - chipAnimationController.onChipAnimationEnd(animationState) - animationState = if (endState == SHOWING_PERSISTENT_DOT && !hasPersistentDot) { - IDLE - } else { - endState - } - } - - override fun onAnimationStart(p0: Animator?) { - chipAnimationController.onChipAnimationStart(viewCreator, animationState) - } - } } /** @@ -344,16 +320,14 @@ class SystemStatusAnimationScheduler @Inject constructor( * create space for the chip animation to display. This means hiding the system elements in the * status bar and keyguard. * - * TODO: the chip animation really only has one client, we can probably remove it from this - * interface - * * The value animators themselves are simple animators from 0.0 to 1.0. Listeners can apply any * interpolation they choose but realistically these are most likely to be simple alpha transitions */ interface SystemStatusAnimationCallback { - @JvmDefault fun onSystemChromeAnimationUpdate(animator: ValueAnimator) {} - @JvmDefault fun onSystemChromeAnimationStart() {} - @JvmDefault fun onSystemChromeAnimationEnd() {} + /** Implement this method to return an [Animator] or [AnimatorSet] that presents the chip */ + fun onSystemEventAnimationBegin(): Animator? { return null } + /** Implement this method to return an [Animator] or [AnimatorSet] that hides the chip */ + fun onSystemEventAnimationFinish(hasPersistentDot: Boolean): Animator? { return null } // Best method name, change my mind @JvmDefault @@ -363,50 +337,61 @@ interface SystemStatusAnimationCallback { @JvmDefault fun onHidePersistentDot(): Animator? { return null } } -interface SystemStatusChipAnimationCallback { - fun onChipAnimationUpdate(animator: ValueAnimator, @SystemAnimationState state: Int) {} - - fun onChipAnimationStart( - viewCreator: ViewCreator, - @SystemAnimationState state: Int - ) {} - - fun onChipAnimationEnd(@SystemAnimationState state: Int) {} -} - /** + * Animation state IntDef */ @Retention(AnnotationRetention.SOURCE) @IntDef( value = [ - IDLE, ANIMATING_IN, RUNNING_CHIP_ANIM, ANIMATING_OUT, SHOWING_PERSISTENT_DOT + IDLE, + ANIMATION_QUEUED, + ANIMATING_IN, + RUNNING_CHIP_ANIM, + ANIMATING_OUT, + SHOWING_PERSISTENT_DOT ] ) annotation class SystemAnimationState /** No animation is in progress */ const val IDLE = 0 +/** An animation is queued, and awaiting the debounce period */ +const val ANIMATION_QUEUED = 1 /** System is animating out, and chip is animating in */ -const val ANIMATING_IN = 1 +const val ANIMATING_IN = 2 /** Chip has animated in and is awaiting exit animation, and optionally playing its own animation */ -const val RUNNING_CHIP_ANIM = 2 +const val RUNNING_CHIP_ANIM = 3 /** Chip is animating away and system is animating back */ -const val ANIMATING_OUT = 3 +const val ANIMATING_OUT = 4 /** Chip has animated away, and the persistent dot is showing */ -const val SHOWING_PERSISTENT_DOT = 4 +const val SHOWING_PERSISTENT_DOT = 5 + +/** Commonly-needed interpolators can go here */ +@JvmField val STATUS_BAR_X_MOVE_OUT = PathInterpolator(0.33f, 0f, 0f, 1f) +@JvmField val STATUS_BAR_X_MOVE_IN = PathInterpolator(0f, 0f, 0f, 1f) +/** + * Status chip animation to dot have multiple stages of motion, the _1 and _2 interpolators should + * be used in succession + */ +val STATUS_CHIP_WIDTH_TO_DOT_KEYFRAME_1 = PathInterpolator(0.44f, 0f, 0.25f, 1f) +val STATUS_CHIP_WIDTH_TO_DOT_KEYFRAME_2 = PathInterpolator(0.3f, 0f, 0.26f, 1f) +val STATUS_CHIP_HEIGHT_TO_DOT_KEYFRAME_1 = PathInterpolator(0.4f, 0f, 0.17f, 1f) +val STATUS_CHIP_HEIGHT_TO_DOT_KEYFRAME_2 = PathInterpolator(0.3f, 0f, 0f, 1f) +val STATUS_CHIP_MOVE_TO_DOT = PathInterpolator(0f, 0f, 0.05f, 1f) private const val TAG = "SystemStatusAnimationScheduler" -private const val DELAY = 0L +private const val DEBOUNCE_DELAY = 100L /** - * The total time spent animation should be 1500ms. The entrance animation is how much time - * we give to the system to animate system elements out of the way. Total chip animation length - * will be equivalent to 2*chip_anim_length + display_length + * The total time spent on the chip animation is 1500ms, broken up into 3 sections: + * - 500ms to animate the chip in (including animating system icons away) + * - 500ms holding the chip on screen + * - 500ms to animate the chip away (and system icons back) + * + * So DISPLAY_LENGTH should be the sum of the first 2 phases, while the final 500ms accounts for + * the actual animation */ -private const val ENTRANCE_ANIM_LENGTH = 250L -private const val CHIP_ANIM_LENGTH = 250L -// 1s + entrance time + chip anim_length -private const val DISPLAY_LENGTH = 1500L +private const val DISPLAY_LENGTH = 1000L private const val MIN_UPTIME: Long = 5 * 1000 diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationLaunchAnimatorController.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationLaunchAnimatorController.kt index 7fbb0f1182c0..02aa1f2fd585 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationLaunchAnimatorController.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/NotificationLaunchAnimatorController.kt @@ -25,7 +25,7 @@ class NotificationLaunchAnimatorControllerProvider @Inject constructor( @JvmOverloads fun getAnimatorController( notification: ExpandableNotificationRow, - onFinishAnimationCallback: Runnable = Runnable {} + onFinishAnimationCallback: Runnable? = null ): NotificationLaunchAnimatorController { return NotificationLaunchAnimatorController( notificationShadeWindowViewController, @@ -49,7 +49,7 @@ class NotificationLaunchAnimatorController( private val headsUpManager: HeadsUpManagerPhone, private val notification: ExpandableNotificationRow, private val jankMonitor: InteractionJankMonitor, - private val onFinishAnimationCallback: Runnable + private val onFinishAnimationCallback: Runnable? ) : ActivityLaunchAnimator.Controller { companion object { @@ -123,7 +123,7 @@ class NotificationLaunchAnimatorController( if (!willAnimate) { removeHun(animate = true) - onFinishAnimationCallback.run() + onFinishAnimationCallback?.run() } } @@ -142,7 +142,7 @@ class NotificationLaunchAnimatorController( notificationShadeWindowViewController.setExpandAnimationRunning(false) notificationEntry.isExpandAnimationRunning = false removeHun(animate = true) - onFinishAnimationCallback.run() + onFinishAnimationCallback?.run() } override fun onLaunchAnimationStart(isExpandingFullyAbove: Boolean) { @@ -162,7 +162,7 @@ class NotificationLaunchAnimatorController( notificationListContainer.setExpandingNotification(null) applyParams(null) removeHun(animate = false) - onFinishAnimationCallback.run() + onFinishAnimationCallback?.run() } private fun applyParams(params: ExpandAnimationParameters?) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java index 65173a230871..cb332bdf59b1 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarView.java @@ -174,7 +174,7 @@ public class KeyguardStatusBarView extends RelativeLayout { } private void updateKeyguardStatusBarHeight() { - MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams(); + MarginLayoutParams lp = (MarginLayoutParams) getLayoutParams(); lp.height = getStatusBarHeaderHeightKeyguard(mContext); setLayoutParams(lp); } @@ -510,28 +510,6 @@ public class KeyguardStatusBarView extends RelativeLayout { } } - void onSystemChromeAnimationStart(boolean isAnimatingOut) { - if (isAnimatingOut) { - mSystemIconsContainer.setVisibility(View.VISIBLE); - mSystemIconsContainer.setAlpha(0f); - } - } - - void onSystemChromeAnimationEnd(boolean isAnimatingIn) { - // Make sure the system icons are out of the way - if (isAnimatingIn) { - mSystemIconsContainer.setVisibility(View.INVISIBLE); - mSystemIconsContainer.setAlpha(0f); - } else { - mSystemIconsContainer.setAlpha(1f); - mSystemIconsContainer.setVisibility(View.VISIBLE); - } - } - - void onSystemChromeAnimationUpdate(float animatedValue) { - mSystemIconsContainer.setAlpha(animatedValue); - } - @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewController.java index 1df1aff38593..af4fb8e2cf49 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/KeyguardStatusBarViewController.java @@ -17,8 +17,6 @@ package com.android.systemui.statusbar.phone; import static com.android.systemui.statusbar.StatusBarState.KEYGUARD; -import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.ANIMATING_IN; -import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.ANIMATING_OUT; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; @@ -47,6 +45,7 @@ import com.android.systemui.statusbar.notification.AnimatableProperty; import com.android.systemui.statusbar.notification.PropertyAnimator; import com.android.systemui.statusbar.notification.stack.AnimationProperties; import com.android.systemui.statusbar.notification.stack.StackStateAnimator; +import com.android.systemui.statusbar.phone.fragment.StatusBarSystemEventAnimator; import com.android.systemui.statusbar.phone.userswitcher.StatusBarUserInfoTracker; import com.android.systemui.statusbar.phone.userswitcher.StatusBarUserSwitcherController; import com.android.systemui.statusbar.phone.userswitcher.StatusBarUserSwitcherFeatureController; @@ -107,6 +106,8 @@ public class KeyguardStatusBarViewController extends ViewController<KeyguardStat @Override public void onDensityOrFontScaleChanged() { mView.loadDimens(); + // The animator is dependent on resources for offsets + mSystemEventAnimator = new StatusBarSystemEventAnimator(mView, getResources()); } @Override @@ -123,21 +124,16 @@ public class KeyguardStatusBarViewController extends ViewController<KeyguardStat private final SystemStatusAnimationCallback mAnimationCallback = new SystemStatusAnimationCallback() { + @NonNull @Override - public void onSystemChromeAnimationStart() { - mView.onSystemChromeAnimationStart( - mAnimationScheduler.getAnimationState() == ANIMATING_OUT); + public Animator onSystemEventAnimationFinish(boolean hasPersistentDot) { + return mSystemEventAnimator.onSystemEventAnimationFinish(hasPersistentDot); } + @NonNull @Override - public void onSystemChromeAnimationEnd() { - mView.onSystemChromeAnimationEnd( - mAnimationScheduler.getAnimationState() == ANIMATING_IN); - } - - @Override - public void onSystemChromeAnimationUpdate(@NonNull ValueAnimator anim) { - mView.onSystemChromeAnimationUpdate((float) anim.getAnimatedValue()); + public Animator onSystemEventAnimationBegin() { + return mSystemEventAnimator.onSystemEventAnimationBegin(); } }; @@ -232,6 +228,7 @@ public class KeyguardStatusBarViewController extends ViewController<KeyguardStat private int mStatusBarState; private boolean mDozing; private boolean mShowingKeyguardHeadsUp; + private StatusBarSystemEventAnimator mSystemEventAnimator; @Inject public KeyguardStatusBarViewController( @@ -302,6 +299,7 @@ public class KeyguardStatusBarViewController extends ViewController<KeyguardStat mView.setKeyguardUserAvatarEnabled( !mFeatureController.isStatusBarUserSwitcherFeatureEnabled()); mFeatureController.addCallback(enabled -> mView.setKeyguardUserAvatarEnabled(!enabled)); + mSystemEventAnimator = new StatusBarSystemEventAnimator(mView, r); } @Override diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java index 419661b766d6..1ad365bf6d7b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ScrimController.java @@ -116,6 +116,15 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, Dump private float mTransitionToFullShadeProgress; /** + * Same as {@link #mTransitionToFullShadeProgress}, but specifically for the notifications scrim + * on the lock screen. + * + * On split shade lock screen we want the different scrims to fade in at different times and + * rates. + */ + private float mTransitionToLockScreenFullShadeNotificationsProgress; + + /** * If we're currently transitioning to the full shade. */ private boolean mTransitioningToFullShade; @@ -574,11 +583,17 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, Dump * Set the amount of progress we are currently in if we're transitioning to the full shade. * 0.0f means we're not transitioning yet, while 1 means we're all the way in the full * shade. + * + * @param progress the progress for all scrims. + * @param lockScreenNotificationsProgress the progress specifically for the notifications scrim. */ - public void setTransitionToFullShadeProgress(float progress) { - if (progress != mTransitionToFullShadeProgress) { + public void setTransitionToFullShadeProgress(float progress, + float lockScreenNotificationsProgress) { + if (progress != mTransitionToFullShadeProgress || lockScreenNotificationsProgress + != mTransitionToLockScreenFullShadeNotificationsProgress) { mTransitionToFullShadeProgress = progress; - setTransitionToFullShade(progress > 0.0f); + mTransitionToLockScreenFullShadeNotificationsProgress = lockScreenNotificationsProgress; + setTransitionToFullShade(progress > 0.0f || lockScreenNotificationsProgress > 0.0f); applyAndDispatchState(); } } @@ -754,12 +769,13 @@ public class ScrimController implements ViewTreeObserver.OnPreDrawListener, Dump } else { mNotificationsAlpha = Math.max(1.0f - getInterpolatedFraction(), mQsExpansion); } - if (mState == ScrimState.KEYGUARD && mTransitionToFullShadeProgress > 0.0f) { + if (mState == ScrimState.KEYGUARD + && mTransitionToLockScreenFullShadeNotificationsProgress > 0.0f) { // Interpolate the notification alpha when transitioning! mNotificationsAlpha = MathUtils.lerp( mNotificationsAlpha, getInterpolatedFraction(), - mTransitionToFullShadeProgress); + mTransitionToLockScreenFullShadeNotificationsProgress); } mNotificationsTint = mState.getNotifTint(); mBehindTint = behindTint; diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java index 637e4bee8948..6fe92fafc075 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarter.java @@ -397,15 +397,25 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte mMainThreadHandler.post(() -> { final Runnable removeNotification = () -> { mOnUserInteractionCallback.onDismiss(entry, REASON_CLICK, summaryToRemove); + if (!animate) { + // If we're animating, this would be invoked after the activity launch + // animation completes. Since we're not animating, the launch already + // happened synchronously, so we notify the launch is complete here after + // onDismiss. + mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry); + } }; if (mPresenter.isCollapsing()) { - // To avoid lags we're only performing the remove - // after the shade is collapsed + // To avoid lags we're only performing the remove after the shade is collapsed mShadeController.addPostCollapseAction(removeNotification); } else { removeNotification.run(); } }); + } else if (!canBubble && !animate) { + // Not animating, this is the end of the launch flow (see above comment for more info). + mMainThreadHandler.post( + () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry)); } mIsCollapsingToShowActivityOverLockscreen = false; @@ -481,8 +491,9 @@ class StatusBarNotificationActivityStarter implements NotificationActivityStarte boolean isActivityIntent) { mLogger.logStartNotificationIntent(entry.getKey(), intent); try { - Runnable onFinishAnimationCallback = - () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry); + Runnable onFinishAnimationCallback = animate + ? () -> mLaunchEventsEmitter.notifyFinishLaunchNotifActivity(entry) + : null; ActivityLaunchAnimator.Controller animationController = new StatusBarLaunchAnimatorController( mNotificationAnimationProvider diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java index 2c84219dbfd0..33bc40119745 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/CollapsedStatusBarFragment.java @@ -20,12 +20,10 @@ import static android.app.StatusBarManager.DISABLE_NOTIFICATION_ICONS; import static android.app.StatusBarManager.DISABLE_ONGOING_CALL_CHIP; import static android.app.StatusBarManager.DISABLE_SYSTEM_INFO; -import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.ANIMATING_IN; -import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.ANIMATING_OUT; import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.IDLE; import static com.android.systemui.statusbar.events.SystemStatusAnimationSchedulerKt.SHOWING_PERSISTENT_DOT; -import android.animation.ValueAnimator; +import android.animation.Animator; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.SuppressLint; @@ -136,6 +134,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue } }; private OperatorNameViewController mOperatorNameViewController; + private StatusBarSystemEventAnimator mSystemEventAnimator; @SuppressLint("ValidFragment") public CollapsedStatusBarFragment( @@ -210,7 +209,8 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue initEmergencyCryptkeeperText(); initOperatorName(); initNotificationIconArea(); - mAnimationScheduler.addCallback(this); + mSystemEventAnimator = + new StatusBarSystemEventAnimator(mSystemIconArea, getResources()); } @VisibleForTesting @@ -245,6 +245,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue mCommandQueue.addCallback(this); mStatusBarStateController.addCallback(this); initOngoingCallChip(); + mAnimationScheduler.addCallback(this); mSecureSettings.registerContentObserver( Settings.Secure.getUriFor(Settings.Secure.STATUS_BAR_SHOW_VIBRATE_ICON), @@ -258,6 +259,7 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue mCommandQueue.removeCallback(this); mStatusBarStateController.removeCallback(this); mOngoingCallController.removeCallback(mOngoingCallListener); + mAnimationScheduler.removeCallback(this); mSecureSettings.unregisterContentObserver(mVolumeSettingObserver); } @@ -265,7 +267,6 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue public void onDestroyView() { super.onDestroyView(); mStatusBarIconController.removeIconGroup(mDarkIconManager); - mAnimationScheduler.removeCallback(this); if (mNetworkController.hasEmergencyCryptKeeperText()) { mNetworkController.removeCallback(mSignalCallback); } @@ -576,35 +577,16 @@ public class CollapsedStatusBarFragment extends Fragment implements CommandQueue disable(getContext().getDisplayId(), mDisabled1, mDisabled2, false /* animate */); } + @Nullable @Override - public void onSystemChromeAnimationStart() { - if (mAnimationScheduler.getAnimationState() == ANIMATING_OUT - && !isSystemIconAreaDisabled()) { - mSystemIconArea.setVisibility(View.VISIBLE); - mSystemIconArea.setAlpha(0f); - } - } - - @Override - public void onSystemChromeAnimationEnd() { - // Make sure the system icons are out of the way - if (mAnimationScheduler.getAnimationState() == ANIMATING_IN) { - mSystemIconArea.setVisibility(View.INVISIBLE); - mSystemIconArea.setAlpha(0f); - } else { - if (isSystemIconAreaDisabled()) { - // don't unhide - return; - } - - mSystemIconArea.setAlpha(1f); - mSystemIconArea.setVisibility(View.VISIBLE); - } + public Animator onSystemEventAnimationBegin() { + return mSystemEventAnimator.onSystemEventAnimationBegin(); } + @Nullable @Override - public void onSystemChromeAnimationUpdate(@NonNull ValueAnimator animator) { - mSystemIconArea.setAlpha((float) animator.getAnimatedValue()); + public Animator onSystemEventAnimationFinish(boolean hasPersistentDot) { + return mSystemEventAnimator.onSystemEventAnimationFinish(hasPersistentDot); } private boolean isSystemIconAreaDisabled() { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/StatusBarSystemEventAnimator.kt b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/StatusBarSystemEventAnimator.kt new file mode 100644 index 000000000000..f530ec83aec5 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/fragment/StatusBarSystemEventAnimator.kt @@ -0,0 +1,84 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.systemui.statusbar.phone.fragment + +import android.animation.Animator +import android.animation.AnimatorSet +import android.animation.ValueAnimator +import android.content.res.Resources +import android.view.View +import com.android.systemui.R +import com.android.systemui.statusbar.events.STATUS_BAR_X_MOVE_IN +import com.android.systemui.statusbar.events.STATUS_BAR_X_MOVE_OUT +import com.android.systemui.statusbar.events.SystemStatusAnimationCallback + +/** + * Tied directly to [SystemStatusAnimationScheduler]. Any StatusBar-like thing (keyguard, collapsed + * status bar fragment), can just feed this an animatable view to get the default system status + * animation. + * + * This animator relies on resources, and should be recreated whenever resources are updated. While + * this class could be used directly as the animation callback, it's probably best to forward calls + * to it so that it can be recreated at any moment without needing to remove/add callback. + */ +class StatusBarSystemEventAnimator( + val animatedView: View, + resources: Resources +) : SystemStatusAnimationCallback { + private val translationXIn: Int = resources.getDimensionPixelSize( + R.dimen.ongoing_appops_chip_animation_in_status_bar_translation_x) + private val translationXOut: Int = resources.getDimensionPixelSize( + R.dimen.ongoing_appops_chip_animation_out_status_bar_translation_x) + + override fun onSystemEventAnimationBegin(): Animator { + val moveOut = ValueAnimator.ofFloat(0f, 1f).setDuration(383) + moveOut.interpolator = STATUS_BAR_X_MOVE_OUT + moveOut.addUpdateListener { animation: ValueAnimator -> + animatedView.translationX = -(translationXIn * animation.animatedValue as Float) + } + val alphaOut = ValueAnimator.ofFloat(1f, 0f).setDuration(133) + alphaOut.interpolator = null + alphaOut.addUpdateListener { animation: ValueAnimator -> + animatedView.alpha = animation.animatedValue as Float + } + + val animSet = AnimatorSet() + animSet.playTogether(moveOut, alphaOut) + return animSet + } + + override fun onSystemEventAnimationFinish(hasPersistentDot: Boolean): Animator { + animatedView.translationX = translationXOut.toFloat() + val moveIn = ValueAnimator.ofFloat(1f, 0f).setDuration(467) + moveIn.startDelay = 33 + moveIn.interpolator = STATUS_BAR_X_MOVE_IN + moveIn.addUpdateListener { animation: ValueAnimator -> + animatedView.translationX = translationXOut * animation.animatedValue as Float + } + val alphaIn = ValueAnimator.ofFloat(0f, 1f).setDuration(167) + alphaIn.startDelay = 67 + alphaIn.interpolator = null + alphaIn.addUpdateListener { animation: ValueAnimator -> + animatedView.alpha = animation.animatedValue as Float + } + + val animatorSet = AnimatorSet() + animatorSet.playTogether(moveIn, alphaIn) + + return animatorSet + } +}
\ No newline at end of file diff --git a/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java b/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java index 7a0db1fd975c..8c7927782d2d 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java +++ b/packages/SystemUI/tests/src/com/android/systemui/SysuiTestCase.java @@ -208,6 +208,11 @@ public abstract class SysuiTestCase { } } + /** Delegates to {@link android.testing.TestableResources#addOverride(int, Object)}. */ + protected void overrideResource(int resourceId, Object value) { + mContext.getOrCreateTestableResources().addOverride(resourceId, value); + } + public static final class EmptyRunnable implements Runnable { public void run() { } diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthRippleControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthRippleControllerTest.kt index ec2c1de49b4c..a95da6295350 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthRippleControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthRippleControllerTest.kt @@ -114,12 +114,13 @@ class AuthRippleControllerTest : SysuiTestCase() { } @Test - fun testFingerprintTrigger_Ripple() { + fun testFingerprintTrigger_KeyguardVisible_Ripple() { // GIVEN fp exists, keyguard is visible, user doesn't need strong auth val fpsLocation = PointF(5f, 5f) `when`(authController.fingerprintSensorLocation).thenReturn(fpsLocation) controller.onViewAttached() `when`(keyguardUpdateMonitor.isKeyguardVisible).thenReturn(true) + `when`(keyguardUpdateMonitor.isDreaming).thenReturn(false) `when`(keyguardUpdateMonitor.userNeedsStrongAuth()).thenReturn(false) // WHEN fingerprint authenticated @@ -136,7 +137,30 @@ class AuthRippleControllerTest : SysuiTestCase() { } @Test - fun testFingerprintTrigger_KeyguardNotVisible_NoRipple() { + fun testFingerprintTrigger_Dreaming_Ripple() { + // GIVEN fp exists, keyguard is visible, user doesn't need strong auth + val fpsLocation = PointF(5f, 5f) + `when`(authController.fingerprintSensorLocation).thenReturn(fpsLocation) + controller.onViewAttached() + `when`(keyguardUpdateMonitor.isKeyguardVisible).thenReturn(false) + `when`(keyguardUpdateMonitor.isDreaming).thenReturn(true) + `when`(keyguardUpdateMonitor.userNeedsStrongAuth()).thenReturn(false) + + // WHEN fingerprint authenticated + val captor = ArgumentCaptor.forClass(KeyguardUpdateMonitorCallback::class.java) + verify(keyguardUpdateMonitor).registerCallback(captor.capture()) + captor.value.onBiometricAuthenticated( + 0 /* userId */, + BiometricSourceType.FINGERPRINT /* type */, + false /* isStrongBiometric */) + + // THEN update sensor location and show ripple + verify(rippleView).setFingerprintSensorLocation(fpsLocation, -1f) + verify(rippleView).startUnlockedRipple(any()) + } + + @Test + fun testFingerprintTrigger_KeyguardNotVisible_NotDreaming_NoRipple() { // GIVEN fp exists & user doesn't need strong auth val fpsLocation = PointF(5f, 5f) `when`(authController.udfpsSensorLocation).thenReturn(fpsLocation) @@ -145,6 +169,7 @@ class AuthRippleControllerTest : SysuiTestCase() { // WHEN keyguard is NOT visible & fingerprint authenticated `when`(keyguardUpdateMonitor.isKeyguardVisible).thenReturn(false) + `when`(keyguardUpdateMonitor.isDreaming).thenReturn(false) val captor = ArgumentCaptor.forClass(KeyguardUpdateMonitorCallback::class.java) verify(keyguardUpdateMonitor).registerCallback(captor.capture()) captor.value.onBiometricAuthenticated( diff --git a/packages/SystemUI/tests/src/com/android/systemui/media/MediaHierarchyManagerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/media/MediaHierarchyManagerTest.kt index 8e201b5a3e87..203eb47165e0 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/media/MediaHierarchyManagerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/media/MediaHierarchyManagerTest.kt @@ -223,6 +223,18 @@ class MediaHierarchyManagerTest : SysuiTestCase() { } @Test + fun calculateTransformationType_onLockSplitShade_goingToFullShade_mediaInvisible_returnsFade() { + enableSplitShade() + goToLockscreen() + expandQS() + whenever(lockHost.visible).thenReturn(false) + mediaHiearchyManager.setTransitionToFullShadeAmount(10000f) + + val transformType = mediaHiearchyManager.calculateTransformationType() + assertThat(transformType).isEqualTo(MediaHierarchyManager.TRANSFORMATION_TYPE_FADE) + } + + @Test fun calculateTransformationType_onLockShade_inSplitShade_notExpanding_returnsFade() { enableSplitShade() goToLockscreen() diff --git a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogControllerTest.kt index 350822691121..38b448fb362c 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/privacy/PrivacyDialogControllerTest.kt @@ -19,8 +19,11 @@ package com.android.systemui.privacy import android.app.ActivityManager import android.content.Context import android.content.Intent +import android.content.pm.ActivityInfo import android.content.pm.ApplicationInfo import android.content.pm.PackageManager +import android.content.pm.PackageManager.ResolveInfoFlags +import android.content.pm.ResolveInfo import android.content.pm.UserInfo import android.os.Process.SYSTEM_UID import android.os.UserHandle @@ -648,6 +651,77 @@ class PrivacyDialogControllerTest : SysuiTestCase() { } } + @Test + fun testCorrectIntentSubAttribution() { + val usage = createMockPermGroupUsage( + attributionTag = TEST_ATTRIBUTION_TAG, + attributionLabel = "TEST_LABEL" + ) + + val activityInfo = createMockActivityInfo() + val resolveInfo = createMockResolveInfo(activityInfo) + `when`(permissionManager.getIndicatorAppOpUsageData(anyBoolean())).thenReturn(listOf(usage)) + `when`(packageManager.resolveActivity(any(), any<ResolveInfoFlags>())) + .thenAnswer { resolveInfo } + controller.showDialog(context) + exhaustExecutors() + + dialogProvider.list?.let { list -> + val navigationIntent = list.get(0).navigationIntent!! + assertThat(navigationIntent.action).isEqualTo(Intent.ACTION_MANAGE_PERMISSION_USAGE) + assertThat(navigationIntent.getStringExtra(Intent.EXTRA_PERMISSION_GROUP_NAME)) + .isEqualTo(PERM_CAMERA) + assertThat(navigationIntent.getStringArrayExtra(Intent.EXTRA_ATTRIBUTION_TAGS)) + .isEqualTo(arrayOf(TEST_ATTRIBUTION_TAG.toString())) + assertThat(navigationIntent.getBooleanExtra(Intent.EXTRA_SHOWING_ATTRIBUTION, false)) + .isTrue() + } + } + + @Test + fun testDefaultIntentOnMissingAttributionLabel() { + val usage = createMockPermGroupUsage( + attributionTag = TEST_ATTRIBUTION_TAG + ) + + val activityInfo = createMockActivityInfo() + val resolveInfo = createMockResolveInfo(activityInfo) + `when`(permissionManager.getIndicatorAppOpUsageData(anyBoolean())).thenReturn(listOf(usage)) + `when`(packageManager.resolveActivity(any(), any<ResolveInfoFlags>())) + .thenAnswer { resolveInfo } + controller.showDialog(context) + exhaustExecutors() + + dialogProvider.list?.let { list -> + assertThat(isIntentEqual(list.get(0).navigationIntent!!, + controller.getDefaultManageAppPermissionsIntent(TEST_PACKAGE_NAME, USER_ID))) + .isTrue() + } + } + + @Test + fun testDefaultIntentOnIncorrectPermission() { + val usage = createMockPermGroupUsage( + attributionTag = TEST_ATTRIBUTION_TAG + ) + + val activityInfo = createMockActivityInfo( + permission = "INCORRECT_PERMISSION" + ) + val resolveInfo = createMockResolveInfo(activityInfo) + `when`(permissionManager.getIndicatorAppOpUsageData(anyBoolean())).thenReturn(listOf(usage)) + `when`(packageManager.resolveActivity(any(), any<ResolveInfoFlags>())) + .thenAnswer { resolveInfo } + controller.showDialog(context) + exhaustExecutors() + + dialogProvider.list?.let { list -> + assertThat(isIntentEqual(list.get(0).navigationIntent!!, + controller.getDefaultManageAppPermissionsIntent(TEST_PACKAGE_NAME, USER_ID))) + .isTrue() + } + } + private fun exhaustExecutors() { FakeExecutor.exhaustExecutors(backgroundExecutor, uiExecutor) } @@ -680,6 +754,24 @@ class PrivacyDialogControllerTest : SysuiTestCase() { return user * UserHandle.PER_USER_RANGE + nextUid++ } + private fun createMockResolveInfo( + activityInfo: ActivityInfo? = null + ): ResolveInfo { + val resolveInfo = mock(ResolveInfo::class.java) + resolveInfo.activityInfo = activityInfo + return resolveInfo + } + + private fun createMockActivityInfo( + permission: String = android.Manifest.permission.START_VIEW_PERMISSION_USAGE, + className: String = "TEST_CLASS_NAME" + ): ActivityInfo { + val activityInfo = mock(ActivityInfo::class.java) + activityInfo.permission = permission + activityInfo.name = className + return activityInfo + } + private fun createMockPermGroupUsage( packageName: String = TEST_PACKAGE_NAME, uid: Int = generateUidForUser(USER_ID), diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt index 64a0a2342a44..1d2a0ca3777a 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/LockscreenShadeTransitionControllerTest.kt @@ -1,5 +1,6 @@ package com.android.systemui.statusbar +import org.mockito.Mockito.`when` as whenever import android.test.suitebuilder.annotation.SmallTest import android.testing.AndroidTestingRunner import android.testing.TestableLooper @@ -18,11 +19,11 @@ import com.android.systemui.statusbar.notification.row.NotificationTestHelper import com.android.systemui.statusbar.notification.stack.AmbientState import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayoutController +import com.android.systemui.statusbar.phone.CentralSurfaces import com.android.systemui.statusbar.phone.KeyguardBypassController import com.android.systemui.statusbar.phone.LSShadeTransitionLogger import com.android.systemui.statusbar.phone.NotificationPanelViewController import com.android.systemui.statusbar.phone.ScrimController -import com.android.systemui.statusbar.phone.CentralSurfaces import com.android.systemui.statusbar.policy.FakeConfigurationController import org.junit.After import org.junit.Assert.assertFalse @@ -37,14 +38,13 @@ import org.mockito.ArgumentMatchers.anyBoolean import org.mockito.ArgumentMatchers.anyFloat import org.mockito.ArgumentMatchers.anyInt import org.mockito.ArgumentMatchers.anyLong +import org.mockito.ArgumentMatchers.eq import org.mockito.Mock import org.mockito.Mockito import org.mockito.Mockito.clearInvocations import org.mockito.Mockito.never import org.mockito.Mockito.verify import org.mockito.junit.MockitoJUnit -import org.mockito.Mockito.`when` as whenever -import org.mockito.ArgumentMatchers.eq private fun <T> anyObject(): T { return Mockito.anyObject<T>() @@ -231,7 +231,7 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() { transitionController.dragDownAmount = 10f verify(nsslController, never()).setTransitionToFullShadeAmount(anyFloat(), anyFloat()) verify(mediaHierarchyManager, never()).setTransitionToFullShadeAmount(anyFloat()) - verify(scrimController, never()).setTransitionToFullShadeProgress(anyFloat()) + verify(scrimController, never()).setTransitionToFullShadeProgress(anyFloat(), anyFloat()) verify(notificationPanelController, never()).setTransitionToFullShadeAmount(anyFloat(), anyBoolean(), anyLong()) verify(qS, never()).setTransitionToFullShadeAmount(anyFloat(), anyFloat()) @@ -242,7 +242,7 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() { transitionController.dragDownAmount = 10f verify(nsslController).setTransitionToFullShadeAmount(anyFloat(), anyFloat()) verify(mediaHierarchyManager).setTransitionToFullShadeAmount(anyFloat()) - verify(scrimController).setTransitionToFullShadeProgress(anyFloat()) + verify(scrimController).setTransitionToFullShadeProgress(anyFloat(), anyFloat()) verify(notificationPanelController).setTransitionToFullShadeAmount(anyFloat(), anyBoolean(), anyLong()) verify(qS).setTransitionToFullShadeAmount(anyFloat(), anyFloat()) @@ -311,6 +311,75 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() { } @Test + fun setDragAmount_setsScrimProgressBasedOnScrimDistance() { + val distance = 10 + context.orCreateTestableResources + .addOverride(R.dimen.lockscreen_shade_scrim_transition_distance, distance) + configurationController.notifyConfigurationChanged() + + transitionController.dragDownAmount = 5f + + verify(scrimController).transitionToFullShadeProgress( + progress = eq(0.5f), + lockScreenNotificationsProgress = anyFloat() + ) + } + + @Test + fun setDragAmount_setsNotificationsScrimProgressBasedOnNotificationsScrimDistanceAndDelay() { + val distance = 100 + val delay = 10 + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_distance, distance) + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_delay, delay) + configurationController.notifyConfigurationChanged() + + transitionController.dragDownAmount = 20f + + verify(scrimController).transitionToFullShadeProgress( + progress = anyFloat(), + lockScreenNotificationsProgress = eq(0.1f) + ) + } + + @Test + fun setDragAmount_dragAmountLessThanNotifDelayDistance_setsNotificationsScrimProgressToZero() { + val distance = 100 + val delay = 50 + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_distance, distance) + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_delay, delay) + configurationController.notifyConfigurationChanged() + + transitionController.dragDownAmount = 20f + + verify(scrimController).transitionToFullShadeProgress( + progress = anyFloat(), + lockScreenNotificationsProgress = eq(0f) + ) + } + + @Test + fun setDragAmount_dragAmountMoreThanTotalDistance_setsNotificationsScrimProgressToOne() { + val distance = 100 + val delay = 50 + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_distance, distance) + context.orCreateTestableResources.addOverride( + R.dimen.lockscreen_shade_notifications_scrim_transition_delay, delay) + configurationController.notifyConfigurationChanged() + + transitionController.dragDownAmount = 999999f + + verify(scrimController).transitionToFullShadeProgress( + progress = anyFloat(), + lockScreenNotificationsProgress = eq(1f) + ) + } + + @Test fun setDragDownAmount_inSplitShade_setsValueOnMediaHierarchyManager() { enableSplitShade() @@ -328,9 +397,21 @@ class LockscreenShadeTransitionControllerTest : SysuiTestCase() { } private fun setSplitShadeEnabled(enabled: Boolean) { - context.getOrCreateTestableResources().addOverride( - R.bool.config_use_split_notification_shade, enabled - ) + overrideResource(R.bool.config_use_split_notification_shade, enabled) configurationController.notifyConfigurationChanged() } + + /** + * Wrapper around [ScrimController.transitionToFullShadeProgress] that has named parameters for + * clarify and easier refactoring of parameter names. + */ + private fun ScrimController.transitionToFullShadeProgress( + progress: Float, + lockScreenNotificationsProgress: Float + ) { + scrimController.setTransitionToFullShadeProgress( + progress, + lockScreenNotificationsProgress + ) + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationQSContainerControllerTest.kt b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationQSContainerControllerTest.kt index 83eabb667997..6526fabefe49 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationQSContainerControllerTest.kt +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/NotificationQSContainerControllerTest.kt @@ -6,7 +6,6 @@ import android.view.View import android.view.ViewGroup import android.view.WindowInsets import android.view.WindowManagerPolicyConstants -import androidx.annotation.AnyRes import androidx.annotation.IdRes import androidx.constraintlayout.widget.ConstraintLayout import androidx.constraintlayout.widget.ConstraintSet @@ -104,10 +103,6 @@ class NotificationQSContainerControllerTest : SysuiTestCase() { windowInsetsCallback = windowInsetsCallbackCaptor.value } - private fun overrideResource(@AnyRes id: Int, value: Any) { - mContext.orCreateTestableResources.addOverride(id, value) - } - @Test fun testTaskbarVisibleInSplitShade() { enableSplitShade() diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java index 0b25467d20d8..786a8586ea39 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/ScrimControllerTest.java @@ -16,7 +16,6 @@ package com.android.systemui.statusbar.phone; -import static com.android.systemui.statusbar.phone.ScrimController.KEYGUARD_SCRIM_ALPHA; import static com.android.systemui.statusbar.phone.ScrimController.OPAQUE; import static com.android.systemui.statusbar.phone.ScrimController.SEMI_TRANSPARENT; import static com.android.systemui.statusbar.phone.ScrimController.TRANSPARENT; @@ -1263,19 +1262,36 @@ public class ScrimControllerTest extends SysuiTestCase { mScrimController.setClipsQsScrim(true); float progress = 0.5f; - mScrimController.setTransitionToFullShadeProgress(progress); + float lsNotifProgress = 0.3f; + mScrimController.setTransitionToFullShadeProgress(progress, lsNotifProgress); assertEquals(MathUtils.lerp(keyguardAlpha, shadeLockedAlpha, progress), mNotificationsScrim.getViewAlpha(), 0.2); progress = 0.0f; - mScrimController.setTransitionToFullShadeProgress(progress); + mScrimController.setTransitionToFullShadeProgress(progress, lsNotifProgress); assertEquals(MathUtils.lerp(keyguardAlpha, shadeLockedAlpha, progress), mNotificationsScrim.getViewAlpha(), 0.2); progress = 1.0f; - mScrimController.setTransitionToFullShadeProgress(progress); + mScrimController.setTransitionToFullShadeProgress(progress, lsNotifProgress); assertEquals(MathUtils.lerp(keyguardAlpha, shadeLockedAlpha, progress), mNotificationsScrim.getViewAlpha(), 0.2); } + @Test + public void notificationTransparency_followsNotificationScrimProgress() { + mScrimController.transitionTo(ScrimState.SHADE_LOCKED); + mScrimController.setRawPanelExpansionFraction(1.0f); + finishAnimationsImmediately(); + mScrimController.transitionTo(ScrimState.KEYGUARD); + mScrimController.setRawPanelExpansionFraction(1.0f); + finishAnimationsImmediately(); + + float progress = 0.5f; + float notifProgress = 0.3f; + mScrimController.setTransitionToFullShadeProgress(progress, notifProgress); + + assertThat(mNotificationsScrim.getViewAlpha()).isEqualTo(notifProgress); + } + private void assertAlphaAfterExpansion(ScrimView scrim, float expectedAlpha, float expansion) { mScrimController.setRawPanelExpansionFraction(expansion); finishAnimationsImmediately(); diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java index d48ce8c6803e..fa867e2796f7 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarNotificationActivityStarterTest.java @@ -447,4 +447,15 @@ public class StatusBarNotificationActivityStarterTest extends SysuiTestCase { controllerCaptor.getValue().onIntentStarted(false); verify(listener).onFinishLaunchNotifActivity(mNotificationRow.getEntry()); } + + @Test + public void testNotifActivityStarterEventSourceFinishEvent_postPanelCollapse_noAnimate() { + NotifActivityLaunchEvents.Listener listener = + mock(NotifActivityLaunchEvents.Listener.class); + mLaunchEventsEmitter.registerListener(listener); + when(mCentralSurfaces.shouldAnimateLaunch(anyBoolean())).thenReturn(false); + mNotificationActivityStarter + .onNotificationClicked(mNotificationRow.getEntry().getSbn(), mNotificationRow); + verify(listener).onFinishLaunchNotifActivity(mNotificationRow.getEntry()); + } } diff --git a/proto/src/metrics_constants/metrics_constants.proto b/proto/src/metrics_constants/metrics_constants.proto index 3f712dd1492f..3801c2473c11 100644 --- a/proto/src/metrics_constants/metrics_constants.proto +++ b/proto/src/metrics_constants/metrics_constants.proto @@ -2260,10 +2260,12 @@ message MetricsEvent { ACCOUNTS_WORK_PROFILE_SETTINGS = 401; // Settings -> Dev options -> Convert to file encryption - CONVERT_FBE = 402; + // DEPRECATED: this setting was removed in Android T. + CONVERT_FBE = 402 [deprecated=true]; // Settings -> Dev options -> Convert to file encryption -> WIPE AND CONVERT... - CONVERT_FBE_CONFIRM = 403; + // DEPRECATED: this setting was removed in Android T. + CONVERT_FBE_CONFIRM = 403 [deprecated=true]; // Settings -> Dev options -> Running services RUNNING_SERVICES = 404; diff --git a/services/accessibility/java/com/android/server/accessibility/magnification/FullScreenMagnificationController.java b/services/accessibility/java/com/android/server/accessibility/magnification/FullScreenMagnificationController.java index fa32452f389e..ecc45eb743c6 100644 --- a/services/accessibility/java/com/android/server/accessibility/magnification/FullScreenMagnificationController.java +++ b/services/accessibility/java/com/android/server/accessibility/magnification/FullScreenMagnificationController.java @@ -18,6 +18,7 @@ package com.android.server.accessibility.magnification; import static android.accessibilityservice.AccessibilityTrace.FLAGS_WINDOW_MANAGER_INTERNAL; import static android.accessibilityservice.MagnificationConfig.MAGNIFICATION_MODE_FULLSCREEN; +import static android.util.TypedValue.COMPLEX_UNIT_DIP; import static android.view.accessibility.MagnificationAnimationCallback.STUB_ANIMATION_CALLBACK; import static com.android.server.accessibility.AccessibilityManagerService.INVALID_SERVICE_ID; @@ -31,15 +32,20 @@ import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; +import android.content.res.CompatibilityInfo; import android.graphics.Rect; import android.graphics.Region; +import android.hardware.display.DisplayManagerInternal; import android.os.Handler; import android.os.Message; import android.text.TextUtils; +import android.util.DisplayMetrics; import android.util.MathUtils; import android.util.Slog; import android.util.SparseArray; +import android.util.TypedValue; import android.view.Display; +import android.view.DisplayInfo; import android.view.MagnificationSpec; import android.view.View; import android.view.accessibility.MagnificationAnimationCallback; @@ -93,6 +99,8 @@ public class FullScreenMagnificationController implements // Whether the following typing focus feature for magnification is enabled. private boolean mMagnificationFollowTypingEnabled = true; + private final DisplayManagerInternal mDisplayManagerInternal; + /** * This class implements {@link WindowManagerInternal.MagnificationCallbacks} and holds * magnification information per display. @@ -395,6 +403,18 @@ public class FullScreenMagnificationController implements outRegion.set(mMagnificationRegion); } + private DisplayMetrics getDisplayMetricsForId() { + final DisplayMetrics outMetrics = new DisplayMetrics(); + final DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(mDisplayId); + if (displayInfo != null) { + displayInfo.getLogicalMetrics(outMetrics, + CompatibilityInfo.DEFAULT_COMPATIBILITY_INFO, null); + } else { + outMetrics.setToDefaults(); + } + return outMetrics; + } + void requestRectangleOnScreen(int left, int top, int right, int bottom) { synchronized (mLock) { final Rect magnifiedFrame = mTempRect; @@ -408,6 +428,12 @@ public class FullScreenMagnificationController implements final float scrollX; final float scrollY; + // We offset an additional distance for a user to know the surrounding context. + DisplayMetrics metrics = getDisplayMetricsForId(); + final float offsetViewportX = (float) magnifFrameInScreenCoords.width() / 4; + final float offsetViewportY = + TypedValue.applyDimension(COMPLEX_UNIT_DIP, 10, metrics); + if (right - left > magnifFrameInScreenCoords.width()) { final int direction = TextUtils .getLayoutDirectionFromLocale(Locale.getDefault()); @@ -417,9 +443,9 @@ public class FullScreenMagnificationController implements scrollX = right - magnifFrameInScreenCoords.right; } } else if (left < magnifFrameInScreenCoords.left) { - scrollX = left - magnifFrameInScreenCoords.left; + scrollX = left - magnifFrameInScreenCoords.left - offsetViewportX; } else if (right > magnifFrameInScreenCoords.right) { - scrollX = right - magnifFrameInScreenCoords.right; + scrollX = right - magnifFrameInScreenCoords.right + offsetViewportX; } else { scrollX = 0; } @@ -427,9 +453,9 @@ public class FullScreenMagnificationController implements if (bottom - top > magnifFrameInScreenCoords.height()) { scrollY = top - magnifFrameInScreenCoords.top; } else if (top < magnifFrameInScreenCoords.top) { - scrollY = top - magnifFrameInScreenCoords.top; + scrollY = top - magnifFrameInScreenCoords.top - offsetViewportY; } else if (bottom > magnifFrameInScreenCoords.bottom) { - scrollY = bottom - magnifFrameInScreenCoords.bottom; + scrollY = bottom - magnifFrameInScreenCoords.bottom + offsetViewportY; } else { scrollY = 0; } @@ -687,6 +713,7 @@ public class FullScreenMagnificationController implements mScreenStateObserver = new ScreenStateObserver(mControllerCtx.getContext(), this); mMagnificationInfoChangedCallback = magnificationInfoChangedCallback; mScaleProvider = scaleProvider; + mDisplayManagerInternal = LocalServices.getService(DisplayManagerInternal.class); } /** diff --git a/services/core/java/com/android/server/NetworkTimeUpdateService.java b/services/core/java/com/android/server/NetworkTimeUpdateService.java index 186ff6215c9c..2015dc929a59 100644 --- a/services/core/java/com/android/server/NetworkTimeUpdateService.java +++ b/services/core/java/com/android/server/NetworkTimeUpdateService.java @@ -196,13 +196,15 @@ public class NetworkTimeUpdateService extends Binder { * Overrides the NTP server config for tests. Passing {@code null} to a parameter clears the * test value, i.e. so the normal value will be used next time. */ - void setServerConfigForTests(@Nullable String hostname, @Nullable Duration timeout) { + void setServerConfigForTests( + @Nullable String hostname, @Nullable Integer port, @Nullable Duration timeout) { mContext.enforceCallingPermission( android.Manifest.permission.SET_TIME, "set NTP server config for tests"); mLocalLog.log("Setting server config for tests: hostname=" + hostname + + ", port=" + port + ", timeout=" + timeout); - mTime.setServerConfigForTests(hostname, timeout); + mTime.setServerConfigForTests(hostname, port, timeout); } private void onPollNetworkTime(int event) { diff --git a/services/core/java/com/android/server/NetworkTimeUpdateServiceShellCommand.java b/services/core/java/com/android/server/NetworkTimeUpdateServiceShellCommand.java index 464af01a009a..d7504ceb9d4d 100644 --- a/services/core/java/com/android/server/NetworkTimeUpdateServiceShellCommand.java +++ b/services/core/java/com/android/server/NetworkTimeUpdateServiceShellCommand.java @@ -46,6 +46,7 @@ class NetworkTimeUpdateServiceShellCommand extends ShellCommand { */ private static final String SHELL_COMMAND_SET_SERVER_CONFIG = "set_server_config"; private static final String SET_SERVER_CONFIG_HOSTNAME_ARG = "--hostname"; + private static final String SET_SERVER_CONFIG_PORT_ARG = "--port"; private static final String SET_SERVER_CONFIG_TIMEOUT_ARG = "--timeout_millis"; @NonNull @@ -87,6 +88,7 @@ class NetworkTimeUpdateServiceShellCommand extends ShellCommand { private int runSetServerConfig() { String hostname = null; + Integer port = null; Duration timeout = null; String opt; while ((opt = getNextArg()) != null) { @@ -95,6 +97,10 @@ class NetworkTimeUpdateServiceShellCommand extends ShellCommand { hostname = getNextArgRequired(); break; } + case SET_SERVER_CONFIG_PORT_ARG: { + port = Integer.parseInt(getNextArgRequired()); + break; + } case SET_SERVER_CONFIG_TIMEOUT_ARG: { timeout = Duration.ofMillis(Integer.parseInt(getNextArgRequired())); break; @@ -104,7 +110,7 @@ class NetworkTimeUpdateServiceShellCommand extends ShellCommand { } } } - mNetworkTimeUpdateService.setServerConfigForTests(hostname, timeout); + mNetworkTimeUpdateService.setServerConfigForTests(hostname, port, timeout); return 0; } @@ -120,8 +126,9 @@ class NetworkTimeUpdateServiceShellCommand extends ShellCommand { pw.printf(" Refreshes the latest time. Prints whether it was successful.\n"); pw.printf(" %s\n", SHELL_COMMAND_SET_SERVER_CONFIG); pw.printf(" Sets the NTP server config for tests. The config is not persisted.\n"); - pw.printf(" Options: [%s <hostname>] [%s <millis>]\n", - SET_SERVER_CONFIG_HOSTNAME_ARG, SET_SERVER_CONFIG_TIMEOUT_ARG); + pw.printf(" Options: [%s <hostname>] [%s <port>] [%s <millis>]\n", + SET_SERVER_CONFIG_HOSTNAME_ARG, SET_SERVER_CONFIG_PORT_ARG, + SET_SERVER_CONFIG_TIMEOUT_ARG); pw.printf(" Each key/value is optional and must be specified to override the\n"); pw.printf(" normal value, not specifying a key causes it to reset to the original.\n"); pw.println(); diff --git a/services/core/java/com/android/server/StorageManagerService.java b/services/core/java/com/android/server/StorageManagerService.java index 677fc7931f64..a2cfe4928249 100644 --- a/services/core/java/com/android/server/StorageManagerService.java +++ b/services/core/java/com/android/server/StorageManagerService.java @@ -3130,23 +3130,6 @@ class StorageManagerService extends IStorageManager.Stub } /** - * Is userdata convertible to file based encryption? - * @return non zero for convertible - */ - @Override - public boolean isConvertibleToFBE() throws RemoteException { - mContext.enforceCallingOrSelfPermission(Manifest.permission.CRYPT_KEEPER, - "no permission to access the crypt keeper"); - - try { - return mVold.isConvertibleToFbe(); - } catch (Exception e) { - Slog.wtf(TAG, e); - return false; - } - } - - /** * Check whether the device supports filesystem checkpointing. * * @return true if the device supports filesystem checkpointing, false otherwise. diff --git a/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java index 1131fa8a32b8..4fdc88d3fd64 100644 --- a/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java +++ b/services/core/java/com/android/server/am/BatteryExternalStatsWorker.java @@ -561,8 +561,18 @@ class BatteryExternalStatsWorker implements BatteryStatsImpl.ExternalStatsSync { // We were asked to fetch Bluetooth data. final BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter(); if (adapter != null) { - bluetoothReceiver = new SynchronousResultReceiver("bluetooth"); - adapter.requestControllerActivityEnergyInfo(bluetoothReceiver); + SynchronousResultReceiver resultReceiver = + new SynchronousResultReceiver("bluetooth"); + adapter.requestControllerActivityEnergyInfo( + Runnable::run, + info -> { + Bundle bundle = new Bundle(); + bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, + info); + resultReceiver.send(0, bundle); + } + ); + bluetoothReceiver = resultReceiver; } } diff --git a/services/core/java/com/android/server/am/OomAdjuster.java b/services/core/java/com/android/server/am/OomAdjuster.java index 7ed3dcf40f65..9626bbe0b4b2 100644 --- a/services/core/java/com/android/server/am/OomAdjuster.java +++ b/services/core/java/com/android/server/am/OomAdjuster.java @@ -407,7 +407,6 @@ public class OomAdjuster { uids.clear(); uids.put(uidRec.getUid(), uidRec); updateUidsLSP(uids, SystemClock.elapsedRealtime()); - mProcessList.incrementProcStateSeqAndNotifyAppsLOSP(uids); } } @@ -1144,8 +1143,6 @@ public class OomAdjuster { } } - mProcessList.incrementProcStateSeqAndNotifyAppsLOSP(activeUids); - return mService.mAppProfiler.updateLowMemStateLSP(numCached, numEmpty, numTrimming); } @@ -1180,6 +1177,11 @@ public class OomAdjuster { @GuardedBy({"mService", "mProcLock"}) private void updateUidsLSP(ActiveUids activeUids, final long nowElapsed) { + // This compares previously set procstate to the current procstate in regards to whether + // or not the app's network access will be blocked. So, this needs to be called before + // we update the UidRecord's procstate by calling {@link UidRecord#setSetProcState}. + mProcessList.incrementProcStateSeqAndNotifyAppsLOSP(activeUids); + ArrayList<UidRecord> becameIdle = mTmpBecameIdle; becameIdle.clear(); diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java index d01be5820d34..309a4ff16753 100644 --- a/services/core/java/com/android/server/audio/AudioService.java +++ b/services/core/java/com/android/server/audio/AudioService.java @@ -102,6 +102,7 @@ import android.media.IRecordingConfigDispatcher; import android.media.IRingtonePlayer; import android.media.ISpatializerCallback; import android.media.ISpatializerHeadToSoundStagePoseCallback; +import android.media.ISpatializerHeadTrackerAvailableCallback; import android.media.ISpatializerHeadTrackingModeCallback; import android.media.ISpatializerOutputCallback; import android.media.IStrategyPreferredDevicesDispatcher; @@ -8723,6 +8724,11 @@ public class AudioService extends IAudioService.Stub return mSpatializerHelper.isHeadTrackerEnabled(Objects.requireNonNull(device)); } + /** @see Spatializer#isHeadTrackerAvailable() */ + public boolean isHeadTrackerAvailable() { + return mSpatializerHelper.isHeadTrackerAvailable(); + } + /** @see Spatializer#setSpatializerEnabled(boolean) */ public void setSpatializerEnabled(boolean enabled) { enforceModifyDefaultAudioEffectsPermission(); @@ -8767,6 +8773,13 @@ public class AudioService extends IAudioService.Stub mSpatializerHelper.unregisterHeadTrackingModeCallback(cb); } + /** @see Spatializer.SpatializerHeadTrackerAvailableDispatcherStub */ + public void registerSpatializerHeadTrackerAvailableCallback( + @NonNull ISpatializerHeadTrackerAvailableCallback cb, boolean register) { + Objects.requireNonNull(cb); + mSpatializerHelper.registerHeadTrackerAvailableCallback(cb, register); + } + /** @see Spatializer#setOnHeadToSoundstagePoseUpdatedListener */ public void registerHeadToSoundstagePoseCallback( @NonNull ISpatializerHeadToSoundStagePoseCallback cb) { diff --git a/services/core/java/com/android/server/audio/SpatializerHelper.java b/services/core/java/com/android/server/audio/SpatializerHelper.java index 5af73c9e46ea..f0f04e27b7de 100644 --- a/services/core/java/com/android/server/audio/SpatializerHelper.java +++ b/services/core/java/com/android/server/audio/SpatializerHelper.java @@ -30,6 +30,7 @@ import android.media.INativeSpatializerCallback; import android.media.ISpatializer; import android.media.ISpatializerCallback; import android.media.ISpatializerHeadToSoundStagePoseCallback; +import android.media.ISpatializerHeadTrackerAvailableCallback; import android.media.ISpatializerHeadTrackingCallback; import android.media.ISpatializerHeadTrackingModeCallback; import android.media.ISpatializerOutputCallback; @@ -126,6 +127,7 @@ public class SpatializerHelper { private boolean mBinauralSupported = false; private int mActualHeadTrackingMode = Spatializer.HEAD_TRACKING_MODE_UNSUPPORTED; private int mDesiredHeadTrackingMode = Spatializer.HEAD_TRACKING_MODE_RELATIVE_WORLD; + private boolean mHeadTrackerAvailable = false; /** * The desired head tracking mode when enabling head tracking, tracks mDesiredHeadTrackingMode, * except when head tracking gets disabled through setting the desired mode to @@ -137,6 +139,7 @@ public class SpatializerHelper { private @Nullable SpatializerCallback mSpatCallback; private @Nullable SpatializerHeadTrackingCallback mSpatHeadTrackingCallback; private @Nullable HelperDynamicSensorCallback mDynSensorCallback; + private boolean mIsHeadTrackingSupported = false; // default attributes and format that determine basic availability of spatialization private static final AudioAttributes DEFAULT_ATTRIBUTES = new AudioAttributes.Builder() @@ -811,8 +814,9 @@ public class SpatializerHelper { mSpat = AudioSystem.getSpatializer(mSpatCallback); try { mSpat.setLevel((byte) Spatializer.SPATIALIZER_IMMERSIVE_LEVEL_MULTICHANNEL); + mIsHeadTrackingSupported = mSpat.isHeadTrackingSupported(); //TODO: register heatracking callback only when sensors are registered - if (mSpat.isHeadTrackingSupported()) { + if (mIsHeadTrackingSupported) { mSpat.registerHeadTrackingCallback(mSpatHeadTrackingCallback); } } catch (RemoteException e) { @@ -830,11 +834,15 @@ public class SpatializerHelper { if (mSpat != null) { mSpatCallback = null; try { - mSpat.registerHeadTrackingCallback(null); + if (mIsHeadTrackingSupported) { + mSpat.registerHeadTrackingCallback(null); + } + mHeadTrackerAvailable = false; mSpat.release(); } catch (RemoteException e) { Log.e(TAG, "Can't set release spatializer cleanly", e); } + mIsHeadTrackingSupported = false; mSpat = null; } } @@ -890,6 +898,18 @@ public class SpatializerHelper { mHeadTrackingModeCallbacks.unregister(callback); } + final RemoteCallbackList<ISpatializerHeadTrackerAvailableCallback> mHeadTrackerCallbacks = + new RemoteCallbackList<>(); + + synchronized void registerHeadTrackerAvailableCallback( + @NonNull ISpatializerHeadTrackerAvailableCallback cb, boolean register) { + if (register) { + mHeadTrackerCallbacks.register(cb); + } else { + mHeadTrackerCallbacks.unregister(cb); + } + } + synchronized int[] getSupportedHeadTrackingModes() { switch (mState) { case STATE_UNINITIALIZED: @@ -1090,6 +1110,10 @@ public class SpatializerHelper { return false; } + synchronized boolean isHeadTrackerAvailable() { + return mHeadTrackerAvailable; + } + private boolean checkSpatForHeadTracking(String funcName) { switch (mState) { case STATE_UNINITIALIZED: @@ -1105,7 +1129,7 @@ public class SpatializerHelper { } break; } - return true; + return mIsHeadTrackingSupported; } private void dispatchActualHeadTrackingMode(int newMode) { @@ -1115,7 +1139,8 @@ public class SpatializerHelper { mHeadTrackingModeCallbacks.getBroadcastItem(i) .dispatchSpatializerActualHeadTrackingModeChanged(newMode); } catch (RemoteException e) { - Log.e(TAG, "Error in dispatchSpatializerActualHeadTrackingModeChanged", e); + Log.e(TAG, "Error in dispatchSpatializerActualHeadTrackingModeChanged(" + + newMode + ")", e); } } mHeadTrackingModeCallbacks.finishBroadcast(); @@ -1128,12 +1153,27 @@ public class SpatializerHelper { mHeadTrackingModeCallbacks.getBroadcastItem(i) .dispatchSpatializerDesiredHeadTrackingModeChanged(newMode); } catch (RemoteException e) { - Log.e(TAG, "Error in dispatchSpatializerDesiredHeadTrackingModeChanged", e); + Log.e(TAG, "Error in dispatchSpatializerDesiredHeadTrackingModeChanged(" + + newMode + ")", e); } } mHeadTrackingModeCallbacks.finishBroadcast(); } + private void dispatchHeadTrackerAvailable(boolean available) { + final int nbCallbacks = mHeadTrackerCallbacks.beginBroadcast(); + for (int i = 0; i < nbCallbacks; i++) { + try { + mHeadTrackerCallbacks.getBroadcastItem(i) + .dispatchSpatializerHeadTrackerAvailable(available); + } catch (RemoteException e) { + Log.e(TAG, "Error in dispatchSpatializerHeadTrackerAvailable(" + + available + ")", e); + } + } + mHeadTrackerCallbacks.finishBroadcast(); + } + //------------------------------------------------------ // head pose final RemoteCallbackList<ISpatializerHeadToSoundStagePoseCallback> mHeadPoseCallbacks = @@ -1279,13 +1319,8 @@ public class SpatializerHelper { Log.e(TAG, "not " + action + " sensors, null spatializer"); return; } - try { - if (!mSpat.isHeadTrackingSupported()) { - Log.e(TAG, "not " + action + " sensors, spatializer doesn't support headtracking"); - return; - } - } catch (RemoteException e) { - Log.e(TAG, "not " + action + " sensors, error querying headtracking", e); + if (!mIsHeadTrackingSupported) { + Log.e(TAG, "not " + action + " sensors, spatializer doesn't support headtracking"); return; } int headHandle = -1; @@ -1348,6 +1383,10 @@ public class SpatializerHelper { try { Log.i(TAG, "setHeadSensor:" + headHandle); mSpat.setHeadSensor(headHandle); + if (mHeadTrackerAvailable != (headHandle != -1)) { + mHeadTrackerAvailable = (headHandle != -1); + dispatchHeadTrackerAvailable(mHeadTrackerAvailable); + } } catch (Exception e) { Log.e(TAG, "Error calling setHeadSensor:" + headHandle, e); } diff --git a/services/core/java/com/android/server/display/ColorFade.java b/services/core/java/com/android/server/display/ColorFade.java index 7cb29215b5bf..cb04ddfd636d 100644 --- a/services/core/java/com/android/server/display/ColorFade.java +++ b/services/core/java/com/android/server/display/ColorFade.java @@ -156,9 +156,15 @@ final class ColorFade { mMode = mode; + DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(mDisplayId); + if (displayInfo == null) { + // displayInfo can be null if the associated display has been removed. There + // is a delay between the display being removed and ColorFade being dismissed. + return false; + } + // Get the display size and layer stack. // This is not expected to change while the color fade surface is showing. - DisplayInfo displayInfo = mDisplayManagerInternal.getDisplayInfo(mDisplayId); mDisplayLayerStack = displayInfo.layerStack; mDisplayWidth = displayInfo.getNaturalWidth(); mDisplayHeight = displayInfo.getNaturalHeight(); diff --git a/services/core/java/com/android/server/display/LocalDisplayAdapter.java b/services/core/java/com/android/server/display/LocalDisplayAdapter.java index 7a0cf4b592e7..540ae8165dbd 100644 --- a/services/core/java/com/android/server/display/LocalDisplayAdapter.java +++ b/services/core/java/com/android/server/display/LocalDisplayAdapter.java @@ -73,6 +73,8 @@ final class LocalDisplayAdapter extends DisplayAdapter { private final SurfaceControlProxy mSurfaceControlProxy; + private final boolean mIsBootDisplayModeSupported; + // Called with SyncRoot lock held. public LocalDisplayAdapter(DisplayManagerService.SyncRoot syncRoot, Context context, Handler handler, Listener listener) { @@ -85,6 +87,7 @@ final class LocalDisplayAdapter extends DisplayAdapter { super(syncRoot, context, handler, listener, TAG); mInjector = injector; mSurfaceControlProxy = mInjector.getSurfaceControlProxy(); + mIsBootDisplayModeSupported = mSurfaceControlProxy.getBootDisplayModeSupport(); } @Override @@ -349,8 +352,7 @@ final class LocalDisplayAdapter extends DisplayAdapter { if (preferredRecord != null) { int preferredModeId = preferredRecord.mMode.getModeId(); - if (mSurfaceControlProxy.getBootDisplayModeSupport() - && mSystemPreferredModeId != preferredModeId) { + if (mIsBootDisplayModeSupported && mSystemPreferredModeId != preferredModeId) { mSystemPreferredModeId = preferredModeId; preferredModeChanged = true; } @@ -900,7 +902,7 @@ final class LocalDisplayAdapter extends DisplayAdapter { } updateDeviceInfoLocked(); - if (!mSurfaceControlProxy.getBootDisplayModeSupport()) { + if (!mIsBootDisplayModeSupported) { return; } if (mUserPreferredModeId == INVALID_MODE_ID) { diff --git a/services/core/java/com/android/server/locales/LocaleManagerService.java b/services/core/java/com/android/server/locales/LocaleManagerService.java index 176c08c8da29..924db6a49eeb 100644 --- a/services/core/java/com/android/server/locales/LocaleManagerService.java +++ b/services/core/java/com/android/server/locales/LocaleManagerService.java @@ -22,12 +22,14 @@ import android.Manifest; import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.UserIdInt; +import android.app.ActivityManager; import android.app.ActivityManagerInternal; import android.app.ILocaleManager; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager; import android.content.pm.PackageManagerInternal; +import android.content.res.Configuration; import android.os.Binder; import android.os.HandlerThread; import android.os.LocaleList; @@ -154,6 +156,12 @@ public class LocaleManagerService extends SystemService { } @Override + @NonNull + public LocaleList getSystemLocales() throws RemoteException { + return LocaleManagerService.this.getSystemLocales(); + } + + @Override public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) { @@ -426,6 +434,32 @@ public class LocaleManagerService extends SystemService { return null; } + /** + * Returns the current system locales. + */ + @NonNull + public LocaleList getSystemLocales() throws RemoteException { + final long token = Binder.clearCallingIdentity(); + try { + return getSystemLocalesUnchecked(); + } finally { + Binder.restoreCallingIdentity(token); + } + } + + @NonNull + private LocaleList getSystemLocalesUnchecked() throws RemoteException { + LocaleList systemLocales = null; + Configuration conf = ActivityManager.getService().getConfiguration(); + if (conf != null) { + systemLocales = conf.getLocales(); + } + if (systemLocales == null) { + systemLocales = LocaleList.getEmptyLocaleList(); + } + return systemLocales; + } + private void logMetric(@NonNull AppLocaleChangedAtomRecord atomRecordForMetrics) { FrameworkStatsLog.write(FrameworkStatsLog.APPLICATION_LOCALES_CHANGED, atomRecordForMetrics.mCallingUid, diff --git a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java index 3ce8e4659737..1937852fa333 100644 --- a/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java +++ b/services/core/java/com/android/server/media/projection/MediaProjectionManagerService.java @@ -45,6 +45,7 @@ import android.os.RemoteException; import android.os.UserHandle; import android.util.ArrayMap; import android.util.Slog; +import android.window.WindowContainerToken; import com.android.internal.util.ArrayUtils; import com.android.internal.util.DumpUtils; @@ -410,6 +411,7 @@ public final class MediaProjectionManagerService extends SystemService private IBinder mToken; private IBinder.DeathRecipient mDeathEater; private boolean mRestoreSystemAlertWindow; + private WindowContainerToken mTaskRecordingWindowContainerToken = null; MediaProjection(int type, int uid, String packageName, int targetSdkVersion, boolean isPrivileged) { @@ -568,7 +570,7 @@ public final class MediaProjectionManagerService extends SystemService } } - @Override + @Override // Binder call public void registerCallback(IMediaProjectionCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback must not be null"); @@ -576,7 +578,7 @@ public final class MediaProjectionManagerService extends SystemService mCallbackDelegate.add(callback); } - @Override + @Override // Binder call public void unregisterCallback(IMediaProjectionCallback callback) { if (callback == null) { throw new IllegalArgumentException("callback must not be null"); @@ -584,6 +586,17 @@ public final class MediaProjectionManagerService extends SystemService mCallbackDelegate.remove(callback); } + @Override // Binder call + public void setTaskRecordingWindowContainerToken(WindowContainerToken token) { + // TODO(b/221417940) set the task id to record from sysui, for the package chosen. + mTaskRecordingWindowContainerToken = token; + } + + @Override // Binder call + public WindowContainerToken getTaskRecordingWindowContainerToken() { + return mTaskRecordingWindowContainerToken; + } + public MediaProjectionInfo getProjectionInfo() { return new MediaProjectionInfo(packageName, userHandle); } diff --git a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java index 35f6a94f3ed6..57ffba70ba2e 100644 --- a/services/core/java/com/android/server/net/NetworkPolicyManagerService.java +++ b/services/core/java/com/android/server/net/NetworkPolicyManagerService.java @@ -5421,6 +5421,11 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { try { mNetworkManager.setUidOnMeteredNetworkDenylist(uid, enable); mLogger.meteredAllowlistChanged(uid, enable); + if (Process.isApplicationUid(uid)) { + final int sdkSandboxUid = Process.toSdkSandboxUid(uid); + mNetworkManager.setUidOnMeteredNetworkDenylist(sdkSandboxUid, enable); + mLogger.meteredAllowlistChanged(sdkSandboxUid, enable); + } } catch (IllegalStateException e) { Log.wtf(TAG, "problem setting denylist (" + enable + ") rules for " + uid, e); } catch (RemoteException e) { @@ -5433,6 +5438,11 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { try { mNetworkManager.setUidOnMeteredNetworkAllowlist(uid, enable); mLogger.meteredDenylistChanged(uid, enable); + if (Process.isApplicationUid(uid)) { + final int sdkSandboxUid = Process.toSdkSandboxUid(uid); + mNetworkManager.setUidOnMeteredNetworkAllowlist(sdkSandboxUid, enable); + mLogger.meteredDenylistChanged(sdkSandboxUid, enable); + } } catch (IllegalStateException e) { Log.wtf(TAG, "problem setting allowlist (" + enable + ") rules for " + uid, e); } catch (RemoteException e) { @@ -5471,12 +5481,31 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } } + private void addSdkSandboxUidsIfNeeded(SparseIntArray uidRules) { + final int size = uidRules.size(); + final SparseIntArray sdkSandboxUids = new SparseIntArray(); + for (int index = 0; index < size; index++) { + final int uid = uidRules.keyAt(index); + final int rule = uidRules.valueAt(index); + if (Process.isApplicationUid(uid)) { + sdkSandboxUids.put(Process.toSdkSandboxUid(uid), rule); + } + } + + for (int index = 0; index < sdkSandboxUids.size(); index++) { + final int uid = sdkSandboxUids.keyAt(index); + final int rule = sdkSandboxUids.valueAt(index); + uidRules.put(uid, rule); + } + } + /** * Set uid rules on a particular firewall chain. This is going to synchronize the rules given * here to netd. It will clean up dead rules and make sure the target chain only contains rules * specified here. */ private void setUidFirewallRulesUL(int chain, SparseIntArray uidRules) { + addSdkSandboxUidsIfNeeded(uidRules); try { int size = uidRules.size(); int[] uids = new int[size]; @@ -5519,6 +5548,11 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { try { mNetworkManager.setFirewallUidRule(chain, uid, rule); mLogger.uidFirewallRuleChanged(chain, uid, rule); + if (Process.isApplicationUid(uid)) { + final int sdkSandboxUid = Process.toSdkSandboxUid(uid); + mNetworkManager.setFirewallUidRule(chain, sdkSandboxUid, rule); + mLogger.uidFirewallRuleChanged(chain, sdkSandboxUid, rule); + } } catch (IllegalStateException e) { Log.wtf(TAG, "problem setting firewall uid rules", e); } catch (RemoteException e) { @@ -5555,15 +5589,16 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { */ private void resetUidFirewallRules(int uid) { try { - mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, FIREWALL_RULE_DEFAULT); - mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, FIREWALL_RULE_DEFAULT); - mNetworkManager - .setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, FIREWALL_RULE_DEFAULT); - mNetworkManager - .setFirewallUidRule(FIREWALL_CHAIN_RESTRICTED, uid, FIREWALL_RULE_DEFAULT); - mNetworkManager - .setFirewallUidRule(FIREWALL_CHAIN_LOW_POWER_STANDBY, uid, - FIREWALL_RULE_DEFAULT); + mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_DOZABLE, uid, + FIREWALL_RULE_DEFAULT); + mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_STANDBY, uid, + FIREWALL_RULE_DEFAULT); + mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_POWERSAVE, uid, + FIREWALL_RULE_DEFAULT); + mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_RESTRICTED, uid, + FIREWALL_RULE_DEFAULT); + mNetworkManager.setFirewallUidRule(FIREWALL_CHAIN_LOW_POWER_STANDBY, uid, + FIREWALL_RULE_DEFAULT); mNetworkManager.setUidOnMeteredNetworkAllowlist(uid, false); mLogger.meteredAllowlistChanged(uid, false); mNetworkManager.setUidOnMeteredNetworkDenylist(uid, false); @@ -5573,6 +5608,9 @@ public class NetworkPolicyManagerService extends INetworkPolicyManager.Stub { } catch (RemoteException e) { // ignored; service lives in system_server } + if (Process.isApplicationUid(uid)) { + resetUidFirewallRules(Process.toSdkSandboxUid(uid)); + } } @Deprecated diff --git a/services/core/java/com/android/server/pm/BackgroundDexOptService.java b/services/core/java/com/android/server/pm/BackgroundDexOptService.java index 9ff4aab83cff..d26a1ac4fba0 100644 --- a/services/core/java/com/android/server/pm/BackgroundDexOptService.java +++ b/services/core/java/com/android/server/pm/BackgroundDexOptService.java @@ -253,7 +253,8 @@ public final class BackgroundDexOptService { * * <p>This is only for shell command and only root or shell user can use this. * - * @param packageNames dex optimize the passed packages or all packages if null + * @param packageNames dex optimize the passed packages in the given order, or all packages in + * the default order if null * * @return true if dex optimization is complete. false if the task is cancelled or if there was * an error. @@ -268,11 +269,11 @@ public final class BackgroundDexOptService { resetStatesForNewDexOptRunLocked(Thread.currentThread()); } PackageManagerService pm = mInjector.getPackageManagerService(); - ArraySet<String> packagesToOptimize; + List<String> packagesToOptimize; if (packageNames == null) { packagesToOptimize = mDexOptHelper.getOptimizablePackages(pm.snapshotComputer()); } else { - packagesToOptimize = new ArraySet<>(packageNames); + packagesToOptimize = packageNames; } return runIdleOptimization(pm, packagesToOptimize, /* isPostBootUpdate= */ false); } finally { @@ -335,7 +336,7 @@ public final class BackgroundDexOptService { return false; } - ArraySet<String> pkgs = mDexOptHelper.getOptimizablePackages(pm.snapshotComputer()); + List<String> pkgs = mDexOptHelper.getOptimizablePackages(pm.snapshotComputer()); if (pkgs.isEmpty()) { Slog.i(TAG, "No packages to optimize"); markPostBootUpdateCompleted(params); @@ -525,7 +526,7 @@ public final class BackgroundDexOptService { } /** Returns true if completed */ - private boolean runIdleOptimization(PackageManagerService pm, ArraySet<String> pkgs, + private boolean runIdleOptimization(PackageManagerService pm, List<String> pkgs, boolean isPostBootUpdate) { synchronized (mLock) { mLastExecutionStartTimeMs = SystemClock.elapsedRealtime(); @@ -581,10 +582,9 @@ public final class BackgroundDexOptService { } @Status - private int idleOptimizePackages(PackageManagerService pm, ArraySet<String> pkgs, + private int idleOptimizePackages(PackageManagerService pm, List<String> pkgs, long lowStorageThreshold, boolean isPostBootUpdate) { ArraySet<String> updatedPackages = new ArraySet<>(); - ArraySet<String> updatedPackagesDueToSecondaryDex = new ArraySet<>(); try { boolean supportSecondaryDex = mInjector.supportSecondaryDex(); @@ -640,25 +640,12 @@ public final class BackgroundDexOptService { } } - pkgs = new ArraySet<>(pkgs); + pkgs = new ArrayList<>(pkgs); pkgs.removeAll(unusedPackages); } } - @Status int primaryResult = optimizePackages(pkgs, lowStorageThreshold, - /*isForPrimaryDex=*/ true, updatedPackages, isPostBootUpdate); - if (primaryResult != STATUS_OK) { - return primaryResult; - } - - if (!supportSecondaryDex) { - return STATUS_OK; - } - - @Status int secondaryResult = optimizePackages(pkgs, lowStorageThreshold, - /*isForPrimaryDex*/ false, updatedPackagesDueToSecondaryDex, - isPostBootUpdate); - return secondaryResult; + return optimizePackages(pkgs, lowStorageThreshold, updatedPackages, isPostBootUpdate); } finally { // Always let the pinner service know about changes. notifyPinService(updatedPackages); @@ -670,8 +657,10 @@ public final class BackgroundDexOptService { } @Status - private int optimizePackages(ArraySet<String> pkgs, long lowStorageThreshold, - boolean isForPrimaryDex, ArraySet<String> updatedPackages, boolean isPostBootUpdate) { + private int optimizePackages(List<String> pkgs, long lowStorageThreshold, + ArraySet<String> updatedPackages, boolean isPostBootUpdate) { + boolean supportSecondaryDex = mInjector.supportSecondaryDex(); + for (String pkg : pkgs) { int abortCode = abortIdleOptimizations(lowStorageThreshold); if (abortCode != STATUS_OK) { @@ -679,11 +668,23 @@ public final class BackgroundDexOptService { return abortCode; } - @DexOptResult int result = optimizePackage(pkg, isForPrimaryDex, isPostBootUpdate); - if (result == PackageDexOptimizer.DEX_OPT_PERFORMED) { + @DexOptResult int primaryResult = + optimizePackage(pkg, true /* isForPrimaryDex */, isPostBootUpdate); + if (primaryResult == PackageDexOptimizer.DEX_OPT_PERFORMED) { updatedPackages.add(pkg); - } else if (result != PackageDexOptimizer.DEX_OPT_SKIPPED) { - return convertPackageDexOptimizerStatusToInternal(result); + } else if (primaryResult != PackageDexOptimizer.DEX_OPT_SKIPPED) { + return convertPackageDexOptimizerStatusToInternal(primaryResult); + } + + if (!supportSecondaryDex) { + continue; + } + + @DexOptResult int secondaryResult = + optimizePackage(pkg, false /* isForPrimaryDex */, isPostBootUpdate); + if (secondaryResult != PackageDexOptimizer.DEX_OPT_PERFORMED + && secondaryResult != PackageDexOptimizer.DEX_OPT_SKIPPED) { + return convertPackageDexOptimizerStatusToInternal(secondaryResult); } } return STATUS_OK; diff --git a/services/core/java/com/android/server/pm/DexOptHelper.java b/services/core/java/com/android/server/pm/DexOptHelper.java index 50b2e2321886..bb2ba5cc498d 100644 --- a/services/core/java/com/android/server/pm/DexOptHelper.java +++ b/services/core/java/com/android/server/pm/DexOptHelper.java @@ -293,8 +293,8 @@ final class DexOptHelper { MetricsLogger.histogram(mPm.mContext, "opt_dialog_time_s", elapsedTimeSeconds); } - public ArraySet<String> getOptimizablePackages(@NonNull Computer snapshot) { - ArraySet<String> pkgs = new ArraySet<>(); + public List<String> getOptimizablePackages(@NonNull Computer snapshot) { + ArrayList<String> pkgs = new ArrayList<>(); mPm.forEachPackageState(snapshot, packageState -> { final AndroidPackage pkg = packageState.getPkg(); if (pkg != null && mPm.mPackageDexOptimizer.canOptimizePackage(pkg)) { diff --git a/services/core/java/com/android/server/pm/InitAndSystemPackageHelper.java b/services/core/java/com/android/server/pm/InitAppsHelper.java index 91750dee7688..15f26e7a6d6c 100644 --- a/services/core/java/com/android/server/pm/InitAndSystemPackageHelper.java +++ b/services/core/java/com/android/server/pm/InitAppsHelper.java @@ -32,6 +32,7 @@ import static com.android.server.pm.PackageManagerService.SYSTEM_PARTITIONS; import static com.android.server.pm.PackageManagerService.TAG; import static com.android.server.pm.pkg.parsing.ParsingPackageUtils.PARSE_CHECK_MAX_SDK_VERSION; +import android.annotation.NonNull; import android.annotation.Nullable; import android.content.pm.parsing.ApkLiteParseUtils; import android.os.Environment; @@ -61,14 +62,24 @@ import java.util.concurrent.ExecutorService; * further cleanup and eventually all the installation/scanning related logic will go to another * class. */ -final class InitAndSystemPackageHelper { +final class InitAppsHelper { private final PackageManagerService mPm; - private final List<ScanPartition> mDirsToScanAsSystem; private final int mScanFlags; private final int mSystemParseFlags; private final int mSystemScanFlags; private final InstallPackageHelper mInstallPackageHelper; + private final ApexManager mApexManager; + private final ExecutorService mExecutorService; + /* Tracks how long system scan took */ + private long mSystemScanTime; + /* Track of the number of cached system apps */ + private int mCachedSystemApps; + /* Track of the number of system apps */ + private int mSystemPackagesCount; + private final boolean mIsDeviceUpgrading; + private final boolean mIsOnlyCoreApps; + private final List<ScanPartition> mSystemPartitions; /** * Tracks new system packages [received in an OTA] that we expect to @@ -76,21 +87,33 @@ final class InitAndSystemPackageHelper { * are package location. */ private final ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); + /* Tracks of any system packages that no longer exist that needs to be pruned. */ + private final List<String> mPossiblyDeletedUpdatedSystemApps = new ArrayList<>(); + // Tracks of stub packages that must either be replaced with full versions in the /data + // partition or be disabled. + private final List<String> mStubSystemApps = new ArrayList<>(); // TODO(b/198166813): remove PMS dependency - InitAndSystemPackageHelper(PackageManagerService pm) { + InitAppsHelper(PackageManagerService pm, ApexManager apexManager, + InstallPackageHelper installPackageHelper, + List<ScanPartition> systemPartitions) { mPm = pm; - mInstallPackageHelper = new InstallPackageHelper(pm); + mApexManager = apexManager; + mInstallPackageHelper = installPackageHelper; + mSystemPartitions = systemPartitions; mDirsToScanAsSystem = getSystemScanPartitions(); + mIsDeviceUpgrading = mPm.isDeviceUpgrading(); + mIsOnlyCoreApps = mPm.isOnlyCoreApps(); // Set flag to monitor and not change apk file paths when scanning install directories. int scanFlags = SCAN_BOOTING | SCAN_INITIAL; - if (mPm.isDeviceUpgrading() || mPm.isFirstBoot()) { + if (mIsDeviceUpgrading || mPm.isFirstBoot()) { mScanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; } else { mScanFlags = scanFlags; } mSystemParseFlags = mPm.getDefParseFlags() | ParsingPackageUtils.PARSE_IS_SYSTEM_DIR; mSystemScanFlags = scanFlags | SCAN_AS_SYSTEM; + mExecutorService = ParallelPackageParser.makeExecutorService(); } private List<File> getFrameworkResApkSplitFiles() { @@ -118,7 +141,7 @@ final class InitAndSystemPackageHelper { private List<ScanPartition> getSystemScanPartitions() { final List<ScanPartition> scanPartitions = new ArrayList<>(); - scanPartitions.addAll(mPm.mInjector.getSystemPartitions()); + scanPartitions.addAll(mSystemPartitions); scanPartitions.addAll(getApexScanPartitions()); Slog.d(TAG, "Directories scanned as system partitions: " + scanPartitions); return scanPartitions; @@ -126,8 +149,7 @@ final class InitAndSystemPackageHelper { private List<ScanPartition> getApexScanPartitions() { final List<ScanPartition> scanPartitions = new ArrayList<>(); - final List<ApexManager.ActiveApexInfo> activeApexInfos = - mPm.mApexManager.getActiveApexInfos(); + final List<ApexManager.ActiveApexInfo> activeApexInfos = mApexManager.getActiveApexInfos(); for (int i = 0; i < activeApexInfos.size(); i++) { final ScanPartition scanPartition = resolveApexToScanPartition(activeApexInfos.get(i)); if (scanPartition != null) { @@ -144,117 +166,134 @@ final class InitAndSystemPackageHelper { if (apexInfo.preInstalledApexPath.getAbsolutePath().equals( sp.getFolder().getAbsolutePath()) || apexInfo.preInstalledApexPath.getAbsolutePath().startsWith( - sp.getFolder().getAbsolutePath() + File.separator)) { + sp.getFolder().getAbsolutePath() + File.separator)) { return new ScanPartition(apexInfo.apexDirectory, sp, SCAN_AS_APK_IN_APEX); } } return null; } - public OverlayConfig initPackages( - WatchedArrayMap<String, PackageSetting> packageSettings, int[] userIds, - long startTime) { - PackageParser2 packageParser = mPm.mInjector.getScanningCachingPackageParser(); - - ExecutorService executorService = ParallelPackageParser.makeExecutorService(); + /** + * Install apps from system dirs. + */ + @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) + public OverlayConfig initSystemApps(PackageParser2 packageParser, + WatchedArrayMap<String, PackageSetting> packageSettings, + int[] userIds, long startTime) { // Prepare apex package info before scanning APKs, this information is needed when // scanning apk in apex. - mPm.mApexManager.scanApexPackagesTraced(packageParser, executorService); + mApexManager.scanApexPackagesTraced(packageParser, mExecutorService); - scanSystemDirs(packageParser, executorService); + scanSystemDirs(packageParser, mExecutorService); // Parse overlay configuration files to set default enable state, mutability, and // priority of system overlays. final ArrayMap<String, File> apkInApexPreInstalledPaths = new ArrayMap<>(); - for (ApexManager.ActiveApexInfo apexInfo : mPm.mApexManager.getActiveApexInfos()) { - for (String packageName : mPm.mApexManager.getApksInApex(apexInfo.apexModuleName)) { + for (ApexManager.ActiveApexInfo apexInfo : mApexManager.getActiveApexInfos()) { + for (String packageName : mApexManager.getApksInApex(apexInfo.apexModuleName)) { apkInApexPreInstalledPaths.put(packageName, apexInfo.preInstalledApexPath); } } - OverlayConfig overlayConfig = OverlayConfig.initializeSystemInstance( + final OverlayConfig overlayConfig = OverlayConfig.initializeSystemInstance( consumer -> mPm.forEachPackage(mPm.snapshotComputer(), pkg -> consumer.accept(pkg, pkg.isSystem(), - apkInApexPreInstalledPaths.get(pkg.getPackageName())))); - // Prune any system packages that no longer exist. - final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); - // Stub packages must either be replaced with full versions in the /data - // partition or be disabled. - final List<String> stubSystemApps = new ArrayList<>(); - - if (!mPm.isOnlyCoreApps()) { + apkInApexPreInstalledPaths.get(pkg.getPackageName())))); + + if (!mIsOnlyCoreApps) { // do this first before mucking with mPackages for the "expecting better" case - updateStubSystemAppsList(stubSystemApps); + updateStubSystemAppsList(mStubSystemApps); mInstallPackageHelper.prepareSystemPackageCleanUp(packageSettings, - possiblyDeletedUpdatedSystemApps, mExpectingBetter, userIds); + mPossiblyDeletedUpdatedSystemApps, mExpectingBetter, userIds); } - final int cachedSystemApps = PackageCacher.sCachedPackageReadCount.get(); + logSystemAppsScanningTime(startTime); + return overlayConfig; + } + + @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) + private void logSystemAppsScanningTime(long startTime) { + mCachedSystemApps = PackageCacher.sCachedPackageReadCount.get(); // Remove any shared userIDs that have no associated packages mPm.mSettings.pruneSharedUsersLPw(); - final long systemScanTime = SystemClock.uptimeMillis() - startTime; - final int systemPackagesCount = mPm.mPackages.size(); - Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime - + " ms, packageCount: " + systemPackagesCount + mSystemScanTime = SystemClock.uptimeMillis() - startTime; + mSystemPackagesCount = mPm.mPackages.size(); + Slog.i(TAG, "Finished scanning system apps. Time: " + mSystemScanTime + + " ms, packageCount: " + mSystemPackagesCount + " , timePerPackage: " - + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) - + " , cached: " + cachedSystemApps); - if (mPm.isDeviceUpgrading() && systemPackagesCount > 0) { + + (mSystemPackagesCount == 0 ? 0 : mSystemScanTime / mSystemPackagesCount) + + " , cached: " + mCachedSystemApps); + if (mIsDeviceUpgrading && mSystemPackagesCount > 0) { //CHECKSTYLE:OFF IndentationCheck FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED, BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_SYSTEM_APP_AVG_SCAN_TIME, - systemScanTime / systemPackagesCount); + mSystemScanTime / mSystemPackagesCount); //CHECKSTYLE:ON IndentationCheck } + } - if (!mPm.isOnlyCoreApps()) { + /** + * Install apps/updates from data dir and fix system apps that are affected. + */ + @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) + public void initNonSystemApps(PackageParser2 packageParser, @NonNull int[] userIds, + long startTime) { + if (!mIsOnlyCoreApps) { EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, SystemClock.uptimeMillis()); scanDirTracedLI(mPm.getAppInstallDir(), /* frameworkSplits= */ null, 0, - mScanFlags | SCAN_REQUIRE_KNOWN, 0, - packageParser, executorService); - + mScanFlags | SCAN_REQUIRE_KNOWN, + packageParser, mExecutorService); } - List<Runnable> unfinishedTasks = executorService.shutdownNow(); + List<Runnable> unfinishedTasks = mExecutorService.shutdownNow(); if (!unfinishedTasks.isEmpty()) { throw new IllegalStateException("Not all tasks finished before calling close: " + unfinishedTasks); } - - if (!mPm.isOnlyCoreApps()) { - mInstallPackageHelper.cleanupDisabledPackageSettings(possiblyDeletedUpdatedSystemApps, - userIds, mScanFlags); - mInstallPackageHelper.checkExistingBetterPackages(mExpectingBetter, - stubSystemApps, mSystemScanFlags, mSystemParseFlags); - - // Uncompress and install any stubbed system applications. - // This must be done last to ensure all stubs are replaced or disabled. - mInstallPackageHelper.installSystemStubPackages(stubSystemApps, mScanFlags); - - final int cachedNonSystemApps = PackageCacher.sCachedPackageReadCount.get() - - cachedSystemApps; - - final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; - final int dataPackagesCount = mPm.mPackages.size() - systemPackagesCount; - Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime - + " ms, packageCount: " + dataPackagesCount - + " , timePerPackage: " - + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) - + " , cached: " + cachedNonSystemApps); - if (mPm.isDeviceUpgrading() && dataPackagesCount > 0) { - //CHECKSTYLE:OFF IndentationCheck - FrameworkStatsLog.write( - FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED, - BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_DATA_APP_AVG_SCAN_TIME, - dataScanTime / dataPackagesCount); - //CHECKSTYLE:OFF IndentationCheck - } + if (!mIsOnlyCoreApps) { + fixSystemPackages(userIds); + logNonSystemAppScanningTime(startTime); } mExpectingBetter.clear(); - mPm.mSettings.pruneRenamedPackagesLPw(); - packageParser.close(); - return overlayConfig; + } + + /** + * Clean up system packages now that some system package updates have been installed from + * the data dir. Also install system stub packages as the last step. + */ + @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) + private void fixSystemPackages(@NonNull int[] userIds) { + mInstallPackageHelper.cleanupDisabledPackageSettings(mPossiblyDeletedUpdatedSystemApps, + userIds, mScanFlags); + mInstallPackageHelper.checkExistingBetterPackages(mExpectingBetter, + mStubSystemApps, mSystemScanFlags, mSystemParseFlags); + + // Uncompress and install any stubbed system applications. + // This must be done last to ensure all stubs are replaced or disabled. + mInstallPackageHelper.installSystemStubPackages(mStubSystemApps, mScanFlags); + } + + @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) + private void logNonSystemAppScanningTime(long startTime) { + final int cachedNonSystemApps = PackageCacher.sCachedPackageReadCount.get() + - mCachedSystemApps; + + final long dataScanTime = SystemClock.uptimeMillis() - mSystemScanTime - startTime; + final int dataPackagesCount = mPm.mPackages.size() - mSystemPackagesCount; + Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime + + " ms, packageCount: " + dataPackagesCount + + " , timePerPackage: " + + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) + + " , cached: " + cachedNonSystemApps); + if (mIsDeviceUpgrading && dataPackagesCount > 0) { + //CHECKSTYLE:OFF IndentationCheck + FrameworkStatsLog.write( + FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED, + BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_DATA_APP_AVG_SCAN_TIME, + dataScanTime / dataPackagesCount); + //CHECKSTYLE:OFF IndentationCheck + } } /** @@ -274,13 +313,13 @@ final class InitAndSystemPackageHelper { continue; } scanDirTracedLI(partition.getOverlayFolder(), /* frameworkSplits= */ null, - mSystemParseFlags, mSystemScanFlags | partition.scanFlag, 0, + mSystemParseFlags, mSystemScanFlags | partition.scanFlag, packageParser, executorService); } scanDirTracedLI(frameworkDir, null, mSystemParseFlags, - mSystemScanFlags | SCAN_NO_DEX | SCAN_AS_PRIVILEGED, 0, + mSystemScanFlags | SCAN_NO_DEX | SCAN_AS_PRIVILEGED, packageParser, executorService); if (!mPm.mPackages.containsKey("android")) { throw new IllegalStateException( @@ -292,11 +331,11 @@ final class InitAndSystemPackageHelper { if (partition.getPrivAppFolder() != null) { scanDirTracedLI(partition.getPrivAppFolder(), /* frameworkSplits= */ null, mSystemParseFlags, - mSystemScanFlags | SCAN_AS_PRIVILEGED | partition.scanFlag, 0, + mSystemScanFlags | SCAN_AS_PRIVILEGED | partition.scanFlag, packageParser, executorService); } scanDirTracedLI(partition.getAppFolder(), /* frameworkSplits= */ null, - mSystemParseFlags, mSystemScanFlags | partition.scanFlag, 0, + mSystemParseFlags, mSystemScanFlags | partition.scanFlag, packageParser, executorService); } } @@ -315,7 +354,7 @@ final class InitAndSystemPackageHelper { @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) private void scanDirTracedLI(File scanDir, List<File> frameworkSplits, int parseFlags, int scanFlags, - long currentTime, PackageParser2 packageParser, ExecutorService executorService) { + PackageParser2 packageParser, ExecutorService executorService) { Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); try { if ((scanFlags & SCAN_AS_APK_IN_APEX) != 0) { @@ -323,7 +362,7 @@ final class InitAndSystemPackageHelper { parseFlags |= PARSE_CHECK_MAX_SDK_VERSION; } mInstallPackageHelper.installPackagesFromDir(scanDir, frameworkSplits, parseFlags, - scanFlags, currentTime, packageParser, executorService); + scanFlags, packageParser, executorService); } finally { Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); } diff --git a/services/core/java/com/android/server/pm/InstallPackageHelper.java b/services/core/java/com/android/server/pm/InstallPackageHelper.java index b39b24f6defa..870a11ac2d61 100644 --- a/services/core/java/com/android/server/pm/InstallPackageHelper.java +++ b/services/core/java/com/android/server/pm/InstallPackageHelper.java @@ -3062,7 +3062,7 @@ final class InstallPackageHelper { final RemovePackageHelper removePackageHelper = new RemovePackageHelper(mPm); removePackageHelper.removePackageLI(stubPkg, true /*chatty*/); try { - return scanSystemPackageTracedLI(scanFile, parseFlags, scanFlags, 0, null); + return scanSystemPackageTracedLI(scanFile, parseFlags, scanFlags, null); } catch (PackageManagerException e) { Slog.w(TAG, "Failed to install compressed system package:" + stubPkg.getPackageName(), e); @@ -3194,7 +3194,7 @@ final class InstallPackageHelper { | ParsingPackageUtils.PARSE_IS_SYSTEM_DIR; @PackageManagerService.ScanFlags int scanFlags = mPm.getSystemPackageScanFlags(codePath); final AndroidPackage pkg = scanSystemPackageTracedLI( - codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); + codePath, parseFlags, scanFlags, null); PackageSetting pkgSetting = mPm.mSettings.getPackageLPr(pkg.getPackageName()); @@ -3368,7 +3368,7 @@ final class InstallPackageHelper { mRemovePackageHelper.removePackageLI(pkg, true); try { final File codePath = new File(pkg.getPath()); - scanSystemPackageTracedLI(codePath, 0, scanFlags, 0, null); + scanSystemPackageTracedLI(codePath, 0, scanFlags, null); } catch (PackageManagerException e) { Slog.e(TAG, "Failed to parse updated, ex-system package: " + e.getMessage()); @@ -3389,7 +3389,7 @@ final class InstallPackageHelper { @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) public void installPackagesFromDir(File scanDir, List<File> frameworkSplits, int parseFlags, - int scanFlags, long currentTime, PackageParser2 packageParser, + int scanFlags, PackageParser2 packageParser, ExecutorService executorService) { final File[] files = scanDir.listFiles(); if (ArrayUtils.isEmpty(files)) { @@ -3432,7 +3432,7 @@ final class InstallPackageHelper { parseResult.parsedPackage); } try { - addForInitLI(parseResult.parsedPackage, parseFlags, scanFlags, currentTime, + addForInitLI(parseResult.parsedPackage, parseFlags, scanFlags, null); } catch (PackageManagerException e) { errorCode = e.error; @@ -3495,7 +3495,7 @@ final class InstallPackageHelper { try { final AndroidPackage newPkg = scanSystemPackageTracedLI( - scanFile, reparseFlags, rescanFlags, 0, null); + scanFile, reparseFlags, rescanFlags, null); // We rescanned a stub, add it to the list of stubbed system packages if (newPkg.isStub()) { stubSystemApps.add(packageName); @@ -3509,14 +3509,14 @@ final class InstallPackageHelper { /** * Traces a package scan. - * @see #scanSystemPackageLI(File, int, int, long, UserHandle) + * @see #scanSystemPackageLI(File, int, int, UserHandle) */ @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) public AndroidPackage scanSystemPackageTracedLI(File scanFile, final int parseFlags, - int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { + int scanFlags, UserHandle user) throws PackageManagerException { Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); try { - return scanSystemPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); + return scanSystemPackageLI(scanFile, parseFlags, scanFlags, user); } finally { Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); } @@ -3528,7 +3528,7 @@ final class InstallPackageHelper { */ @GuardedBy({"mPm.mInstallLock", "mPm.mLock"}) private AndroidPackage scanSystemPackageLI(File scanFile, int parseFlags, int scanFlags, - long currentTime, UserHandle user) throws PackageManagerException { + UserHandle user) throws PackageManagerException { if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); @@ -3544,7 +3544,7 @@ final class InstallPackageHelper { PackageManagerService.renameStaticSharedLibraryPackage(parsedPackage); } - return addForInitLI(parsedPackage, parseFlags, scanFlags, currentTime, user); + return addForInitLI(parsedPackage, parseFlags, scanFlags, user); } /** @@ -3563,11 +3563,11 @@ final class InstallPackageHelper { @GuardedBy({"mPm.mLock", "mPm.mInstallLock"}) private AndroidPackage addForInitLI(ParsedPackage parsedPackage, @ParsingPackageUtils.ParseFlags int parseFlags, - @PackageManagerService.ScanFlags int scanFlags, long currentTime, + @PackageManagerService.ScanFlags int scanFlags, @Nullable UserHandle user) throws PackageManagerException { final Pair<ScanResult, Boolean> scanResultPair = scanSystemPackageLI( - parsedPackage, parseFlags, scanFlags, currentTime, user); + parsedPackage, parseFlags, scanFlags, user); final ScanResult scanResult = scanResultPair.first; boolean shouldHideSystemApp = scanResultPair.second; if (scanResult.mSuccess) { @@ -3762,7 +3762,7 @@ final class InstallPackageHelper { private Pair<ScanResult, Boolean> scanSystemPackageLI(ParsedPackage parsedPackage, @ParsingPackageUtils.ParseFlags int parseFlags, - @PackageManagerService.ScanFlags int scanFlags, long currentTime, + @PackageManagerService.ScanFlags int scanFlags, @Nullable UserHandle user) throws PackageManagerException { final boolean scanSystemPartition = (parseFlags & ParsingPackageUtils.PARSE_IS_SYSTEM_DIR) != 0; @@ -3950,7 +3950,7 @@ final class InstallPackageHelper { } final ScanResult scanResult = scanPackageNewLI(parsedPackage, parseFlags, - scanFlags | SCAN_UPDATE_SIGNATURE, currentTime, user, null); + scanFlags | SCAN_UPDATE_SIGNATURE, 0 /* currentTime */, user, null); return new Pair<>(scanResult, shouldHideSystemApp); } diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java index eaecb17103a5..b1b05bedfcad 100644 --- a/services/core/java/com/android/server/pm/PackageManagerService.java +++ b/services/core/java/com/android/server/pm/PackageManagerService.java @@ -229,7 +229,6 @@ import com.android.server.pm.resolution.ComponentResolverApi; import com.android.server.pm.verify.domain.DomainVerificationManagerInternal; import com.android.server.pm.verify.domain.DomainVerificationService; import com.android.server.pm.verify.domain.proxy.DomainVerificationProxy; -import com.android.server.pm.verify.domain.proxy.DomainVerificationProxyV1; import com.android.server.sdksandbox.SdkSandboxManagerLocal; import com.android.server.storage.DeviceStorageMonitorInternal; import com.android.server.utils.SnapshotCache; @@ -936,7 +935,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService private final BroadcastHelper mBroadcastHelper; private final RemovePackageHelper mRemovePackageHelper; private final DeletePackageHelper mDeletePackageHelper; - private final InitAndSystemPackageHelper mInitAndSystemPackageHelper; + private final InitAppsHelper mInitAppsHelper; private final AppDataHelper mAppDataHelper; private final InstallPackageHelper mInstallPackageHelper; private final PreferredActivityHelper mPreferredActivityHelper; @@ -1671,7 +1670,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService mAppDataHelper = testParams.appDataHelper; mInstallPackageHelper = testParams.installPackageHelper; mRemovePackageHelper = testParams.removePackageHelper; - mInitAndSystemPackageHelper = testParams.initAndSystemPackageHelper; + mInitAppsHelper = testParams.initAndSystemPackageHelper; mDeletePackageHelper = testParams.deletePackageHelper; mPreferredActivityHelper = testParams.preferredActivityHelper; mResolveIntentHelper = testParams.resolveIntentHelper; @@ -1821,7 +1820,8 @@ public class PackageManagerService implements PackageSender, TestUtilityService mAppDataHelper = new AppDataHelper(this); mInstallPackageHelper = new InstallPackageHelper(this, mAppDataHelper); mRemovePackageHelper = new RemovePackageHelper(this, mAppDataHelper); - mInitAndSystemPackageHelper = new InitAndSystemPackageHelper(this); + mInitAppsHelper = new InitAppsHelper(this, mApexManager, mInstallPackageHelper, + mInjector.getSystemPartitions()); mDeletePackageHelper = new DeletePackageHelper(this, mRemovePackageHelper, mAppDataHelper); mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper); @@ -1956,8 +1956,11 @@ public class PackageManagerService implements PackageSender, TestUtilityService mIsEngBuild, mIsUserDebugBuild, mIncrementalVersion); final int[] userIds = mUserManager.getUserIds(); - mOverlayConfig = mInitAndSystemPackageHelper.initPackages(packageSettings, - userIds, startTime); + PackageParser2 packageParser = mInjector.getScanningCachingPackageParser(); + mOverlayConfig = mInitAppsHelper.initSystemApps(packageParser, packageSettings, userIds, + startTime); + mInitAppsHelper.initNonSystemApps(packageParser, userIds, startTime); + packageParser.close(); // Resolve the storage manager. mStorageManagerPackage = getStorageManagerPackageName(computer); @@ -7030,7 +7033,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService } boolean isExpectingBetter(String packageName) { - return mInitAndSystemPackageHelper.isExpectingBetter(packageName); + return mInitAppsHelper.isExpectingBetter(packageName); } int getDefParseFlags() { @@ -7129,13 +7132,12 @@ public class PackageManagerService implements PackageSender, TestUtilityService } boolean isOverlayMutable(String packageName) { - return (mOverlayConfig != null ? mOverlayConfig - : OverlayConfig.getSystemInstance()).isMutable(packageName); + return mOverlayConfig.isMutable(packageName); } @ScanFlags int getSystemPackageScanFlags(File codePath) { List<ScanPartition> dirsToScanAsSystem = - mInitAndSystemPackageHelper.getDirsToScanAsSystem(); + mInitAppsHelper.getDirsToScanAsSystem(); @PackageManagerService.ScanFlags int scanFlags = SCAN_AS_SYSTEM; for (int i = dirsToScanAsSystem.size() - 1; i >= 0; i--) { ScanPartition partition = dirsToScanAsSystem.get(i); @@ -7153,7 +7155,7 @@ public class PackageManagerService implements PackageSender, TestUtilityService Pair<Integer, Integer> getSystemPackageRescanFlagsAndReparseFlags(File scanFile, int systemScanFlags, int systemParseFlags) { List<ScanPartition> dirsToScanAsSystem = - mInitAndSystemPackageHelper.getDirsToScanAsSystem(); + mInitAppsHelper.getDirsToScanAsSystem(); @ParsingPackageUtils.ParseFlags int reparseFlags = 0; @PackageManagerService.ScanFlags int rescanFlags = 0; for (int i1 = dirsToScanAsSystem.size() - 1; i1 >= 0; i1--) { diff --git a/services/core/java/com/android/server/pm/PackageManagerServiceTestParams.java b/services/core/java/com/android/server/pm/PackageManagerServiceTestParams.java index 5bdda0b3c1d8..e466fe2c0e31 100644 --- a/services/core/java/com/android/server/pm/PackageManagerServiceTestParams.java +++ b/services/core/java/com/android/server/pm/PackageManagerServiceTestParams.java @@ -109,7 +109,7 @@ public final class PackageManagerServiceTestParams { public AppDataHelper appDataHelper; public InstallPackageHelper installPackageHelper; public RemovePackageHelper removePackageHelper; - public InitAndSystemPackageHelper initAndSystemPackageHelper; + public InitAppsHelper initAndSystemPackageHelper; public DeletePackageHelper deletePackageHelper; public PreferredActivityHelper preferredActivityHelper; public ResolveIntentHelper resolveIntentHelper; diff --git a/services/core/java/com/android/server/pm/StorageEventHelper.java b/services/core/java/com/android/server/pm/StorageEventHelper.java index df19d3e58bfd..a991ed3c4792 100644 --- a/services/core/java/com/android/server/pm/StorageEventHelper.java +++ b/services/core/java/com/android/server/pm/StorageEventHelper.java @@ -151,7 +151,7 @@ public final class StorageEventHelper extends StorageEventListener { final AndroidPackage pkg; try { pkg = installPackageHelper.scanSystemPackageTracedLI( - ps.getPath(), parseFlags, SCAN_INITIAL, 0, null); + ps.getPath(), parseFlags, SCAN_INITIAL, null); loaded.add(pkg); } catch (PackageManagerException e) { diff --git a/services/core/java/com/android/server/pm/TEST_MAPPING b/services/core/java/com/android/server/pm/TEST_MAPPING index 9c74dd795d30..88a298a756d4 100644 --- a/services/core/java/com/android/server/pm/TEST_MAPPING +++ b/services/core/java/com/android/server/pm/TEST_MAPPING @@ -52,6 +52,9 @@ "options": [ { "include-filter": "com.google.android.security.gts.PackageVerifierTest" + }, + { + "exclude-filter": "com.google.android.security.gts.PackageVerifierTest#testAdbInstall_timeout_allowed" } ] }, diff --git a/services/core/java/com/android/server/pm/UserManagerService.java b/services/core/java/com/android/server/pm/UserManagerService.java index 34b7ad41e540..70053bdeb47e 100644 --- a/services/core/java/com/android/server/pm/UserManagerService.java +++ b/services/core/java/com/android/server/pm/UserManagerService.java @@ -5409,6 +5409,21 @@ public class UserManagerService extends IUserManager.Stub { (new Shell()).exec(this, in, out, err, args, callback, resultReceiver); } + private static final String PREFIX_HELP_COMMAND = " "; + private static final String PREFIX_HELP_DESCRIPTION = " "; + private static final String PREFIX_HELP_DESCRIPTION_EXTRA_LINES = " "; + + private static final String CMD_HELP = "help"; + private static final String CMD_LIST = "list"; + private static final String CMD_REPORT_SYSTEM_USER_PACKAGE_ALLOWLIST_PROBLEMS = + "report-system-user-package-whitelist-problems"; + + private static final String ARG_V = "-v"; + private static final String ARG_VERBOSE = "--verbose"; + private static final String ARG_ALL = "--all"; + private static final String ARG_CRITICAL_ONLY = "--critical-only"; + private static final String ARG_MODE = "--mode"; + private int onShellCommand(Shell shell, String cmd) { if (cmd == null) { return shell.handleDefaultCommands(cmd); @@ -5417,9 +5432,9 @@ public class UserManagerService extends IUserManager.Stub { final PrintWriter pw = shell.getOutPrintWriter(); try { switch(cmd) { - case "list": + case CMD_LIST: return runList(pw, shell); - case "report-system-user-package-whitelist-problems": + case CMD_REPORT_SYSTEM_USER_PACKAGE_ALLOWLIST_PROBLEMS: return runReportPackageWhitelistProblems(pw, shell); default: return shell.handleDefaultCommands(cmd); @@ -5436,10 +5451,10 @@ public class UserManagerService extends IUserManager.Stub { String opt; while ((opt = shell.getNextOption()) != null) { switch (opt) { - case "-v": + case ARG_V: verbose = true; break; - case "--all": + case ARG_ALL: all = true; break; default: @@ -5520,14 +5535,14 @@ public class UserManagerService extends IUserManager.Stub { String opt; while ((opt = shell.getNextOption()) != null) { switch (opt) { - case "-v": - case "--verbose": + case ARG_V: + case ARG_VERBOSE: verbose = true; break; - case "--critical-only": + case ARG_CRITICAL_ONLY: criticalOnly = true; break; - case "--mode": + case ARG_MODE: mode = Integer.parseInt(shell.getNextArgRequired()); break; default: @@ -6248,20 +6263,28 @@ public class UserManagerService extends IUserManager.Stub { @Override public void onHelp() { final PrintWriter pw = getOutPrintWriter(); - pw.println("User manager (user) commands:"); - pw.println(" help"); - pw.println(" Prints this help text."); - pw.println(""); - pw.println(" list [-v] [-all]"); - pw.println(" Prints all users on the system."); - pw.println(" report-system-user-package-whitelist-problems [-v | --verbose] " - + "[--critical-only] [--mode MODE]"); - pw.println(" Reports all issues on user-type package whitelist XML files. Options:"); - pw.println(" -v | --verbose : shows extra info, like number of issues"); - pw.println(" --critical-only: show only critical issues, excluding warnings"); - pw.println(" --mode MODE: shows what errors would be if device used mode MODE (where" - + " MODE is the whitelist mode integer as defined by " - + "config_userTypePackageWhitelistMode)"); + pw.printf("User manager (user) commands:\n"); + + pw.printf("%s%s\n", PREFIX_HELP_COMMAND, CMD_HELP); + pw.printf("%sPrints this help text.\n\n", PREFIX_HELP_DESCRIPTION); + + pw.printf("%s%s [%s] [%s]\n", PREFIX_HELP_COMMAND, CMD_LIST, ARG_V, ARG_ALL); + pw.printf("%sPrints all users on the system.\n\n", PREFIX_HELP_DESCRIPTION); + + pw.printf("%s%s [%s | %s] [%s] [%s MODE]\n", PREFIX_HELP_COMMAND, + CMD_REPORT_SYSTEM_USER_PACKAGE_ALLOWLIST_PROBLEMS, + ARG_V, ARG_VERBOSE, ARG_CRITICAL_ONLY, ARG_MODE); + + pw.printf("%sReports all issues on user-type package allowlist XML files. Options:\n", + PREFIX_HELP_DESCRIPTION); + pw.printf("%s%s | %s: shows extra info, like number of issues\n", + PREFIX_HELP_DESCRIPTION, ARG_V, ARG_VERBOSE); + pw.printf("%s%s: show only critical issues, excluding warnings\n", + PREFIX_HELP_DESCRIPTION, ARG_CRITICAL_ONLY); + pw.printf("%s%s MODE: shows what errors would be if device used mode MODE\n" + + "%s(where MODE is the allowlist mode integer as defined by " + + "config_userTypePackageWhitelistMode)\n\n", + PREFIX_HELP_DESCRIPTION, ARG_MODE, PREFIX_HELP_DESCRIPTION_EXTRA_LINES); } } diff --git a/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java b/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java index 46fde4b59d8b..60602337ba1a 100644 --- a/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java +++ b/services/core/java/com/android/server/pm/permission/OneTimePermissionUserManager.java @@ -272,6 +272,10 @@ public class OneTimePermissionUserManager { mHandler.removeCallbacksAndMessages(mToken); if (importance > IMPORTANCE_CACHED) { + if (mRevokeAfterKilledDelay == 0) { + onPackageInactiveLocked(); + return; + } // Delay revocation in case app is restarting mHandler.postDelayed(() -> { int imp = mActivityManager.getUidImportance(mUid); diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java index 71554eee3127..5a05134bed81 100644 --- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java +++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java @@ -562,12 +562,6 @@ public class PermissionManagerService extends IPermissionManager.Stub { } @Override - public void revokeOwnPermissionsOnKill(@NonNull String packageName, - @NonNull List<String> permissions) { - mPermissionManagerServiceImpl.revokeOwnPermissionsOnKill(packageName, permissions); - } - - @Override public boolean shouldShowRequestPermissionRationale(String packageName, String permissionName, int userId) { return mPermissionManagerServiceImpl.shouldShowRequestPermissionRationale(packageName, diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java index d0609307e6a8..009d155e96ef 100644 --- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java +++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceImpl.java @@ -1597,25 +1597,6 @@ public class PermissionManagerServiceImpl implements PermissionManagerServiceInt } } - @Override - public void revokeOwnPermissionsOnKill(String packageName, List<String> permissions) { - final int callingUid = Binder.getCallingUid(); - int callingUserId = UserHandle.getUserId(callingUid); - int targetPackageUid = mPackageManagerInt.getPackageUid(packageName, 0, callingUserId); - if (targetPackageUid != callingUid) { - throw new SecurityException("uid " + callingUid - + " cannot revoke permissions for package " + packageName + " with uid " - + targetPackageUid); - } - for (String permName : permissions) { - if (!checkCallingOrSelfPermission(permName)) { - throw new SecurityException("uid " + callingUid + " cannot revoke permission " - + permName + " because it does not hold that permission"); - } - } - mPermissionControllerManager.revokeOwnPermissionsOnKill(packageName, permissions); - } - private boolean mayManageRolePermission(int uid) { final PackageManager packageManager = mContext.getPackageManager(); final String[] packageNames = packageManager.getPackagesForUid(uid); diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java index 3e28320a2130..3771f030aefa 100644 --- a/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java +++ b/services/core/java/com/android/server/pm/permission/PermissionManagerServiceInterface.java @@ -327,28 +327,6 @@ public interface PermissionManagerServiceInterface extends PermissionManagerInte void revokePostNotificationPermissionWithoutKillForTest(String packageName, int userId); /** - * Triggers the revocation of one or more permissions for a package, under the following - * conditions: - * <ul> - * <li>The package {@code packageName} must be under the same UID as the calling process - * (typically, the target package is the calling package). - * <li>Each permission in {@code permissions} must be granted to the package - * {@code packageName}. - * <li>Each permission in {@code permissions} must be a runtime permission. - * </ul> - * <p> - * Background permissions which have no corresponding foreground permission still granted once - * the revocation is effective will also be revoked. - * <p> - * This revocation happens asynchronously and kills all processes running in the same UID as - * {@code packageName}. It will be triggered once it is safe to do so. - * - * @param packageName The name of the package for which the permissions will be revoked. - * @param permissions List of permissions to be revoked. - */ - void revokeOwnPermissionsOnKill(String packageName, List<String> permissions); - - /** * Get whether you should show UI with rationale for requesting a permission. You should do this * only if you do not have the permission and the context in which the permission is requested * does not clearly communicate to the user what would be the benefit from grating this diff --git a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java index 2e60f130bc4b..526dccb72e39 100644 --- a/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java +++ b/services/core/java/com/android/server/stats/pull/StatsPullAtomService.java @@ -1633,7 +1633,14 @@ public class StatsPullAtomService extends SystemService { if (adapter != null) { SynchronousResultReceiver bluetoothReceiver = new SynchronousResultReceiver("bluetooth"); - adapter.requestControllerActivityEnergyInfo(bluetoothReceiver); + adapter.requestControllerActivityEnergyInfo( + Runnable::run, + info -> { + Bundle bundle = new Bundle(); + bundle.putParcelable(BatteryStats.RESULT_RECEIVER_CONTROLLER_KEY, info); + bluetoothReceiver.send(0, bundle); + } + ); return awaitControllerInfo(bluetoothReceiver); } else { Slog.e(TAG, "Failed to get bluetooth adapter!"); @@ -2338,51 +2345,25 @@ public class StatsPullAtomService extends SystemService { } int pullProcessDmabufMemory(int atomTag, List<StatsEvent> pulledData) { - List<ProcessMemoryState> managedProcessList = - LocalServices.getService(ActivityManagerInternal.class) - .getMemoryStateForProcesses(); - for (ProcessMemoryState process : managedProcessList) { - KernelAllocationStats.ProcessDmabuf proc = - KernelAllocationStats.getDmabufAllocations(process.pid); - if (proc == null || (proc.retainedBuffersCount <= 0 && proc.mappedBuffersCount <= 0)) { - continue; - } - pulledData.add( - FrameworkStatsLog.buildStatsEvent( - atomTag, - process.uid, - process.processName, - process.oomScore, - proc.retainedSizeKb, - proc.retainedBuffersCount, - proc.mappedSizeKb, - proc.mappedBuffersCount)); + KernelAllocationStats.ProcessDmabuf[] procBufs = + KernelAllocationStats.getDmabufAllocations(); + + if (procBufs == null) { + return StatsManager.PULL_SKIP; } - SparseArray<String> processCmdlines = getProcessCmdlines(); - managedProcessList.forEach(managedProcess -> processCmdlines.delete(managedProcess.pid)); - int size = processCmdlines.size(); - for (int i = 0; i < size; ++i) { - int pid = processCmdlines.keyAt(i); - int uid = getUidForPid(pid); - // ignore root processes (unlikely to be interesting) - if (uid <= 0) { - continue; - } - KernelAllocationStats.ProcessDmabuf proc = - KernelAllocationStats.getDmabufAllocations(pid); - if (proc == null || (proc.retainedBuffersCount <= 0 && proc.mappedBuffersCount <= 0)) { - continue; - } - pulledData.add( - FrameworkStatsLog.buildStatsEvent( - atomTag, - uid, - processCmdlines.valueAt(i), - -1001 /*Placeholder for native processes, OOM_SCORE_ADJ_MIN - 1.*/, - proc.retainedSizeKb, - proc.retainedBuffersCount, - proc.mappedSizeKb, - proc.mappedBuffersCount)); + for (KernelAllocationStats.ProcessDmabuf procBuf : procBufs) { + pulledData.add(FrameworkStatsLog.buildStatsEvent( + atomTag, + procBuf.uid, + procBuf.processName, + procBuf.oomScore, + procBuf.retainedSizeKb, + procBuf.retainedBuffersCount, + 0, /* mapped_dmabuf_kb - deprecated */ + 0, /* mapped_dmabuf_count - deprecated */ + procBuf.surfaceFlingerSizeKb, + procBuf.surfaceFlingerCount + )); } return StatsManager.PULL_SUCCESS; } diff --git a/services/core/java/com/android/server/trust/TrustAgentWrapper.java b/services/core/java/com/android/server/trust/TrustAgentWrapper.java index 20cd8f5c12f8..adca21676f9d 100644 --- a/services/core/java/com/android/server/trust/TrustAgentWrapper.java +++ b/services/core/java/com/android/server/trust/TrustAgentWrapper.java @@ -198,6 +198,8 @@ public class TrustAgentWrapper { // Fall through. case MSG_REVOKE_TRUST: mTrusted = false; + mTrustable = false; + mWaitingForTrustableDowngrade = false; mDisplayTrustGrantedMessage = false; mMessage = null; mHandler.removeMessages(MSG_TRUST_TIMEOUT); diff --git a/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java b/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java index 53a9244837ed..c252043028c9 100644 --- a/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java +++ b/services/core/java/com/android/server/tv/interactive/TvInteractiveAppManagerService.java @@ -42,8 +42,8 @@ import android.media.tv.interactive.ITvInteractiveAppService; import android.media.tv.interactive.ITvInteractiveAppServiceCallback; import android.media.tv.interactive.ITvInteractiveAppSession; import android.media.tv.interactive.ITvInteractiveAppSessionCallback; -import android.media.tv.interactive.TvInteractiveAppInfo; import android.media.tv.interactive.TvInteractiveAppService; +import android.media.tv.interactive.TvInteractiveAppServiceInfo; import android.net.Uri; import android.os.Binder; import android.os.Bundle; @@ -130,7 +130,7 @@ public class TvInteractiveAppManagerService extends SystemService { new Intent(TvInteractiveAppService.SERVICE_INTERFACE), PackageManager.GET_SERVICES | PackageManager.GET_META_DATA, userId); - List<TvInteractiveAppInfo> iAppList = new ArrayList<>(); + List<TvInteractiveAppServiceInfo> iAppList = new ArrayList<>(); for (ResolveInfo ri : services) { ServiceInfo si = ri.serviceInfo; @@ -143,8 +143,8 @@ public class TvInteractiveAppManagerService extends SystemService { ComponentName component = new ComponentName(si.packageName, si.name); try { - TvInteractiveAppInfo info = - new TvInteractiveAppInfo(mContext, component); + TvInteractiveAppServiceInfo info = + new TvInteractiveAppServiceInfo(mContext, component); iAppList.add(info); } catch (Exception e) { Slogf.e(TAG, "failed to load TV Interactive App service " + si.name, e); @@ -154,10 +154,10 @@ public class TvInteractiveAppManagerService extends SystemService { } // sort the iApp list by iApp service id - Collections.sort(iAppList, Comparator.comparing(TvInteractiveAppInfo::getId)); + Collections.sort(iAppList, Comparator.comparing(TvInteractiveAppServiceInfo::getId)); Map<String, TvInteractiveAppState> iAppMap = new HashMap<>(); ArrayMap<String, Integer> tiasAppCount = new ArrayMap<>(iAppMap.size()); - for (TvInteractiveAppInfo info : iAppList) { + for (TvInteractiveAppServiceInfo info : iAppList) { String iAppServiceId = info.getId(); if (DEBUG) { Slogf.d(TAG, "add " + iAppServiceId); @@ -195,7 +195,7 @@ public class TvInteractiveAppManagerService extends SystemService { for (String iAppServiceId : userState.mIAppMap.keySet()) { if (!iAppMap.containsKey(iAppServiceId)) { - TvInteractiveAppInfo info = userState.mIAppMap.get(iAppServiceId).mInfo; + TvInteractiveAppServiceInfo info = userState.mIAppMap.get(iAppServiceId).mInfo; ServiceState serviceState = userState.mServiceStateMap.get(info.getComponent()); if (serviceState != null) { abortPendingCreateSessionRequestsLocked(serviceState, iAppServiceId, userId); @@ -283,7 +283,7 @@ public class TvInteractiveAppManagerService extends SystemService { userState.mCallbacks.finishBroadcast(); } - private int getInteractiveAppUid(TvInteractiveAppInfo info) { + private int getInteractiveAppUid(TvInteractiveAppServiceInfo info) { try { return getContext().getPackageManager().getApplicationInfo( info.getServiceInfo().packageName, 0).uid; @@ -642,7 +642,7 @@ public class TvInteractiveAppManagerService extends SystemService { private final class BinderService extends ITvInteractiveAppManager.Stub { @Override - public List<TvInteractiveAppInfo> getTvInteractiveAppServiceList(int userId) { + public List<TvInteractiveAppServiceInfo> getTvInteractiveAppServiceList(int userId) { final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), Binder.getCallingUid(), userId, "getTvInteractiveAppServiceList"); final long identity = Binder.clearCallingIdentity(); @@ -653,7 +653,7 @@ public class TvInteractiveAppManagerService extends SystemService { mGetServiceListCalled = true; } UserState userState = getOrCreateUserStateLocked(resolvedUserId); - List<TvInteractiveAppInfo> iAppList = new ArrayList<>(); + List<TvInteractiveAppServiceInfo> iAppList = new ArrayList<>(); for (TvInteractiveAppState state : userState.mIAppMap.values()) { iAppList.add(state.mInfo); } @@ -1360,6 +1360,32 @@ public class TvInteractiveAppManagerService extends SystemService { } @Override + public void sendSigningResult( + IBinder sessionToken, String signingId, byte[] result, int userId) { + if (DEBUG) { + Slogf.d(TAG, "sendSigningResult(signingId=%s)", signingId); + } + final int callingUid = Binder.getCallingUid(); + final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, + userId, "sendSigningResult"); + SessionState sessionState = null; + final long identity = Binder.clearCallingIdentity(); + try { + synchronized (mLock) { + try { + sessionState = getSessionStateLocked(sessionToken, callingUid, + resolvedUserId); + getSessionLocked(sessionState).sendSigningResult(signingId, result); + } catch (RemoteException | SessionNotFoundException e) { + Slogf.e(TAG, "error in sendSigningResult", e); + } + } + } finally { + Binder.restoreCallingIdentity(identity); + } + } + + @Override public void setSurface(IBinder sessionToken, Surface surface, int userId) { final int callingUid = Binder.getCallingUid(); final int resolvedUserId = resolveCallingUserId(Binder.getCallingPid(), callingUid, @@ -1738,7 +1764,7 @@ public class TvInteractiveAppManagerService extends SystemService { private static final class TvInteractiveAppState { private String mIAppServiceId; private ComponentName mComponentName; - private TvInteractiveAppInfo mInfo; + private TvInteractiveAppServiceInfo mInfo; private int mUid; private int mIAppNumber; } @@ -2221,6 +2247,24 @@ public class TvInteractiveAppManagerService extends SystemService { } @Override + public void onRequestSigning(String id, String algorithm, String alias, byte[] data) { + synchronized (mLock) { + if (DEBUG) { + Slogf.d(TAG, "onRequestSigning"); + } + if (mSessionState.mSession == null || mSessionState.mClient == null) { + return; + } + try { + mSessionState.mClient.onRequestSigning( + id, algorithm, alias, data, mSessionState.mSeq); + } catch (RemoteException e) { + Slogf.e(TAG, "error in onRequestSigning", e); + } + } + } + + @Override public void onAdRequest(AdRequest request) { synchronized (mLock) { if (DEBUG) { diff --git a/services/core/java/com/android/server/utils/TimingsTraceAndSlog.java b/services/core/java/com/android/server/utils/TimingsTraceAndSlog.java index 397acfac2812..b45c962811ad 100644 --- a/services/core/java/com/android/server/utils/TimingsTraceAndSlog.java +++ b/services/core/java/com/android/server/utils/TimingsTraceAndSlog.java @@ -88,7 +88,7 @@ public final class TimingsTraceAndSlog extends TimingsTraceLog { @Override public void traceBegin(@NonNull String name) { - Slog.i(mTag, name); + Slog.d(mTag, name); super.traceBegin(name); } diff --git a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java index c0cdec9ade7f..7f84f61a91ff 100644 --- a/services/core/java/com/android/server/wm/ActivityMetricsLogger.java +++ b/services/core/java/com/android/server/wm/ActivityMetricsLogger.java @@ -191,6 +191,35 @@ class ActivityMetricsLogger { private long mCurrentTransitionStartTimeNs; /** Non-null when a {@link TransitionInfo} is created for this state. */ private TransitionInfo mAssociatedTransitionInfo; + /** The sequence id for trace. It is used to map the traces before resolving intent. */ + private static int sTraceSeqId; + /** The trace format is "launchingActivity#$seqId:$state(:$packageName)". */ + final String mTraceName; + + LaunchingState() { + if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + mTraceName = null; + return; + } + // Use an id because the launching app is not yet known before resolving intent. + sTraceSeqId++; + mTraceName = "launchingActivity#" + sTraceSeqId; + Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, mTraceName, 0); + } + + void stopTrace(boolean abort) { + if (mTraceName == null) return; + Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, mTraceName, 0); + final String launchResult; + if (mAssociatedTransitionInfo == null) { + launchResult = ":failed"; + } else { + launchResult = (abort ? ":canceled:" : ":completed:") + + mAssociatedTransitionInfo.mLastLaunchedActivity.packageName; + } + // Put a supplement trace as the description of the async trace with the same id. + Trace.instant(Trace.TRACE_TAG_ACTIVITY_MANAGER, mTraceName + launchResult); + } @VisibleForTesting boolean allDrawn() { @@ -549,10 +578,10 @@ class ActivityMetricsLogger { } if (existingInfo == null) { - // Only notify the observer for a new launching event. - launchObserverNotifyIntentStarted(intent, transitionStartTimeNs); final LaunchingState launchingState = new LaunchingState(); launchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs; + // Only notify the observer for a new launching event. + launchObserverNotifyIntentStarted(intent, transitionStartTimeNs); return launchingState; } existingInfo.mLaunchingState.mCurrentTransitionStartTimeNs = transitionStartTimeNs; @@ -574,7 +603,7 @@ class ActivityMetricsLogger { @Nullable ActivityOptions options) { if (launchedActivity == null) { // The launch is aborted, e.g. intent not resolved, class not found. - abort(null /* info */, "nothing launched"); + abort(launchingState, "nothing launched"); return; } @@ -601,7 +630,7 @@ class ActivityMetricsLogger { if (launchedActivity.isReportedDrawn() && launchedActivity.isVisible()) { // Launched activity is already visible. We cannot measure windows drawn delay. - abort(info, "launched activity already visible"); + abort(launchingState, "launched activity already visible"); return; } @@ -633,7 +662,7 @@ class ActivityMetricsLogger { final TransitionInfo newInfo = TransitionInfo.create(launchedActivity, launchingState, options, processRunning, processSwitch, newActivityCreated, resultCode); if (newInfo == null) { - abort(info, "unrecognized launch"); + abort(launchingState, "unrecognized launch"); return; } @@ -874,23 +903,29 @@ class ActivityMetricsLogger { } } + private void abort(@NonNull LaunchingState state, String cause) { + if (state.mAssociatedTransitionInfo != null) { + abort(state.mAssociatedTransitionInfo, cause); + return; + } + if (DEBUG_METRICS) Slog.i(TAG, "abort launch cause=" + cause); + state.stopTrace(true /* abort */); + launchObserverNotifyIntentFailed(); + } + /** Aborts tracking of current launch metrics. */ - private void abort(TransitionInfo info, String cause) { + private void abort(@NonNull TransitionInfo info, String cause) { done(true /* abort */, info, cause, 0L /* timestampNs */); } /** Called when the given transition (info) is no longer active. */ - private void done(boolean abort, @Nullable TransitionInfo info, String cause, + private void done(boolean abort, @NonNull TransitionInfo info, String cause, long timestampNs) { if (DEBUG_METRICS) { Slog.i(TAG, "done abort=" + abort + " cause=" + cause + " timestamp=" + timestampNs + " info=" + info); } - if (info == null) { - launchObserverNotifyIntentFailed(); - return; - } - + info.mLaunchingState.stopTrace(abort); stopLaunchTrace(info); final Boolean isHibernating = mLastHibernationStates.remove(info.mLastLaunchedActivity.packageName); @@ -1457,7 +1492,7 @@ class ActivityMetricsLogger { /** Starts trace for an activity is actually launching. */ private void startLaunchTrace(@NonNull TransitionInfo info) { if (DEBUG_METRICS) Slog.i(TAG, "startLaunchTrace " + info); - if (!Trace.isTagEnabled(Trace.TRACE_TAG_ACTIVITY_MANAGER)) { + if (info.mLaunchingState.mTraceName == null) { return; } info.mLaunchTraceName = "launching: " + info.mLastLaunchedActivity.packageName; diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index 883ce99d313d..bfe1f30f671a 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -5603,19 +5603,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A "makeInvisible", true /* beforeStopping */); // Defer telling the client it is hidden if it can enter Pip and isn't current paused, // stopped or stopping. This gives it a chance to enter Pip in onPause(). - // TODO: There is still a question surrounding activities in multi-window mode that want - // to enter Pip after they are paused, but are still visible. I they should be okay to - // enter Pip in those cases, but not "auto-Pip" which is what this condition covers and - // the current contract for "auto-Pip" is that the app should enter it before onPause - // returns. Just need to confirm this reasoning makes sense. final boolean deferHidingClient = canEnterPictureInPicture && !isState(STARTED, STOPPING, STOPPED, PAUSED); - if (!mTransitionController.isShellTransitionsEnabled() - && deferHidingClient && pictureInPictureArgs.isAutoEnterEnabled()) { - // Go ahead and just put the activity in pip if it supports auto-pip. - mAtmService.enterPictureInPictureMode(this, pictureInPictureArgs); - return; - } setDeferHidingClient(deferHidingClient); setVisibility(false); diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java index 7d2dfa071597..77ec67f31d50 100644 --- a/services/core/java/com/android/server/wm/ActivityStarter.java +++ b/services/core/java/com/android/server/wm/ActivityStarter.java @@ -2730,10 +2730,11 @@ class ActivityStarter { false /* includingParents */); intentTask = intentTask.getParent().asTaskFragment().getTask(); } - // If the task is in multi-windowing mode, the activity may already be on + // If the activity is visible in multi-windowing mode, it may already be on // the top (visible to user but not the global top), then the result code // should be START_DELIVERED_TO_TOP instead of START_TASK_TO_FRONT. final boolean wasTopOfVisibleRootTask = intentActivity.mVisibleRequested + && intentActivity.inMultiWindowMode() && intentActivity == mTargetRootTask.topRunningActivity(); // We only want to move to the front, if we aren't going to launch on a // different root task. If we launch on a different root task, we will put the diff --git a/services/core/java/com/android/server/wm/ContentRecorder.java b/services/core/java/com/android/server/wm/ContentRecorder.java index 07a0c372778b..87523f44d4b6 100644 --- a/services/core/java/com/android/server/wm/ContentRecorder.java +++ b/services/core/java/com/android/server/wm/ContentRecorder.java @@ -17,6 +17,7 @@ package com.android.server.wm; import static android.view.ContentRecordingSession.RECORD_CONTENT_DISPLAY; +import static android.view.ContentRecordingSession.RECORD_CONTENT_TASK; import static com.android.internal.protolog.ProtoLogGroup.WM_DEBUG_CONTENT_RECORDING; @@ -26,6 +27,7 @@ import android.content.res.Configuration; import android.graphics.Point; import android.graphics.Rect; import android.os.IBinder; +import android.provider.DeviceConfig; import android.view.ContentRecordingSession; import android.view.Display; import android.view.SurfaceControl; @@ -39,6 +41,11 @@ import com.android.internal.protolog.common.ProtoLog; final class ContentRecorder { /** + * The key for accessing the device config that controls if task recording is supported. + */ + @VisibleForTesting static final String KEY_RECORD_TASK_FEATURE = "record_task_content"; + + /** * The display content this class is handling recording for. */ @NonNull @@ -48,7 +55,7 @@ final class ContentRecorder { * The session for content recording, or null if this DisplayContent is not being used for * recording. */ - @VisibleForTesting private ContentRecordingSession mContentRecordingSession = null; + private ContentRecordingSession mContentRecordingSession = null; /** * The WindowContainer for the level of the hierarchy to record. @@ -187,6 +194,8 @@ final class ContentRecorder { mDisplayContent.mWmService.mTransactionFactory.get().remove(mRecordedSurface).apply(); mRecordedSurface = null; clearContentRecordingSession(); + // Do not need to force remove the VirtualDisplay; this is handled by the media + // projection service. } } @@ -215,46 +224,12 @@ final class ContentRecorder { return; } - final int contentToRecord = mContentRecordingSession.getContentToRecord(); - if (contentToRecord != RECORD_CONTENT_DISPLAY) { - // TODO(b/216625226) handle task-based recording - // Not a valid region, or recording is disabled, so fall back to prior MediaProjection - // approach. - clearContentRecordingSession(); - ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, - "Unable to start recording due to invalid region for display %d", - mDisplayContent.getDisplayId()); - return; - } - // Given the WindowToken of the DisplayArea to record, retrieve the associated - // SurfaceControl. - IBinder tokenToRecord = mContentRecordingSession.getTokenToRecord(); - if (tokenToRecord == null) { - // Unexpectedly missing token. Fall back to prior MediaProjection approach. - clearContentRecordingSession(); - ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, - "Unable to start recording due to null token for display %d", - mDisplayContent.getDisplayId()); - return; - } - - final WindowContainer wc = - mDisplayContent.mWmService.mWindowContextListenerController.getContainer( - tokenToRecord); - if (wc == null) { - // Un-set the window token to record for this VirtualDisplay. Fall back to the - // original MediaProjection approach. - mDisplayContent.mWmService.mDisplayManagerInternal.setWindowManagerMirroring( - mDisplayContent.getDisplayId(), false); - clearContentRecordingSession(); - ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, - "Unable to retrieve window container to start recording for " - + "display %d", - mDisplayContent.getDisplayId()); + mRecordedWindowContainer = retrieveRecordedWindowContainer(); + if (mRecordedWindowContainer == null) { + // Either the token is missing, or the window associated with the token is missing. + // Error has already been handled, so just leave. return; } - // TODO(206461622) Migrate to using the RootDisplayArea - mRecordedWindowContainer = wc.getDisplayContent(); final Point surfaceSize = fetchSurfaceSizeIfPresent(); if (surfaceSize == null) { @@ -296,6 +271,107 @@ final class ContentRecorder { } /** + * Retrieves the {@link WindowContainer} for the level of the hierarchy to start recording, + * indicated by the {@link #mContentRecordingSession}. Performs any error handling and state + * updates necessary if the {@link WindowContainer} could not be retrieved. + * {@link #mContentRecordingSession} must be non-null. + * + * @return a {@link WindowContainer} to record, or {@code null} if an error was encountered. The + * error is logged and any cleanup is handled. + */ + @Nullable + private WindowContainer retrieveRecordedWindowContainer() { + final int contentToRecord = mContentRecordingSession.getContentToRecord(); + // Given the WindowToken of the region to record, retrieve the associated + // SurfaceControl. + final IBinder tokenToRecord = mContentRecordingSession.getTokenToRecord(); + if (tokenToRecord == null) { + handleStartRecordingFailed(); + ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, + "Unable to start recording due to null token for display %d", + mDisplayContent.getDisplayId()); + return null; + } + switch (contentToRecord) { + case RECORD_CONTENT_DISPLAY: + final WindowContainer wc = + mDisplayContent.mWmService.mWindowContextListenerController.getContainer( + tokenToRecord); + if (wc == null) { + // Un-set the window token to record for this VirtualDisplay. Fall back to + // Display stack capture for the entire display. + mDisplayContent.mWmService.mDisplayManagerInternal.setWindowManagerMirroring( + mDisplayContent.getDisplayId(), false); + handleStartRecordingFailed(); + ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, + "Unable to retrieve window container to start recording for " + + "display %d", mDisplayContent.getDisplayId()); + return null; + } + // TODO(206461622) Migrate to using the RootDisplayArea + return wc.getDisplayContent(); + case RECORD_CONTENT_TASK: + if (!DeviceConfig.getBoolean(DeviceConfig.NAMESPACE_WINDOW_MANAGER, + KEY_RECORD_TASK_FEATURE, false)) { + handleStartRecordingFailed(); + ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, + "Unable to record task since feature is disabled %d", + mDisplayContent.getDisplayId()); + return null; + } + Task taskToRecord = WindowContainer.fromBinder(tokenToRecord).asTask(); + if (taskToRecord == null) { + handleStartRecordingFailed(); + ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, + "Unable to retrieve task to start recording for " + + "display %d", mDisplayContent.getDisplayId()); + } + return taskToRecord; + default: + // Not a valid region, or recording is disabled, so fall back to Display stack + // capture for the entire display. + handleStartRecordingFailed(); + ProtoLog.v(WM_DEBUG_CONTENT_RECORDING, + "Unable to start recording due to invalid region for display %d", + mDisplayContent.getDisplayId()); + return null; + } + } + + /** + * Exit this recording session. + * <p> + * If this is a task session, tear down the recording entirely. Do not fall back + * to recording the entire display on the display stack; this would surprise the user + * given they selected task capture. + * </p><p> + * If this is a display session, just stop recording by layer mirroring. Fall back to recording + * from the display stack. + * </p> + */ + private void handleStartRecordingFailed() { + final boolean shouldExitTaskRecording = mContentRecordingSession != null + && mContentRecordingSession.getContentToRecord() == RECORD_CONTENT_TASK; + if (shouldExitTaskRecording) { + // Clean up the cached session first, since tearing down the display will generate + // display + // events which will trickle back to here. + clearContentRecordingSession(); + tearDownVirtualDisplay(); + } else { + clearContentRecordingSession(); + } + } + + /** + * Ensure recording does not fall back to the display stack; ensure the recording is stopped + * and the client notified by tearing down the virtual display. + */ + private void tearDownVirtualDisplay() { + // TODO(b/219761722) Clean up the VirtualDisplay if task mirroring fails + } + + /** * Apply transformations to the mirrored surface to ensure the captured contents are scaled to * fit and centred in the output surface. * diff --git a/services/core/java/com/android/server/wm/TaskFragment.java b/services/core/java/com/android/server/wm/TaskFragment.java index d187bd6f3dfd..2ac41a7c1c1d 100644 --- a/services/core/java/com/android/server/wm/TaskFragment.java +++ b/services/core/java/com/android/server/wm/TaskFragment.java @@ -1459,7 +1459,8 @@ class TaskFragment extends WindowContainer<WindowContainer> { // next activity. final boolean lastResumedCanPip = prev.checkEnterPictureInPictureState( "shouldAutoPipWhilePausing", userLeaving); - if (lastResumedCanPip && prev.pictureInPictureArgs.isAutoEnterEnabled()) { + if (userLeaving && lastResumedCanPip + && prev.pictureInPictureArgs.isAutoEnterEnabled()) { shouldAutoPip = true; } else if (!lastResumedCanPip) { // If the flag RESUME_WHILE_PAUSING is set, then continue to schedule the previous diff --git a/services/core/java/com/android/server/wm/WindowManagerService.java b/services/core/java/com/android/server/wm/WindowManagerService.java index c50888b5a172..eb88b8b0ea97 100644 --- a/services/core/java/com/android/server/wm/WindowManagerService.java +++ b/services/core/java/com/android/server/wm/WindowManagerService.java @@ -3278,7 +3278,7 @@ public class WindowManagerService extends IWindowManager.Stub mContext.enforceCallingOrSelfPermission( Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE, Manifest.permission.SUBSCRIBE_TO_KEYGUARD_LOCKED_STATE - + " permission required to read keyguard visibility"); + + " permission required to subscribe to keyguard locked state changes"); } private void dispatchKeyguardLockedState() { diff --git a/services/core/jni/gnss/MeasurementCorrections.cpp b/services/core/jni/gnss/MeasurementCorrections.cpp index 8a3d84cbe9c6..07d0a45e9c40 100644 --- a/services/core/jni/gnss/MeasurementCorrections.cpp +++ b/services/core/jni/gnss/MeasurementCorrections.cpp @@ -44,6 +44,7 @@ using SingleSatCorrection_Aidl = using ReflectingPlane_V1_0 = android::hardware::gnss::measurement_corrections::V1_0::ReflectingPlane; using ReflectingPlane_Aidl = android::hardware::gnss::measurement_corrections::ReflectingPlane; +using ExcessPathInfo = SingleSatCorrection_Aidl::ExcessPathInfo; using GnssConstellationType_V1_0 = android::hardware::gnss::V1_0::GnssConstellationType; using GnssConstellationType_V2_0 = android::hardware::gnss::V2_0::GnssConstellationType; using GnssConstellationType_Aidl = android::hardware::gnss::GnssConstellationType; @@ -62,7 +63,7 @@ jmethodID method_correctionsHasEnvironmentBearing; jmethodID method_correctionsGetEnvironmentBearingDegrees; jmethodID method_correctionsGetEnvironmentBearingUncertaintyDegrees; jmethodID method_listSize; -jmethodID method_correctionListGet; +jmethodID method_listGet; jmethodID method_correctionSatFlags; jmethodID method_correctionSatConstType; jmethodID method_correctionSatId; @@ -71,10 +72,17 @@ jmethodID method_correctionSatIsLosProb; jmethodID method_correctionSatEpl; jmethodID method_correctionSatEplUnc; jmethodID method_correctionSatRefPlane; +jmethodID method_correctionSatAttenuation; +jmethodID method_correctionSatExcessPathInfoList; jmethodID method_correctionPlaneLatDeg; jmethodID method_correctionPlaneLngDeg; jmethodID method_correctionPlaneAltDeg; jmethodID method_correctionPlaneAzimDeg; +jmethodID method_excessPathInfoFlags; +jmethodID method_excessPathInfoEpl; +jmethodID method_excessPathInfoEplUnc; +jmethodID method_excessPathInfoRefPlane; +jmethodID method_excessPathInfoAttenuation; } // anonymous namespace void MeasurementCorrections_class_init_once(JNIEnv* env, jclass clazz) { @@ -103,7 +111,7 @@ void MeasurementCorrections_class_init_once(JNIEnv* env, jclass clazz) { jclass corrListClass = env->FindClass("java/util/List"); method_listSize = env->GetMethodID(corrListClass, "size", "()I"); - method_correctionListGet = env->GetMethodID(corrListClass, "get", "(I)Ljava/lang/Object;"); + method_listGet = env->GetMethodID(corrListClass, "get", "(I)Ljava/lang/Object;"); jclass singleSatCorrClass = env->FindClass("android/location/GnssSingleSatCorrection"); method_correctionSatFlags = @@ -121,12 +129,27 @@ void MeasurementCorrections_class_init_once(JNIEnv* env, jclass clazz) { env->GetMethodID(singleSatCorrClass, "getExcessPathLengthUncertaintyMeters", "()F"); method_correctionSatRefPlane = env->GetMethodID(singleSatCorrClass, "getReflectingPlane", "()Landroid/location/GnssReflectingPlane;"); + method_correctionSatAttenuation = + env->GetMethodID(singleSatCorrClass, "getCombinedAttenuationDb", "()F"); + method_correctionSatExcessPathInfoList = + env->GetMethodID(singleSatCorrClass, "getGnssExcessPathInfoList", "()Ljava/util/List;"); jclass refPlaneClass = env->FindClass("android/location/GnssReflectingPlane"); method_correctionPlaneLatDeg = env->GetMethodID(refPlaneClass, "getLatitudeDegrees", "()D"); method_correctionPlaneLngDeg = env->GetMethodID(refPlaneClass, "getLongitudeDegrees", "()D"); method_correctionPlaneAltDeg = env->GetMethodID(refPlaneClass, "getAltitudeMeters", "()D"); method_correctionPlaneAzimDeg = env->GetMethodID(refPlaneClass, "getAzimuthDegrees", "()D"); + + jclass excessPathInfoClass = env->FindClass("android/location/GnssExcessPathInfo"); + method_excessPathInfoFlags = env->GetMethodID(excessPathInfoClass, "getFlags", "()I"); + method_excessPathInfoEpl = + env->GetMethodID(excessPathInfoClass, "getExcessPathLengthMeters", "()F"); + method_excessPathInfoEplUnc = + env->GetMethodID(excessPathInfoClass, "getExcessPathLengthUncertaintyMeters", "()F"); + method_excessPathInfoRefPlane = env->GetMethodID(excessPathInfoClass, "getReflectingPlane", + "()Landroid/location/GnssReflectingPlane;"); + method_excessPathInfoAttenuation = + env->GetMethodID(excessPathInfoClass, "getAttenuationDb", "()F"); } template <> @@ -324,7 +347,8 @@ jboolean MeasurementCorrectionsIface_V1_1::setCallback( SingleSatCorrection_V1_0 MeasurementCorrectionsUtil::getSingleSatCorrection_1_0_withoutConstellation( JNIEnv* env, jobject singleSatCorrectionObj) { - jint correctionFlags = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatFlags); + uint16_t corrFlags = static_cast<uint16_t>( + env->CallIntMethod(singleSatCorrectionObj, method_correctionSatFlags)); jint satId = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatId); jfloat carrierFreqHz = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatCarrierFreq); @@ -332,14 +356,16 @@ MeasurementCorrectionsUtil::getSingleSatCorrection_1_0_withoutConstellation( env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatIsLosProb); jfloat eplMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEpl); jfloat eplUncMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEplUnc); - uint16_t corrFlags = static_cast<uint16_t>(correctionFlags); ReflectingPlane_V1_0 reflectingPlane; - if ((corrFlags & GnssSingleSatCorrectionFlags_V1_0::HAS_REFLECTING_PLANE) != 0) - MeasurementCorrectionsUtil::getReflectingPlane<ReflectingPlane_V1_0>(env, - singleSatCorrectionObj, + if ((corrFlags & GnssSingleSatCorrectionFlags_V1_0::HAS_REFLECTING_PLANE) != 0) { + jobject reflectingPlaneObj = + env->CallObjectMethod(singleSatCorrectionObj, method_correctionSatRefPlane); + MeasurementCorrectionsUtil::setReflectingPlane<ReflectingPlane_V1_0>(env, + reflectingPlaneObj, reflectingPlane); - + env->DeleteLocalRef(reflectingPlaneObj); + } SingleSatCorrection_V1_0 singleSatCorrection = { .singleSatCorrectionFlags = corrFlags, .svid = static_cast<uint16_t>(satId), @@ -349,13 +375,14 @@ MeasurementCorrectionsUtil::getSingleSatCorrection_1_0_withoutConstellation( .excessPathLengthUncertaintyMeters = eplUncMeters, .reflectingPlane = reflectingPlane, }; - return singleSatCorrection; } SingleSatCorrection_Aidl MeasurementCorrectionsUtil::getSingleSatCorrection_Aidl( JNIEnv* env, jobject singleSatCorrectionObj) { - jint correctionFlags = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatFlags); + int32_t corrFlags = static_cast<int32_t>( + env->CallIntMethod(singleSatCorrectionObj, method_correctionSatFlags)); + jint constType = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatConstType); jint satId = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatId); jfloat carrierFreqHz = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatCarrierFreq); @@ -363,15 +390,10 @@ SingleSatCorrection_Aidl MeasurementCorrectionsUtil::getSingleSatCorrection_Aidl env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatIsLosProb); jfloat eplMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEpl); jfloat eplUncMeters = env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatEplUnc); - int32_t corrFlags = static_cast<int32_t>(correctionFlags); - - ReflectingPlane_Aidl reflectingPlane; - if ((corrFlags & SingleSatCorrection_Aidl::SINGLE_SAT_CORRECTION_HAS_REFLECTING_PLANE) != 0) - MeasurementCorrectionsUtil::getReflectingPlane<ReflectingPlane_Aidl>(env, - singleSatCorrectionObj, - reflectingPlane); - - jint constType = env->CallIntMethod(singleSatCorrectionObj, method_correctionSatConstType); + jfloat attenuationDb = + env->CallFloatMethod(singleSatCorrectionObj, method_correctionSatAttenuation); + std::vector<ExcessPathInfo> excessPathInfos = + MeasurementCorrectionsUtil::getExcessPathInfoList(env, singleSatCorrectionObj); SingleSatCorrection_Aidl singleSatCorrection; singleSatCorrection.singleSatCorrectionFlags = corrFlags; @@ -379,9 +401,10 @@ SingleSatCorrection_Aidl MeasurementCorrectionsUtil::getSingleSatCorrection_Aidl singleSatCorrection.svid = static_cast<int32_t>(satId); singleSatCorrection.carrierFrequencyHz = carrierFreqHz; singleSatCorrection.probSatIsLos = probSatIsLos; - singleSatCorrection.excessPathLengthMeters = eplMeters; - singleSatCorrection.excessPathLengthUncertaintyMeters = eplUncMeters; - singleSatCorrection.reflectingPlane = reflectingPlane; + singleSatCorrection.combinedExcessPathLengthMeters = eplMeters; + singleSatCorrection.combinedExcessPathLengthUncertaintyMeters = eplUncMeters; + singleSatCorrection.combinedAttenuationDb = attenuationDb; + singleSatCorrection.excessPathInfos = excessPathInfos; return singleSatCorrection; } @@ -391,8 +414,7 @@ void MeasurementCorrectionsUtil::getSingleSatCorrectionList_1_0( hardware::hidl_vec<SingleSatCorrection_V1_0>& list) { for (uint16_t i = 0; i < list.size(); ++i) { jobject singleSatCorrectionObj = - env->CallObjectMethod(singleSatCorrectionList, method_correctionListGet, i); - + env->CallObjectMethod(singleSatCorrectionList, method_listGet, i); SingleSatCorrection_V1_0 singleSatCorrection = getSingleSatCorrection_1_0_withoutConstellation(env, singleSatCorrectionObj); @@ -410,7 +432,7 @@ void MeasurementCorrectionsUtil::getSingleSatCorrectionList_1_1( hardware::hidl_vec<SingleSatCorrection_V1_1>& list) { for (uint16_t i = 0; i < list.size(); ++i) { jobject singleSatCorrectionObj = - env->CallObjectMethod(singleSatCorrectionList, method_correctionListGet, i); + env->CallObjectMethod(singleSatCorrectionList, method_listGet, i); SingleSatCorrection_V1_0 singleSatCorrection_1_0 = getSingleSatCorrection_1_0_withoutConstellation(env, singleSatCorrectionObj); @@ -431,7 +453,7 @@ void MeasurementCorrectionsUtil::getSingleSatCorrectionList_Aidl( JNIEnv* env, jobject singleSatCorrectionList, std::vector<SingleSatCorrection_Aidl>& list) { for (uint16_t i = 0; i < list.size(); ++i) { jobject singleSatCorrectionObj = - env->CallObjectMethod(singleSatCorrectionList, method_correctionListGet, i); + env->CallObjectMethod(singleSatCorrectionList, method_listGet, i); SingleSatCorrection_Aidl singleSatCorrection_Aidl = getSingleSatCorrection_Aidl(env, singleSatCorrectionObj); @@ -441,4 +463,63 @@ void MeasurementCorrectionsUtil::getSingleSatCorrectionList_Aidl( } } +template <> +void MeasurementCorrectionsUtil::setReflectingPlaneAzimuthDegrees<ReflectingPlane_V1_0>( + ReflectingPlane_V1_0& reflectingPlane, double azimuthDegreeRefPlane) { + reflectingPlane.azimuthDegrees = azimuthDegreeRefPlane; +} + +template <> +void MeasurementCorrectionsUtil::setReflectingPlaneAzimuthDegrees<ReflectingPlane_Aidl>( + ReflectingPlane_Aidl& reflectingPlane, double azimuthDegreeRefPlane) { + reflectingPlane.reflectingPlaneAzimuthDegrees = azimuthDegreeRefPlane; +} + +std::vector<ExcessPathInfo> MeasurementCorrectionsUtil::getExcessPathInfoList( + JNIEnv* env, jobject singleSatCorrectionObj) { + jobject excessPathInfoListObj = + env->CallObjectMethod(singleSatCorrectionObj, method_correctionSatExcessPathInfoList); + + int len = env->CallIntMethod(excessPathInfoListObj, method_listSize); + std::vector<ExcessPathInfo> list(len); + for (int i = 0; i < len; ++i) { + jobject excessPathInfoObj = env->CallObjectMethod(excessPathInfoListObj, method_listGet, i); + list[i] = getExcessPathInfo(env, excessPathInfoObj); + env->DeleteLocalRef(excessPathInfoObj); + } + env->DeleteLocalRef(excessPathInfoListObj); + return list; +} + +ExcessPathInfo MeasurementCorrectionsUtil::getExcessPathInfo(JNIEnv* env, + jobject excessPathInfoObj) { + ExcessPathInfo excessPathInfo; + jint flags = env->CallIntMethod(excessPathInfoObj, method_excessPathInfoFlags); + excessPathInfo.excessPathInfoFlags = flags; + if ((flags & ExcessPathInfo::EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH) != 0) { + jfloat epl = env->CallFloatMethod(excessPathInfoObj, method_excessPathInfoEpl); + excessPathInfo.excessPathLengthMeters = epl; + } + if ((flags & ExcessPathInfo::EXCESS_PATH_INFO_HAS_EXCESS_PATH_LENGTH_UNC) != 0) { + jfloat eplUnc = env->CallFloatMethod(excessPathInfoObj, method_excessPathInfoEplUnc); + excessPathInfo.excessPathLengthUncertaintyMeters = eplUnc; + } + if ((flags & ExcessPathInfo::EXCESS_PATH_INFO_HAS_REFLECTING_PLANE) != 0) { + ReflectingPlane_Aidl reflectingPlane; + jobject reflectingPlaneObj = + env->CallObjectMethod(excessPathInfoObj, method_excessPathInfoRefPlane); + MeasurementCorrectionsUtil::setReflectingPlane<ReflectingPlane_Aidl>(env, + reflectingPlaneObj, + reflectingPlane); + env->DeleteLocalRef(reflectingPlaneObj); + excessPathInfo.reflectingPlane = reflectingPlane; + } + if ((flags & ExcessPathInfo::EXCESS_PATH_INFO_HAS_ATTENUATION) != 0) { + jfloat attenuation = + env->CallFloatMethod(excessPathInfoObj, method_excessPathInfoAttenuation); + excessPathInfo.attenuationDb = attenuation; + } + return excessPathInfo; +} + } // namespace android::gnss diff --git a/services/core/jni/gnss/MeasurementCorrections.h b/services/core/jni/gnss/MeasurementCorrections.h index a2e602714326..598ad48d6ac1 100644 --- a/services/core/jni/gnss/MeasurementCorrections.h +++ b/services/core/jni/gnss/MeasurementCorrections.h @@ -43,7 +43,7 @@ extern jmethodID method_correctionsHasEnvironmentBearing; extern jmethodID method_correctionsGetEnvironmentBearingDegrees; extern jmethodID method_correctionsGetEnvironmentBearingUncertaintyDegrees; extern jmethodID method_listSize; -extern jmethodID method_correctionListGet; +extern jmethodID method_listGet; extern jmethodID method_correctionSatFlags; extern jmethodID method_correctionSatConstType; extern jmethodID method_correctionSatId; @@ -52,6 +52,7 @@ extern jmethodID method_correctionSatIsLosProb; extern jmethodID method_correctionSatEpl; extern jmethodID method_correctionSatEplUnc; extern jmethodID method_correctionSatRefPlane; +extern jmethodID method_correctionSatExcessPathInfos; extern jmethodID method_correctionPlaneLatDeg; extern jmethodID method_correctionPlaneLngDeg; extern jmethodID method_correctionPlaneAltDeg; @@ -130,14 +131,20 @@ struct MeasurementCorrectionsUtil { static bool translateMeasurementCorrections(JNIEnv* env, jobject correctionsObj, T& corrections); template <class T> - static void getReflectingPlane(JNIEnv* env, jobject singleSatCorrectionObj, T& reflectingPlane); + static void setReflectingPlane(JNIEnv* env, jobject reflectingPlaneObj, T& reflectingPlane); + template <class T> + static void setReflectingPlaneAzimuthDegrees(T& reflectingPlane, double azimuthDegreeRefPlane); + + static std::vector< + android::hardware::gnss::measurement_corrections::SingleSatCorrection::ExcessPathInfo> + getExcessPathInfoList(JNIEnv* env, jobject correctionsObj); + static android::hardware::gnss::measurement_corrections::SingleSatCorrection::ExcessPathInfo + getExcessPathInfo(JNIEnv* env, jobject correctionsObj); }; template <class T> -void MeasurementCorrectionsUtil::getReflectingPlane(JNIEnv* env, jobject singleSatCorrectionObj, +void MeasurementCorrectionsUtil::setReflectingPlane(JNIEnv* env, jobject reflectingPlaneObj, T& reflectingPlane) { - jobject reflectingPlaneObj = - env->CallObjectMethod(singleSatCorrectionObj, method_correctionSatRefPlane); jdouble latitudeDegreesRefPlane = env->CallDoubleMethod(reflectingPlaneObj, method_correctionPlaneLatDeg); jdouble longitudeDegreesRefPlane = @@ -149,8 +156,7 @@ void MeasurementCorrectionsUtil::getReflectingPlane(JNIEnv* env, jobject singleS reflectingPlane.latitudeDegrees = latitudeDegreesRefPlane; reflectingPlane.longitudeDegrees = longitudeDegreesRefPlane; reflectingPlane.altitudeMeters = altitudeDegreesRefPlane; - reflectingPlane.azimuthDegrees = azimuthDegreeRefPlane; - env->DeleteLocalRef(reflectingPlaneObj); + setReflectingPlaneAzimuthDegrees<T>(reflectingPlane, azimuthDegreeRefPlane); } } // namespace android::gnss diff --git a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java index 2f5ab0b31332..48c40523e9c2 100644 --- a/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java +++ b/services/devicepolicy/java/com/android/server/devicepolicy/ActiveAdmin.java @@ -1227,5 +1227,12 @@ class ActiveAdmin { pw.print("mSsidDenylist="); pw.println(mSsidDenylist); + + if (mFactoryResetProtectionPolicy != null) { + pw.println("mFactoryResetProtectionPolicy:"); + pw.increaseIndent(); + mFactoryResetProtectionPolicy.dump(pw); + pw.decreaseIndent(); + } } } diff --git a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt index 8f81e930d0cd..7a9c41256d61 100644 --- a/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt +++ b/services/tests/PackageManagerServiceTests/unit/src/com/android/server/pm/test/parsing/parcelling/AndroidPackageTest.kt @@ -143,6 +143,7 @@ class AndroidPackageTest : ParcelableComponentTest(AndroidPackage::class, Packag AndroidPackage::getLogo, AndroidPackage::getLocaleConfigRes, AndroidPackage::getManageSpaceActivityName, + AndroidPackage::getMaxSdkVersion, AndroidPackage::getMemtagMode, AndroidPackage::getMinSdkVersion, AndroidPackage::getNativeHeapZeroInitialized, diff --git a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java index 784f732ba3b1..8d6269c93764 100644 --- a/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/display/LocalDisplayAdapterTest.java @@ -118,6 +118,7 @@ public class LocalDisplayAdapterTest { LocalServices.removeServiceForTest(LightsManager.class); LocalServices.addService(LightsManager.class, mMockedLightsManager); mInjector = new Injector(); + when(mSurfaceControlProxy.getBootDisplayModeSupport()).thenReturn(true); mAdapter = new LocalDisplayAdapter(mMockedSyncRoot, mMockedContext, mHandler, mListener, mInjector); spyOn(mAdapter); @@ -904,7 +905,6 @@ public class LocalDisplayAdapterTest { .thenReturn(display.dynamicInfo); when(mSurfaceControlProxy.getDesiredDisplayModeSpecs(display.token)) .thenReturn(display.desiredDisplayModeSpecs); - when(mSurfaceControlProxy.getBootDisplayModeSupport()).thenReturn(true); } private void updateAvailableDisplays() { diff --git a/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java b/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java index 6f503c7dd941..444db9128662 100644 --- a/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/pm/BackgroundDexOptServiceUnitTest.java @@ -19,7 +19,9 @@ package com.android.server.pm; import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.atLeastOnce; +import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.times; @@ -36,23 +38,21 @@ import android.content.Intent; import android.content.IntentFilter; import android.os.HandlerThread; import android.os.PowerManager; -import android.util.ArraySet; import com.android.server.LocalServices; import com.android.server.PinnerService; import com.android.server.pm.dex.DexManager; -import com.android.server.pm.dex.DexoptOptions; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.Arrays; -import java.util.HashMap; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.stream.Collectors; @@ -66,9 +66,8 @@ public final class BackgroundDexOptServiceUnitTest { private static final long TEST_WAIT_TIMEOUT_MS = 10_000; - private static final ArraySet<String> DEFAULT_PACKAGE_LIST = new ArraySet<>( - Arrays.asList("aaa", "bbb")); - private static final ArraySet<String> EMPTY_PACKAGE_LIST = new ArraySet<>(); + private static final List<String> DEFAULT_PACKAGE_LIST = List.of("aaa", "bbb"); + private static final List<String> EMPTY_PACKAGE_LIST = List.of(); @Mock private Context mContext; @@ -116,9 +115,11 @@ public final class BackgroundDexOptServiceUnitTest { when(mInjector.getDataDirStorageLowBytes()).thenReturn(STORAGE_LOW_BYTES); when(mInjector.getDexOptThermalCutoff()).thenReturn(PowerManager.THERMAL_STATUS_CRITICAL); when(mInjector.getCurrentThermalStatus()).thenReturn(PowerManager.THERMAL_STATUS_NONE); + when(mInjector.supportSecondaryDex()).thenReturn(true); when(mDexOptHelper.getOptimizablePackages(any())).thenReturn(DEFAULT_PACKAGE_LIST); when(mDexOptHelper.performDexOptWithStatus(any())).thenReturn( PackageDexOptimizer.DEX_OPT_PERFORMED); + when(mDexOptHelper.performDexOpt(any())).thenReturn(true); mService = new BackgroundDexOptService(mInjector); } @@ -418,26 +419,16 @@ public final class BackgroundDexOptServiceUnitTest { verifyPerformDexOpt(DEFAULT_PACKAGE_LIST, totalJobRuns); } - private void verifyPerformDexOpt(ArraySet<String> pkgs, int expectedRuns) { - ArgumentCaptor<DexoptOptions> dexOptOptions = ArgumentCaptor.forClass(DexoptOptions.class); - verify(mDexOptHelper, atLeastOnce()).performDexOptWithStatus(dexOptOptions.capture()); - HashMap<String, Integer> primaryPkgs = new HashMap<>(); // K: pkg, V: dexopt runs left - for (String pkg : pkgs) { - primaryPkgs.put(pkg, expectedRuns); - } - - for (DexoptOptions opt : dexOptOptions.getAllValues()) { - assertThat(pkgs).contains(opt.getPackageName()); - assertThat(opt.isDexoptOnlySecondaryDex()).isFalse(); - Integer count = primaryPkgs.get(opt.getPackageName()); - assertThat(count).isNotNull(); - if (count == 1) { - primaryPkgs.remove(opt.getPackageName()); - } else { - primaryPkgs.put(opt.getPackageName(), count - 1); + private void verifyPerformDexOpt(List<String> pkgs, int expectedRuns) { + InOrder inOrder = inOrder(mDexOptHelper); + for (int i = 0; i < expectedRuns; i++) { + for (String pkg : pkgs) { + inOrder.verify(mDexOptHelper, times(1)).performDexOptWithStatus(argThat((option) -> + option.getPackageName().equals(pkg) && !option.isDexoptOnlySecondaryDex())); + inOrder.verify(mDexOptHelper, times(1)).performDexOpt(argThat((option) -> + option.getPackageName().equals(pkg) && option.isDexoptOnlySecondaryDex())); } } - assertThat(primaryPkgs).isEmpty(); } private static class StartAndWaitThread extends Thread { diff --git a/services/tests/mockingservicestests/src/com/android/server/utils/TimingsTraceAndSlogTest.java b/services/tests/mockingservicestests/src/com/android/server/utils/TimingsTraceAndSlogTest.java new file mode 100644 index 000000000000..52cd29cabb94 --- /dev/null +++ b/services/tests/mockingservicestests/src/com/android/server/utils/TimingsTraceAndSlogTest.java @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.android.server.utils; + +import static android.os.Trace.TRACE_TAG_APP; + +import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; + +import static com.google.common.truth.Truth.assertThat; + +import static org.mockito.Matchers.anyString; +import static org.mockito.Matchers.contains; +import static org.mockito.Matchers.eq; +import static org.mockito.Matchers.matches; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; + +import android.os.Trace; +import android.util.Slog; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import com.android.dx.mockito.inline.extended.MockedVoidMethod; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.MockitoSession; + +import java.util.ArrayList; +import java.util.List; + +/** + * Tests for {@link TimingsTraceAndSlog}. + * + * <p>Usage: {@code atest FrameworksMockingServicesTests:TimingsTraceAndSlogTest} + */ +@SmallTest +@RunWith(AndroidJUnit4.class) +public class TimingsTraceAndSlogTest { + + private static final String TAG = "TEST"; + + private MockitoSession mSession; + + @Before + public final void startMockSession() { + mSession = mockitoSession() + .spyStatic(Slog.class) + .spyStatic(Trace.class) + .startMocking(); + } + + @After + public final void finishMockSession() { + mSession.finishMocking(); + } + + @Test + public void testDifferentThreads() throws Exception { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + // Should be able to log on the same thread + log.traceBegin("test"); + log.traceEnd(); + final List<String> errors = new ArrayList<>(); + // Calling from a different thread should fail + Thread t = new Thread(() -> { + try { + log.traceBegin("test"); + errors.add("traceBegin should fail on a different thread"); + } catch (IllegalStateException expected) { + } + try { + log.traceEnd(); + errors.add("traceEnd should fail on a different thread"); + } catch (IllegalStateException expected) { + } + // Verify that creating a new log will work + TimingsTraceAndSlog log2 = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + log2.traceBegin("test"); + log2.traceEnd(); + + }); + t.start(); + t.join(); + assertThat(errors).isEmpty(); + } + + @Test + public void testGetUnfinishedTracesForDebug() { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + assertThat(log.getUnfinishedTracesForDebug()).isEmpty(); + + log.traceBegin("One"); + assertThat(log.getUnfinishedTracesForDebug()).containsExactly("One").inOrder(); + + log.traceBegin("Two"); + assertThat(log.getUnfinishedTracesForDebug()).containsExactly("One", "Two").inOrder(); + + log.traceEnd(); + assertThat(log.getUnfinishedTracesForDebug()).containsExactly("One").inOrder(); + + log.traceEnd(); + assertThat(log.getUnfinishedTracesForDebug()).isEmpty(); + } + + @Test + public void testLogDuration() throws Exception { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + log.logDuration("logro", 42); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), contains("logro took to complete: 42ms"))); + } + + @Test + public void testOneLevel() throws Exception { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + log.traceBegin("test"); + log.traceEnd(); + + verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "test")); + verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP)); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("test took to complete: \\dms"))); + } + + @Test + public void testMultipleLevels() throws Exception { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + log.traceBegin("L1"); + log.traceBegin("L2"); + log.traceEnd(); + log.traceEnd(); + + verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "L1")); + verify((MockedVoidMethod) () -> Trace.traceBegin(TRACE_TAG_APP, "L2")); + verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP), times(2)); // L1 and L2 + + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L2 took to complete: \\d+ms"))); + verify((MockedVoidMethod) () -> Slog.v(eq(TAG), matches("L1 took to complete: \\d+ms"))); + } + + @Test + public void testEndNoBegin() throws Exception { + TimingsTraceAndSlog log = new TimingsTraceAndSlog(TAG, TRACE_TAG_APP); + log.traceEnd(); + verify((MockedVoidMethod) () -> Trace.traceEnd(TRACE_TAG_APP)); + verify((MockedVoidMethod) () -> Slog.d(eq(TAG), anyString()), never()); + verify((MockedVoidMethod) () -> Slog.w(TAG, "traceEnd called more times than traceBegin")); + } +} diff --git a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationControllerTest.java b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationControllerTest.java index f3a0b7fa1ea7..0780d219dc80 100644 --- a/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationControllerTest.java +++ b/services/tests/servicestests/src/com/android/server/accessibility/magnification/FullScreenMagnificationControllerTest.java @@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.reset; @@ -45,13 +46,16 @@ import android.content.IntentFilter; import android.graphics.PointF; import android.graphics.Rect; import android.graphics.Region; +import android.hardware.display.DisplayManagerInternal; import android.os.Looper; +import android.view.DisplayInfo; import android.view.MagnificationSpec; import android.view.accessibility.MagnificationAnimationCallback; import androidx.test.InstrumentationRegistry; import androidx.test.runner.AndroidJUnit4; +import com.android.server.LocalServices; import com.android.server.accessibility.AccessibilityTraceManager; import com.android.server.accessibility.test.MessageCapturingHandler; import com.android.server.wm.WindowManagerInternal; @@ -113,6 +117,8 @@ public class FullScreenMagnificationControllerTest { FullScreenMagnificationController mFullScreenMagnificationController; + public DisplayManagerInternal mDisplayManagerInternalMock = mock(DisplayManagerInternal.class); + @Before public void setUp() { Looper looper = InstrumentationRegistry.getContext().getMainLooper(); @@ -125,6 +131,12 @@ public class FullScreenMagnificationControllerTest { when(mMockControllerCtx.getAnimationDuration()).thenReturn(1000L); initMockWindowManager(); + final DisplayInfo displayInfo = new DisplayInfo(); + displayInfo.logicalDensityDpi = 300; + doReturn(displayInfo).when(mDisplayManagerInternalMock).getDisplayInfo(anyInt()); + LocalServices.removeServiceForTest(DisplayManagerInternal.class); + LocalServices.addService(DisplayManagerInternal.class, mDisplayManagerInternalMock); + mFullScreenMagnificationController = new FullScreenMagnificationController( mMockControllerCtx, new Object(), mRequestObserver, mScaleProvider); } diff --git a/services/tests/servicestests/src/com/android/server/display/ColorFadeTest.java b/services/tests/servicestests/src/com/android/server/display/ColorFadeTest.java new file mode 100644 index 000000000000..26a83a23de33 --- /dev/null +++ b/services/tests/servicestests/src/com/android/server/display/ColorFadeTest.java @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.server.display; + +import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation; + +import static org.junit.Assert.assertFalse; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import android.content.Context; +import android.hardware.display.DisplayManagerInternal; +import android.platform.test.annotations.Presubmit; + +import androidx.test.filters.SmallTest; +import androidx.test.runner.AndroidJUnit4; + +import com.android.server.LocalServices; + +import org.junit.After; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +@SmallTest +@Presubmit +@RunWith(AndroidJUnit4.class) +public class ColorFadeTest { + private static final int DISPLAY_ID = 123; + + private Context mContext; + + @Mock private DisplayManagerInternal mDisplayManagerInternalMock; + + @Before + public void setUp() { + MockitoAnnotations.initMocks(this); + addLocalServiceMock(DisplayManagerInternal.class, mDisplayManagerInternalMock); + mContext = getInstrumentation().getTargetContext(); + } + + @After + public void tearDown() { + LocalServices.removeServiceForTest(DisplayManagerInternal.class); + } + + @Test + public void testPrepareColorFadeForInvalidDisplay() { + when(mDisplayManagerInternalMock.getDisplayInfo(eq(DISPLAY_ID))).thenReturn(null); + ColorFade colorFade = new ColorFade(DISPLAY_ID); + assertFalse(colorFade.prepare(mContext, ColorFade.MODE_FADE)); + } + + private static <T> void addLocalServiceMock(Class<T> clazz, T mock) { + LocalServices.removeServiceForTest(clazz); + LocalServices.addService(clazz, mock); + } + +} diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java index f9aa4b17bc2c..9902e83c3648 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java @@ -500,6 +500,23 @@ public class ActivityStarterTests extends WindowTestsBase { return Pair.create(splitPrimaryActivity, splitSecondActivity); } + @Test + public void testMoveVisibleTaskToFront() { + final ActivityRecord activity = new TaskBuilder(mSupervisor) + .setCreateActivity(true).build().getTopMostActivity(); + final ActivityRecord translucentActivity = new TaskBuilder(mSupervisor) + .setCreateActivity(true).build().getTopMostActivity(); + assertTrue(activity.mVisibleRequested); + + final ActivityStarter starter = prepareStarter(FLAG_ACTIVITY_NEW_TASK, + false /* mockGetRootTask */); + starter.getIntent().setComponent(activity.mActivityComponent); + final int result = starter.setReason("testMoveVisibleTaskToFront").execute(); + + assertEquals(START_TASK_TO_FRONT, result); + assertEquals(1, activity.compareTo(translucentActivity)); + } + /** * Tests activity is cleaned up properly in a task mode violation. */ diff --git a/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java b/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java index 50eefa066a45..c5117bb83976 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ContentRecorderTests.java @@ -19,12 +19,12 @@ package com.android.server.wm; import static android.content.res.Configuration.ORIENTATION_PORTRAIT; import static android.hardware.display.DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR; -import static android.view.ContentRecordingSession.RECORD_CONTENT_TASK; import static com.android.dx.mockito.inline.extended.ExtendedMockito.any; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; +import static com.android.server.wm.ContentRecorder.KEY_RECORD_TASK_FEATURE; import static com.google.common.truth.Truth.assertThat; @@ -40,17 +40,22 @@ import android.hardware.display.VirtualDisplay; import android.os.Binder; import android.os.IBinder; import android.platform.test.annotations.Presubmit; +import android.provider.DeviceConfig; import android.util.DisplayMetrics; import android.view.ContentRecordingSession; import android.view.Surface; import android.view.SurfaceControl; +import androidx.annotation.NonNull; import androidx.test.filters.SmallTest; +import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; +import java.util.concurrent.CountDownLatch; + /** * Tests for the {@link ContentRecorder} class. * @@ -62,17 +67,18 @@ import org.junit.runner.RunWith; @RunWith(WindowTestRunner.class) public class ContentRecorderTests extends WindowTestsBase { private static final IBinder TEST_TOKEN = new RecordingTestToken(); - private final ContentRecordingSession mDefaultSession = + private static IBinder sTaskWindowContainerToken; + private final ContentRecordingSession mDisplaySession = ContentRecordingSession.createDisplaySession(TEST_TOKEN); + private ContentRecordingSession mTaskSession; private static Point sSurfaceSize; private ContentRecorder mContentRecorder; private SurfaceControl mRecordedSurface; + // Handle feature flag. + private ConfigListener mConfigListener; + private CountDownLatch mLatch; @Before public void setUp() { - // GIVEN MediaProjection has already initialized the WindowToken of the DisplayArea to - // mirror. - setUpDefaultTaskDisplayAreaWindowToken(); - // GIVEN SurfaceControl can successfully mirror the provided surface. sSurfaceSize = new Point( mDefaultDisplay.getDefaultTaskDisplayArea().getBounds().width(), @@ -84,12 +90,32 @@ public class ContentRecorderTests extends WindowTestsBase { sSurfaceSize.x, sSurfaceSize.y, DisplayMetrics.DENSITY_140, new Surface(), VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR); final int displayId = virtualDisplay.getDisplay().getDisplayId(); - mDefaultSession.setDisplayId(displayId); - mWm.mRoot.onDisplayAdded(displayId); - final DisplayContent mVirtualDisplayContent = mWm.mRoot.getDisplayContent(displayId); - mContentRecorder = new ContentRecorder(mVirtualDisplayContent); - spyOn(mVirtualDisplayContent); + final DisplayContent virtualDisplayContent = mWm.mRoot.getDisplayContent(displayId); + mContentRecorder = new ContentRecorder(virtualDisplayContent); + spyOn(virtualDisplayContent); + + // GIVEN MediaProjection has already initialized the WindowToken of the DisplayArea to + // record. + setUpDefaultTaskDisplayAreaWindowToken(); + mDisplaySession.setDisplayId(displayId); + + // GIVEN there is a window token associated with a task to record. + sTaskWindowContainerToken = setUpTaskWindowContainerToken(virtualDisplayContent); + mTaskSession = ContentRecordingSession.createTaskSession(sTaskWindowContainerToken); + mTaskSession.setDisplayId(displayId); + + mConfigListener = new ConfigListener(); + DeviceConfig.addOnPropertiesChangedListener(DeviceConfig.NAMESPACE_WINDOW_MANAGER, + mContext.getMainExecutor(), mConfigListener); + mLatch = new CountDownLatch(1); + DeviceConfig.setProperty(DeviceConfig.NAMESPACE_WINDOW_MANAGER, KEY_RECORD_TASK_FEATURE, + "true", true); + } + + @After + public void teardown() { + DeviceConfig.removeOnPropertiesChangedListener(mConfigListener); } @Test @@ -102,37 +128,79 @@ public class ContentRecorderTests extends WindowTestsBase { @Test public void testUpdateRecording_display() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); assertThat(mContentRecorder.isCurrentlyRecording()).isTrue(); } @Test - public void testUpdateRecording_task() { - mDefaultSession.setContentToRecord(RECORD_CONTENT_TASK); - mContentRecorder.setContentRecordingSession(mDefaultSession); + public void testUpdateRecording_display_nullToken() { + ContentRecordingSession session = ContentRecordingSession.createDisplaySession(TEST_TOKEN); + session.setDisplayId(mDisplaySession.getDisplayId()); + session.setTokenToRecord(null); + mContentRecorder.setContentRecordingSession(session); mContentRecorder.updateRecording(); assertThat(mContentRecorder.isCurrentlyRecording()).isFalse(); } @Test - public void testUpdateRecording_wasPaused() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + public void testUpdateRecording_display_noWindowContainer() { + doReturn(null).when( + mWm.mWindowContextListenerController).getContainer(any()); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); + assertThat(mContentRecorder.isCurrentlyRecording()).isFalse(); + } - mContentRecorder.pauseRecording(); + @Test + public void testUpdateRecording_task_featureDisabled() { + mLatch = new CountDownLatch(1); + DeviceConfig.setProperty(DeviceConfig.NAMESPACE_WINDOW_MANAGER, KEY_RECORD_TASK_FEATURE, + "false", false); + mContentRecorder.setContentRecordingSession(mTaskSession); + mContentRecorder.updateRecording(); + assertThat(mContentRecorder.isCurrentlyRecording()).isFalse(); + } + + @Test + public void testUpdateRecording_task_featureEnabled() { + // Feature already enabled; don't need to again. + mContentRecorder.setContentRecordingSession(mTaskSession); mContentRecorder.updateRecording(); assertThat(mContentRecorder.isCurrentlyRecording()).isTrue(); } @Test - public void testUpdateRecording_wasStopped() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + public void testUpdateRecording_task_nullToken() { + ContentRecordingSession session = ContentRecordingSession.createTaskSession( + sTaskWindowContainerToken); + session.setDisplayId(mDisplaySession.getDisplayId()); + session.setTokenToRecord(null); + mContentRecorder.setContentRecordingSession(session); mContentRecorder.updateRecording(); + assertThat(mContentRecorder.isCurrentlyRecording()).isFalse(); + // TODO(b/219761722) validate VirtualDisplay is torn down when can't set up task recording. + } - mContentRecorder.remove(); + @Test + public void testUpdateRecording_task_noWindowContainer() { + // Use the window container token of the DisplayContent, rather than task. + ContentRecordingSession invalidTaskSession = ContentRecordingSession.createTaskSession( + new WindowContainer.RemoteToken(mDisplayContent)); + mContentRecorder.setContentRecordingSession(invalidTaskSession); mContentRecorder.updateRecording(); assertThat(mContentRecorder.isCurrentlyRecording()).isFalse(); + // TODO(b/219761722) validate VirtualDisplay is torn down when can't set up task recording. + } + + @Test + public void testUpdateRecording_wasPaused() { + mContentRecorder.setContentRecordingSession(mDisplaySession); + mContentRecorder.updateRecording(); + + mContentRecorder.pauseRecording(); + mContentRecorder.updateRecording(); + assertThat(mContentRecorder.isCurrentlyRecording()).isTrue(); } @Test @@ -146,7 +214,7 @@ public class ContentRecorderTests extends WindowTestsBase { @Test public void testOnConfigurationChanged_resizesSurface() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); mContentRecorder.onConfigurationChanged(ORIENTATION_PORTRAIT); @@ -158,7 +226,7 @@ public class ContentRecorderTests extends WindowTestsBase { @Test public void testPauseRecording_pausesRecording() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); mContentRecorder.pauseRecording(); @@ -173,7 +241,7 @@ public class ContentRecorderTests extends WindowTestsBase { @Test public void testRemove_stopsRecording() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); mContentRecorder.remove(); @@ -188,8 +256,9 @@ public class ContentRecorderTests extends WindowTestsBase { @Test public void testUpdateMirroredSurface_capturedAreaResized() { - mContentRecorder.setContentRecordingSession(mDefaultSession); + mContentRecorder.setContentRecordingSession(mDisplaySession); mContentRecorder.updateRecording(); + assertThat(mContentRecorder.isCurrentlyRecording()).isTrue(); // WHEN attempting to mirror on the virtual display, and the captured content is resized. float xScale = 0.7f; @@ -197,13 +266,14 @@ public class ContentRecorderTests extends WindowTestsBase { Rect displayAreaBounds = new Rect(0, 0, Math.round(sSurfaceSize.x * xScale), Math.round(sSurfaceSize.y * yScale)); mContentRecorder.updateMirroredSurface(mTransaction, displayAreaBounds, sSurfaceSize); + assertThat(mContentRecorder.isCurrentlyRecording()).isTrue(); // THEN content in the captured DisplayArea is scaled to fit the surface size. verify(mTransaction, atLeastOnce()).setMatrix(mRecordedSurface, 1.0f / yScale, 0, 0, 1.0f / yScale); // THEN captured content is positioned in the centre of the output surface. - float scaledWidth = displayAreaBounds.width() / xScale; - float xInset = (sSurfaceSize.x - scaledWidth) / 2; + int scaledWidth = Math.round((float) displayAreaBounds.width() / xScale); + int xInset = (sSurfaceSize.x - scaledWidth) / 2; verify(mTransaction, atLeastOnce()).setPosition(mRecordedSurface, xInset, 0); } @@ -222,6 +292,18 @@ public class ContentRecorderTests extends WindowTestsBase { } /** + * Creates a {@link android.window.WindowContainerToken} associated with a task, in order for + * that task to be recorded. + */ + private IBinder setUpTaskWindowContainerToken(DisplayContent displayContent) { + final Task rootTask = createTask(displayContent); + final Task task = createTaskInRootTask(rootTask, 0 /* userId */); + // Ensure the task is not empty. + createActivityRecord(displayContent, task); + return task.getTaskInfo().token.asBinder(); + } + + /** * SurfaceControl successfully creates a mirrored surface of the given size. */ private SurfaceControl surfaceControlMirrors(Point surfaceSize) { @@ -236,4 +318,13 @@ public class ContentRecorderTests extends WindowTestsBase { anyInt()); return mirroredSurface; } + + private class ConfigListener implements DeviceConfig.OnPropertiesChangedListener { + @Override + public void onPropertiesChanged(@NonNull DeviceConfig.Properties properties) { + if (mLatch != null && properties.getKeyset().contains(KEY_RECORD_TASK_FEATURE)) { + mLatch.countDown(); + } + } + } } diff --git a/tests/BandwidthTests/src/com/android/tests/bandwidthenforcement/BandwidthEnforcementTestService.java b/tests/BandwidthTests/src/com/android/tests/bandwidthenforcement/BandwidthEnforcementTestService.java index 35f1e585931b..644d450a7a88 100644 --- a/tests/BandwidthTests/src/com/android/tests/bandwidthenforcement/BandwidthEnforcementTestService.java +++ b/tests/BandwidthTests/src/com/android/tests/bandwidthenforcement/BandwidthEnforcementTestService.java @@ -24,6 +24,8 @@ import android.net.SntpClient; import android.os.Environment; import android.util.Log; +import libcore.io.Streams; + import java.io.BufferedWriter; import java.io.ByteArrayOutputStream; import java.io.File; @@ -37,8 +39,6 @@ import java.net.InetAddress; import java.net.URL; import java.util.Random; -import libcore.io.Streams; - /* * Test Service that tries to connect to the web via different methods and outputs the results to * the log and a output file. @@ -146,7 +146,7 @@ public class BandwidthEnforcementTestService extends IntentService { final ConnectivityManager mCM = context.getSystemService(ConnectivityManager.class); final Network network = mCM.getActiveNetwork(); - if (client.requestTime("0.pool.ntp.org", 10000, network)) { + if (client.requestTime("0.pool.ntp.org", SntpClient.STANDARD_NTP_PORT, 10000, network)) { return true; } return false; diff --git a/tests/TrustTests/AndroidManifest.xml b/tests/TrustTests/AndroidManifest.xml index 68bc1f69628f..8b4cbfd0e44b 100644 --- a/tests/TrustTests/AndroidManifest.xml +++ b/tests/TrustTests/AndroidManifest.xml @@ -68,6 +68,16 @@ <action android:name="android.service.trust.TrustAgentService" /> </intent-filter> </service> + + <service + android:name=".TemporaryAndRenewableTrustAgent" + android:exported="true" + android:label="Test Agent" + android:permission="android.permission.BIND_TRUST_AGENT"> + <intent-filter> + <action android:name="android.service.trust.TrustAgentService" /> + </intent-filter> + </service> </application> <!-- self-instrumenting test package. --> diff --git a/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt b/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt index 790afd389152..af7a98c22ad1 100644 --- a/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt +++ b/tests/TrustTests/src/android/trust/test/GrantAndRevokeTrustTest.kt @@ -60,7 +60,6 @@ class GrantAndRevokeTrustTest { @Test fun sleepingDeviceWithoutGrantLocksDevice() { uiDevice.sleep() - await() lockStateTrackingRule.assertLocked() } @@ -69,7 +68,6 @@ class GrantAndRevokeTrustTest { fun grantKeepsDeviceUnlocked() { trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 10000, 0) uiDevice.sleep() - await() lockStateTrackingRule.assertUnlocked() } @@ -80,7 +78,6 @@ class GrantAndRevokeTrustTest { await() uiDevice.sleep() trustAgentRule.agent.revokeTrust() - await() lockStateTrackingRule.assertLocked() } diff --git a/tests/TrustTests/src/android/trust/test/LockUserTest.kt b/tests/TrustTests/src/android/trust/test/LockUserTest.kt index 8f200a64450e..a7dd41ad2e98 100644 --- a/tests/TrustTests/src/android/trust/test/LockUserTest.kt +++ b/tests/TrustTests/src/android/trust/test/LockUserTest.kt @@ -24,7 +24,6 @@ import android.trust.test.lib.TrustAgentRule import android.util.Log import androidx.test.ext.junit.rules.ActivityScenarioRule import androidx.test.ext.junit.runners.AndroidJUnit4 -import com.google.common.truth.Truth.assertThat import org.junit.Rule import org.junit.Test import org.junit.rules.RuleChain @@ -52,9 +51,8 @@ class LockUserTest { fun lockUser_locksTheDevice() { Log.i(TAG, "Locking user") trustAgentRule.agent.lockUser() - await() - assertThat(lockStateTrackingRule.lockState.locked).isTrue() + lockStateTrackingRule.assertLocked() } companion object { diff --git a/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt b/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt new file mode 100644 index 000000000000..14c227b1f678 --- /dev/null +++ b/tests/TrustTests/src/android/trust/test/TemporaryAndRenewableTrustTest.kt @@ -0,0 +1,124 @@ +/* + * Copyright (C) 2022 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package android.trust.test + +import android.service.trust.TrustAgentService.FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE +import android.trust.BaseTrustAgentService +import android.trust.TrustTestActivity +import android.trust.test.lib.LockStateTrackingRule +import android.trust.test.lib.ScreenLockRule +import android.trust.test.lib.TrustAgentRule +import androidx.test.ext.junit.rules.ActivityScenarioRule +import androidx.test.ext.junit.runners.AndroidJUnit4 +import androidx.test.platform.app.InstrumentationRegistry.getInstrumentation +import androidx.test.uiautomator.UiDevice +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.rules.RuleChain +import org.junit.runner.RunWith + +/** + * Test for testing revokeTrust & grantTrust for renewable trust. + * + * atest TrustTests:TemporaryAndRenewableTrustTest + */ +@RunWith(AndroidJUnit4::class) +class TemporaryAndRenewableTrustTest { + private val uiDevice = UiDevice.getInstance(getInstrumentation()) + private val activityScenarioRule = ActivityScenarioRule(TrustTestActivity::class.java) + private val lockStateTrackingRule = LockStateTrackingRule() + private val trustAgentRule = TrustAgentRule<TemporaryAndRenewableTrustAgent>() + + @get:Rule + val rule: RuleChain = RuleChain + .outerRule(activityScenarioRule) + .around(ScreenLockRule()) + .around(lockStateTrackingRule) + .around(trustAgentRule) + + @Before + fun manageTrust() { + trustAgentRule.agent.setManagingTrust(true) + } + + // This test serves a baseline for Grant tests, verifying that the default behavior of the + // device is to lock when put to sleep + @Test + fun sleepingDeviceWithoutGrantLocksDevice() { + uiDevice.sleep() + + lockStateTrackingRule.assertLocked() + } + + @Test + fun grantTrustLockedDevice_deviceStaysLocked() { + uiDevice.sleep() + lockStateTrackingRule.assertLocked() + + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + uiDevice.wakeUp() + + lockStateTrackingRule.assertLocked() + } + + @Test + fun grantTrustUnlockedDevice_deviceLocksOnScreenOff() { + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + uiDevice.sleep() + + lockStateTrackingRule.assertLocked() + } + + @Test + fun grantTrustLockedDevice_grantTrustOnLockedDeviceUnlocksDevice() { + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + uiDevice.sleep() + + lockStateTrackingRule.assertLocked() + + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + uiDevice.wakeUp() + + lockStateTrackingRule.assertUnlocked() + } + + @Test + fun grantTrustLockedDevice_revokeTrustPreventsSubsequentUnlock() { + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + uiDevice.sleep() + + lockStateTrackingRule.assertLocked() + + trustAgentRule.agent.revokeTrust() + await(500) + uiDevice.wakeUp() + await(500) + + trustAgentRule.agent.grantTrust(GRANT_MESSAGE, 0, FLAG_GRANT_TRUST_TEMPORARY_AND_RENEWABLE) + + lockStateTrackingRule.assertLocked() + } + + companion object { + private const val TAG = "TemporaryAndRenewableTrustTest" + private const val GRANT_MESSAGE = "granted by test" + private fun await(millis: Long) = Thread.sleep(millis) + } +} + +class TemporaryAndRenewableTrustAgent : BaseTrustAgentService() diff --git a/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt b/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt index 0023af8893e2..834f2122a21b 100644 --- a/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt +++ b/tests/TrustTests/src/android/trust/test/lib/LockStateTrackingRule.kt @@ -52,8 +52,29 @@ class LockStateTrackingRule : TestRule { } } - fun assertLocked() = assertThat(lockState.locked).isTrue() - fun assertUnlocked() = assertThat(lockState.locked).isFalse() + fun assertLocked() { + val maxWaits = 50 + var waitCount = 0 + + while ((lockState.locked == false) && waitCount < maxWaits) { + Log.i(TAG, "phone still locked, wait 50ms more ($waitCount)") + Thread.sleep(50) + waitCount++ + } + assertThat(lockState.locked).isTrue() + } + + fun assertUnlocked() { + val maxWaits = 50 + var waitCount = 0 + + while ((lockState.locked == true) && waitCount < maxWaits) { + Log.i(TAG, "phone still unlocked, wait 50ms more ($waitCount)") + Thread.sleep(50) + waitCount++ + } + assertThat(lockState.locked).isFalse() + } inner class Listener : TrustListener { override fun onTrustChanged( |