diff options
73 files changed, 2169 insertions, 1744 deletions
diff --git a/api/current.txt b/api/current.txt index a67f21fd5c0f..e5acc4062377 100644 --- a/api/current.txt +++ b/api/current.txt @@ -42916,6 +42916,7 @@ package android.system { field public static final int IP_MULTICAST_TTL; field public static final int IP_TOS; field public static final int IP_TTL; + field public static final int MAP_ANONYMOUS; field public static final int MAP_FIXED; field public static final int MAP_PRIVATE; field public static final int MAP_SHARED; diff --git a/api/system-current.txt b/api/system-current.txt index 0f4cc51ab22c..213ea3125c69 100644 --- a/api/system-current.txt +++ b/api/system-current.txt @@ -5241,6 +5241,7 @@ package android.os { } public class BatteryStatsManager { + method @NonNull @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public android.os.connectivity.CellularBatteryStats getCellularBatteryStats(); method @NonNull @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public android.os.connectivity.WifiBatteryStats getWifiBatteryStats(); method @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public void noteFullWifiLockAcquiredFromSource(@NonNull android.os.WorkSource); method @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) public void noteFullWifiLockReleasedFromSource(@NonNull android.os.WorkSource); @@ -5748,6 +5749,26 @@ package android.os { package android.os.connectivity { + public final class CellularBatteryStats implements android.os.Parcelable { + method public int describeContents(); + method public long getEnergyConsumedMaMillis(); + method public long getIdleTimeMillis(); + method public long getKernelActiveTimeMillis(); + method public long getLoggingDurationMillis(); + method public long getMonitoredRailChargeConsumedMaMillis(); + method public long getNumBytesRx(); + method public long getNumBytesTx(); + method public long getNumPacketsRx(); + method public long getNumPacketsTx(); + method public long getRxTimeMillis(); + method public long getSleepTimeMillis(); + method @NonNull public long[] getTimeInRatMicros(); + method @NonNull public long[] getTimeInRxSignalStrengthLevelMicros(); + method @NonNull public long[] getTxTimeMillis(); + method public void writeToParcel(@NonNull android.os.Parcel, int); + field @NonNull public static final android.os.Parcelable.Creator<android.os.connectivity.CellularBatteryStats> CREATOR; + } + public final class WifiBatteryStats implements android.os.Parcelable { method public int describeContents(); method public long getEnergyConsumedMaMillis(); diff --git a/core/java/android/app/PendingIntent.java b/core/java/android/app/PendingIntent.java index 3ad88829b812..06b95067c2e8 100644 --- a/core/java/android/app/PendingIntent.java +++ b/core/java/android/app/PendingIntent.java @@ -1274,7 +1274,12 @@ public final class PendingIntent implements Parcelable { return b != null ? new PendingIntent(b, in.getClassCookie(PendingIntent.class)) : null; } - /*package*/ PendingIntent(IIntentSender target) { + /** + * Creates a PendingIntent with the given target. + * @param target the backing IIntentSender + * @hide + */ + public PendingIntent(IIntentSender target) { mTarget = target; } diff --git a/core/java/android/os/BatteryStatsManager.java b/core/java/android/os/BatteryStatsManager.java index 367a868ddef4..e5650aea0522 100644 --- a/core/java/android/os/BatteryStatsManager.java +++ b/core/java/android/os/BatteryStatsManager.java @@ -23,6 +23,7 @@ import android.annotation.RequiresPermission; import android.annotation.SystemApi; import android.annotation.SystemService; import android.content.Context; +import android.os.connectivity.CellularBatteryStats; import android.os.connectivity.WifiBatteryStats; import com.android.internal.app.IBatteryStats; @@ -158,6 +159,21 @@ public class BatteryStatsManager { } /** + * Retrieves all the cellular related battery stats. + * + * @return Instance of {@link CellularBatteryStats}. + */ + @RequiresPermission(android.Manifest.permission.UPDATE_DEVICE_STATS) + public @NonNull CellularBatteryStats getCellularBatteryStats() { + try { + return mBatteryStats.getCellularBatteryStats(); + } catch (RemoteException e) { + e.rethrowFromSystemServer(); + return null; + } + } + + /** * Retrieves all the wifi related battery stats. * * @return Instance of {@link WifiBatteryStats}. diff --git a/core/java/android/os/connectivity/CellularBatteryStats.java b/core/java/android/os/connectivity/CellularBatteryStats.java index 2e0904048d40..caa406899161 100644 --- a/core/java/android/os/connectivity/CellularBatteryStats.java +++ b/core/java/android/os/connectivity/CellularBatteryStats.java @@ -15,241 +15,367 @@ */ package android.os.connectivity; +import android.annotation.NonNull; +import android.annotation.Nullable; +import android.annotation.SystemApi; import android.os.BatteryStats; import android.os.Parcel; import android.os.Parcelable; - +import android.telephony.Annotation.NetworkType; import android.telephony.ModemActivityInfo; import android.telephony.SignalStrength; import java.util.Arrays; +import java.util.Objects; /** * API for Cellular power stats * * @hide */ +@SystemApi public final class CellularBatteryStats implements Parcelable { - private long mLoggingDurationMs; - private long mKernelActiveTimeMs; - private long mNumPacketsTx; - private long mNumBytesTx; - private long mNumPacketsRx; - private long mNumBytesRx; - private long mSleepTimeMs; - private long mIdleTimeMs; - private long mRxTimeMs; - private long mEnergyConsumedMaMs; - private long[] mTimeInRatMs; - private long[] mTimeInRxSignalStrengthLevelMs; - private long[] mTxTimeMs; - private long mMonitoredRailChargeConsumedMaMs; - - public static final @android.annotation.NonNull Parcelable.Creator<CellularBatteryStats> CREATOR = new - Parcelable.Creator<CellularBatteryStats>() { - public CellularBatteryStats createFromParcel(Parcel in) { - return new CellularBatteryStats(in); - } - - public CellularBatteryStats[] newArray(int size) { - return new CellularBatteryStats[size]; - } - }; - - public CellularBatteryStats() { - initialize(); - } - - public void writeToParcel(Parcel out, int flags) { - out.writeLong(mLoggingDurationMs); - out.writeLong(mKernelActiveTimeMs); - out.writeLong(mNumPacketsTx); - out.writeLong(mNumBytesTx); - out.writeLong(mNumPacketsRx); - out.writeLong(mNumBytesRx); - out.writeLong(mSleepTimeMs); - out.writeLong(mIdleTimeMs); - out.writeLong(mRxTimeMs); - out.writeLong(mEnergyConsumedMaMs); - out.writeLongArray(mTimeInRatMs); - out.writeLongArray(mTimeInRxSignalStrengthLevelMs); - out.writeLongArray(mTxTimeMs); - out.writeLong(mMonitoredRailChargeConsumedMaMs); - } - - public void readFromParcel(Parcel in) { - mLoggingDurationMs = in.readLong(); - mKernelActiveTimeMs = in.readLong(); - mNumPacketsTx = in.readLong(); - mNumBytesTx = in.readLong(); - mNumPacketsRx = in.readLong(); - mNumBytesRx = in.readLong(); - mSleepTimeMs = in.readLong(); - mIdleTimeMs = in.readLong(); - mRxTimeMs = in.readLong(); - mEnergyConsumedMaMs = in.readLong(); - in.readLongArray(mTimeInRatMs); - in.readLongArray(mTimeInRxSignalStrengthLevelMs); - in.readLongArray(mTxTimeMs); - mMonitoredRailChargeConsumedMaMs = in.readLong(); - } - - public long getLoggingDurationMs() { - return mLoggingDurationMs; - } - - public long getKernelActiveTimeMs() { - return mKernelActiveTimeMs; - } - - public long getNumPacketsTx() { - return mNumPacketsTx; - } - - public long getNumBytesTx() { - return mNumBytesTx; - } - - public long getNumPacketsRx() { - return mNumPacketsRx; - } - - public long getNumBytesRx() { - return mNumBytesRx; - } - - public long getSleepTimeMs() { - return mSleepTimeMs; - } - - public long getIdleTimeMs() { - return mIdleTimeMs; - } - - public long getRxTimeMs() { - return mRxTimeMs; - } - - public long getEnergyConsumedMaMs() { - return mEnergyConsumedMaMs; - } - - public long[] getTimeInRatMs() { - return mTimeInRatMs; - } - - public long[] getTimeInRxSignalStrengthLevelMs() { - return mTimeInRxSignalStrengthLevelMs; - } - - public long[] getTxTimeMs() { - return mTxTimeMs; - } - - public long getMonitoredRailChargeConsumedMaMs() { - return mMonitoredRailChargeConsumedMaMs; - } - - public void setLoggingDurationMs(long t) { - mLoggingDurationMs = t; - return; - } - - public void setKernelActiveTimeMs(long t) { - mKernelActiveTimeMs = t; - return; - } - - public void setNumPacketsTx(long n) { - mNumPacketsTx = n; - return; - } - - public void setNumBytesTx(long b) { - mNumBytesTx = b; - return; - } - - public void setNumPacketsRx(long n) { - mNumPacketsRx = n; - return; - } - - public void setNumBytesRx(long b) { - mNumBytesRx = b; - return; - } - - public void setSleepTimeMs(long t) { - mSleepTimeMs = t; - return; - } - - public void setIdleTimeMs(long t) { - mIdleTimeMs = t; - return; - } - - public void setRxTimeMs(long t) { - mRxTimeMs = t; - return; - } - - public void setEnergyConsumedMaMs(long e) { - mEnergyConsumedMaMs = e; - return; - } - - public void setTimeInRatMs(long[] t) { - mTimeInRatMs = Arrays.copyOfRange(t, 0, - Math.min(t.length, BatteryStats.NUM_DATA_CONNECTION_TYPES)); - return; - } - - public void setTimeInRxSignalStrengthLevelMs(long[] t) { - mTimeInRxSignalStrengthLevelMs = Arrays.copyOfRange(t, 0, - Math.min(t.length, SignalStrength.NUM_SIGNAL_STRENGTH_BINS)); - return; - } - - public void setTxTimeMs(long[] t) { - mTxTimeMs = Arrays.copyOfRange(t, 0, Math.min(t.length, ModemActivityInfo.TX_POWER_LEVELS)); - return; - } - - public void setMonitoredRailChargeConsumedMaMs(long monitoredRailEnergyConsumedMaMs) { - mMonitoredRailChargeConsumedMaMs = monitoredRailEnergyConsumedMaMs; - return; - } - - public int describeContents() { - return 0; - } - - private CellularBatteryStats(Parcel in) { - initialize(); - readFromParcel(in); - } - - private void initialize() { - mLoggingDurationMs = 0; - mKernelActiveTimeMs = 0; - mNumPacketsTx = 0; - mNumBytesTx = 0; - mNumPacketsRx = 0; - mNumBytesRx = 0; - mSleepTimeMs = 0; - mIdleTimeMs = 0; - mRxTimeMs = 0; - mEnergyConsumedMaMs = 0; - mTimeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES]; - Arrays.fill(mTimeInRatMs, 0); - mTimeInRxSignalStrengthLevelMs = new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS]; - Arrays.fill(mTimeInRxSignalStrengthLevelMs, 0); - mTxTimeMs = new long[ModemActivityInfo.TX_POWER_LEVELS]; - Arrays.fill(mTxTimeMs, 0); - mMonitoredRailChargeConsumedMaMs = 0; - return; - } -}
\ No newline at end of file + private long mLoggingDurationMs = 0; + private long mKernelActiveTimeMs = 0; + private long mNumPacketsTx = 0; + private long mNumBytesTx = 0; + private long mNumPacketsRx = 0; + private long mNumBytesRx = 0; + private long mSleepTimeMs = 0; + private long mIdleTimeMs = 0; + private long mRxTimeMs = 0; + private long mEnergyConsumedMaMs = 0; + private long[] mTimeInRatMs = new long[BatteryStats.NUM_DATA_CONNECTION_TYPES]; + private long[] mTimeInRxSignalStrengthLevelMs = + new long[SignalStrength.NUM_SIGNAL_STRENGTH_BINS]; + private long[] mTxTimeMs = new long[ModemActivityInfo.TX_POWER_LEVELS]; + private long mMonitoredRailChargeConsumedMaMs = 0; + + public static final @NonNull Parcelable.Creator<CellularBatteryStats> CREATOR = + new Parcelable.Creator<CellularBatteryStats>() { + public CellularBatteryStats createFromParcel(Parcel in) { + return new CellularBatteryStats(in); + } + + public CellularBatteryStats[] newArray(int size) { + return new CellularBatteryStats[size]; + } + }; + + /** @hide **/ + public CellularBatteryStats() {} + + @Override + public void writeToParcel(@NonNull Parcel out, int flags) { + out.writeLong(mLoggingDurationMs); + out.writeLong(mKernelActiveTimeMs); + out.writeLong(mNumPacketsTx); + out.writeLong(mNumBytesTx); + out.writeLong(mNumPacketsRx); + out.writeLong(mNumBytesRx); + out.writeLong(mSleepTimeMs); + out.writeLong(mIdleTimeMs); + out.writeLong(mRxTimeMs); + out.writeLong(mEnergyConsumedMaMs); + out.writeLongArray(mTimeInRatMs); + out.writeLongArray(mTimeInRxSignalStrengthLevelMs); + out.writeLongArray(mTxTimeMs); + out.writeLong(mMonitoredRailChargeConsumedMaMs); + } + + private void readFromParcel(Parcel in) { + mLoggingDurationMs = in.readLong(); + mKernelActiveTimeMs = in.readLong(); + mNumPacketsTx = in.readLong(); + mNumBytesTx = in.readLong(); + mNumPacketsRx = in.readLong(); + mNumBytesRx = in.readLong(); + mSleepTimeMs = in.readLong(); + mIdleTimeMs = in.readLong(); + mRxTimeMs = in.readLong(); + mEnergyConsumedMaMs = in.readLong(); + in.readLongArray(mTimeInRatMs); + in.readLongArray(mTimeInRxSignalStrengthLevelMs); + in.readLongArray(mTxTimeMs); + mMonitoredRailChargeConsumedMaMs = in.readLong(); + } + + @Override + public boolean equals(@Nullable Object other) { + if (!(other instanceof CellularBatteryStats)) return false; + if (other == this) return true; + CellularBatteryStats otherStats = (CellularBatteryStats) other; + return this.mLoggingDurationMs == otherStats.mLoggingDurationMs + && this.mKernelActiveTimeMs == otherStats.mKernelActiveTimeMs + && this.mNumPacketsTx == otherStats.mNumPacketsTx + && this.mNumBytesTx == otherStats.mNumBytesTx + && this.mNumPacketsRx == otherStats.mNumPacketsRx + && this.mNumBytesRx == otherStats.mNumBytesRx + && this.mSleepTimeMs == otherStats.mSleepTimeMs + && this.mIdleTimeMs == otherStats.mIdleTimeMs + && this.mRxTimeMs == otherStats.mRxTimeMs + && this.mEnergyConsumedMaMs == otherStats.mEnergyConsumedMaMs + && Arrays.equals(this.mTimeInRatMs, otherStats.mTimeInRatMs) + && Arrays.equals(this.mTimeInRxSignalStrengthLevelMs, + otherStats.mTimeInRxSignalStrengthLevelMs) + && Arrays.equals(this.mTxTimeMs, otherStats.mTxTimeMs) + && this.mMonitoredRailChargeConsumedMaMs + == otherStats.mMonitoredRailChargeConsumedMaMs; + } + + @Override + public int hashCode() { + return Objects.hash(mLoggingDurationMs, mKernelActiveTimeMs, mNumPacketsTx, + mNumBytesTx, mNumPacketsRx, mNumBytesRx, mSleepTimeMs, mIdleTimeMs, + mRxTimeMs, mEnergyConsumedMaMs, Arrays.hashCode(mTimeInRatMs), + Arrays.hashCode(mTimeInRxSignalStrengthLevelMs), Arrays.hashCode(mTxTimeMs), + mMonitoredRailChargeConsumedMaMs); + } + + /** + * Returns the duration for which these cellular stats were collected. + * + * @return Duration of stats collection in milliseconds. + */ + public long getLoggingDurationMillis() { + return mLoggingDurationMs; + } + + /** + * Returns the duration for which the kernel was active within + * {@link #getLoggingDurationMillis()}. + * + * @return Duration of kernel active time in milliseconds. + */ + public long getKernelActiveTimeMillis() { + return mKernelActiveTimeMs; + } + + /** + * Returns the number of packets transmitted over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Number of packets transmitted. + */ + public long getNumPacketsTx() { + return mNumPacketsTx; + } + + /** + * Returns the number of packets received over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Number of packets received. + */ + public long getNumBytesTx() { + return mNumBytesTx; + } + + /** + * Returns the number of bytes transmitted over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Number of bytes transmitted. + */ + public long getNumPacketsRx() { + return mNumPacketsRx; + } + + /** + * Returns the number of bytes received over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Number of bytes received. + */ + public long getNumBytesRx() { + return mNumBytesRx; + } + + /** + * Returns the duration for which the device was sleeping within + * {@link #getLoggingDurationMillis()}. + * + * @return Duration of sleep time in milliseconds. + */ + public long getSleepTimeMillis() { + return mSleepTimeMs; + } + + /** + * Returns the duration for which the device was idle within + * {@link #getLoggingDurationMillis()}. + * + * @return Duration of idle time in milliseconds. + */ + public long getIdleTimeMillis() { + return mIdleTimeMs; + } + + /** + * Returns the duration for which the device was receiving over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Duration of cellular reception time in milliseconds. + */ + public long getRxTimeMillis() { + return mRxTimeMs; + } + + /** + * Returns an estimation of energy consumed by cellular chip within + * {@link #getLoggingDurationMillis()}. + * + * @return Energy consumed in milli-ampere milliseconds (mAmS). + */ + public long getEnergyConsumedMaMillis() { + return mEnergyConsumedMaMs; + } + + /** + * Returns the time in microseconds that the phone has been running with + * the given data connection. + * + * @return Amount of time phone spends in various Radio Access Technologies in microseconds. + * The index is {@link NetworkType}. + */ + @NonNull + public long[] getTimeInRatMicros() { + return mTimeInRatMs; + } + + /** + * Returns the time in microseconds that the phone has been running with + * the given signal strength. + * + * @return Amount of time phone spends in various cellular rx signal strength levels + * in microseconds. The index is signal strength bin. + */ + @NonNull + public long[] getTimeInRxSignalStrengthLevelMicros() { + return mTimeInRxSignalStrengthLevelMs; + } + + /** + * Returns the duration for which the device was transmitting over cellular within + * {@link #getLoggingDurationMillis()}. + * + * @return Duration of cellular transmission time in milliseconds. + * Tx(transmit) power index below + * <ul> + * <li> index 0 = tx_power < 0dBm. </li> + * <li> index 1 = 0dBm < tx_power < 5dBm. </li> + * <li> index 2 = 5dBm < tx_power < 15dBm. </li> + * <li> index 3 = 15dBm < tx_power < 20dBm. </li> + * <li> index 4 = tx_power > 20dBm. </li> + * </ul> + */ + @NonNull + public long[] getTxTimeMillis() { + return mTxTimeMs; + } + + /** + * Returns the energy consumed by cellular chip within {@link #getLoggingDurationMillis()}. + * + * @return Energy consumed in milli-ampere milli-seconds (mAmS). + */ + public long getMonitoredRailChargeConsumedMaMillis() { + return mMonitoredRailChargeConsumedMaMs; + } + + /** @hide **/ + public void setLoggingDurationMillis(long t) { + mLoggingDurationMs = t; + return; + } + + /** @hide **/ + public void setKernelActiveTimeMillis(long t) { + mKernelActiveTimeMs = t; + return; + } + + /** @hide **/ + public void setNumPacketsTx(long n) { + mNumPacketsTx = n; + return; + } + + /** @hide **/ + public void setNumBytesTx(long b) { + mNumBytesTx = b; + return; + } + + /** @hide **/ + public void setNumPacketsRx(long n) { + mNumPacketsRx = n; + return; + } + + /** @hide **/ + public void setNumBytesRx(long b) { + mNumBytesRx = b; + return; + } + + /** @hide **/ + public void setSleepTimeMillis(long t) { + mSleepTimeMs = t; + return; + } + + /** @hide **/ + public void setIdleTimeMillis(long t) { + mIdleTimeMs = t; + return; + } + + /** @hide **/ + public void setRxTimeMillis(long t) { + mRxTimeMs = t; + return; + } + + /** @hide **/ + public void setEnergyConsumedMaMillis(long e) { + mEnergyConsumedMaMs = e; + return; + } + + /** @hide **/ + public void setTimeInRatMicros(@NonNull long[] t) { + mTimeInRatMs = Arrays.copyOfRange(t, 0, + Math.min(t.length, BatteryStats.NUM_DATA_CONNECTION_TYPES)); + return; + } + + /** @hide **/ + public void setTimeInRxSignalStrengthLevelMicros(@NonNull long[] t) { + mTimeInRxSignalStrengthLevelMs = Arrays.copyOfRange(t, 0, + Math.min(t.length, SignalStrength.NUM_SIGNAL_STRENGTH_BINS)); + return; + } + + /** @hide **/ + public void setTxTimeMillis(@NonNull long[] t) { + mTxTimeMs = Arrays.copyOfRange(t, 0, Math.min(t.length, ModemActivityInfo.TX_POWER_LEVELS)); + return; + } + + /** @hide **/ + public void setMonitoredRailChargeConsumedMaMillis(long monitoredRailEnergyConsumedMaMs) { + mMonitoredRailChargeConsumedMaMs = monitoredRailEnergyConsumedMaMs; + return; + } + + @Override + public int describeContents() { + return 0; + } + + private CellularBatteryStats(Parcel in) { + readFromParcel(in); + } +} diff --git a/core/java/com/android/internal/os/BatteryStatsImpl.java b/core/java/com/android/internal/os/BatteryStatsImpl.java index d6b32b58ce64..f5bfe5cfecaf 100644 --- a/core/java/com/android/internal/os/BatteryStatsImpl.java +++ b/core/java/com/android/internal/os/BatteryStatsImpl.java @@ -12618,20 +12618,20 @@ public class BatteryStatsImpl extends BatteryStats { txTimeMs[i] = counter.getTxTimeCounters()[i].getCountLocked(which); totalTxTimeMs += txTimeMs[i]; } - s.setLoggingDurationMs(computeBatteryRealtime(rawRealTime, which) / 1000); - s.setKernelActiveTimeMs(getMobileRadioActiveTime(rawRealTime, which) / 1000); + s.setLoggingDurationMillis(computeBatteryRealtime(rawRealTime, which) / 1000); + s.setKernelActiveTimeMillis(getMobileRadioActiveTime(rawRealTime, which) / 1000); s.setNumPacketsTx(getNetworkActivityPackets(NETWORK_MOBILE_TX_DATA, which)); s.setNumBytesTx(getNetworkActivityBytes(NETWORK_MOBILE_TX_DATA, which)); s.setNumPacketsRx(getNetworkActivityPackets(NETWORK_MOBILE_RX_DATA, which)); s.setNumBytesRx(getNetworkActivityBytes(NETWORK_MOBILE_RX_DATA, which)); - s.setSleepTimeMs(sleepTimeMs); - s.setIdleTimeMs(idleTimeMs); - s.setRxTimeMs(rxTimeMs); - s.setEnergyConsumedMaMs(energyConsumedMaMs); - s.setTimeInRatMs(timeInRatMs); - s.setTimeInRxSignalStrengthLevelMs(timeInRxSignalStrengthLevelMs); - s.setTxTimeMs(txTimeMs); - s.setMonitoredRailChargeConsumedMaMs(monitoredRailChargeConsumedMaMs); + s.setSleepTimeMillis(sleepTimeMs); + s.setIdleTimeMillis(idleTimeMs); + s.setRxTimeMillis(rxTimeMs); + s.setEnergyConsumedMaMillis(energyConsumedMaMs); + s.setTimeInRatMicros(timeInRatMs); + s.setTimeInRxSignalStrengthLevelMicros(timeInRxSignalStrengthLevelMs); + s.setTxTimeMillis(txTimeMs); + s.setMonitoredRailChargeConsumedMaMillis(monitoredRailChargeConsumedMaMs); return s; } diff --git a/core/proto/android/server/activitymanagerservice.proto b/core/proto/android/server/activitymanagerservice.proto index 2f87debce978..b9d28e4ce8eb 100644 --- a/core/proto/android/server/activitymanagerservice.proto +++ b/core/proto/android/server/activitymanagerservice.proto @@ -100,7 +100,8 @@ message ActivityStackProto { message TaskRecordProto { option (.android.msg_privacy).dest = DEST_AUTOMATIC; - optional .com.android.server.wm.ConfigurationContainerProto configuration_container = 1; + // To be removed soon. + optional .com.android.server.wm.ConfigurationContainerProto configuration_container = 1 [deprecated=true]; optional int32 id = 2; repeated ActivityRecordProto activities = 3; optional int32 stack_id = 4; @@ -113,6 +114,7 @@ message TaskRecordProto { optional .android.graphics.RectProto bounds = 11; optional int32 min_width = 12; optional int32 min_height = 13; + optional .com.android.server.wm.TaskProto task = 14; } message ActivityRecordProto { diff --git a/location/java/android/location/LocationRequest.java b/location/java/android/location/LocationRequest.java index 3abd2c2144e1..ca8f2ac82e94 100644 --- a/location/java/android/location/LocationRequest.java +++ b/location/java/android/location/LocationRequest.java @@ -505,6 +505,23 @@ public final class LocationRequest implements Parcelable { } /** + * Returns the realtime at which this request expires, taking into account both + * {@link #setExpireAt(long)} and {@link #setExpireIn(long)} relative to the given realtime. + * + * @hide + */ + public long getExpirationRealtimeMs(long startRealtimeMs) { + long expirationRealtimeMs; + // Check for > Long.MAX_VALUE overflow (elapsedRealtime > 0): + if (mExpireIn > Long.MAX_VALUE - startRealtimeMs) { + expirationRealtimeMs = Long.MAX_VALUE; + } else { + expirationRealtimeMs = startRealtimeMs + mExpireIn; + } + return Math.min(expirationRealtimeMs, mExpireAt); + } + + /** * Set the number of location updates. * * <p>By default locations are continuously updated until the request is explicitly diff --git a/media/java/android/media/tv/tuner/Tuner.java b/media/java/android/media/tv/tuner/Tuner.java index d1c171a2d7df..4ed8f423d6c9 100644 --- a/media/java/android/media/tv/tuner/Tuner.java +++ b/media/java/android/media/tv/tuner/Tuner.java @@ -16,6 +16,11 @@ package android.media.tv.tuner; +import android.annotation.Nullable; +import android.os.Handler; +import android.os.Looper; +import android.os.Message; + import java.util.List; /** @@ -34,8 +39,9 @@ public final class Tuner implements AutoCloseable { nativeInit(); } - private FrontendCallback mFrontendCallback; private List<Integer> mFrontendIds; + private Frontend mFrontend; + private EventHandler mHandler; public Tuner() { nativeSetup(); @@ -80,11 +86,66 @@ public final class Tuner implements AutoCloseable { void onEvent(int frontendEventType); } - protected static class Frontend { - int mId; + @Nullable + private EventHandler createEventHandler() { + Looper looper; + if ((looper = Looper.myLooper()) != null) { + return new EventHandler(looper); + } else if ((looper = Looper.getMainLooper()) != null) { + return new EventHandler(looper); + } + return null; + } + + private class EventHandler extends Handler { + private EventHandler(Looper looper) { + super(looper); + } + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_ON_FRONTEND_EVENT: + if (mFrontend != null && mFrontend.mCallback != null) { + mFrontend.mCallback.onEvent(msg.arg1); + } + break; + default: + // fall through + } + } + } + + protected class Frontend { + private int mId; + private FrontendCallback mCallback; + private Frontend(int id) { mId = id; } + + public void setCallback(@Nullable FrontendCallback callback, @Nullable Handler handler) { + mCallback = callback; + + if (mCallback == null) { + return; + } + + if (handler == null) { + // use default looper if handler is null + if (mHandler == null) { + mHandler = createEventHandler(); + } + return; + } + + Looper looper = handler.getLooper(); + if (mHandler != null && mHandler.getLooper() == looper) { + // the same looper. reuse mHandler + return; + } + mHandler = new EventHandler(looper); + } } private List<Integer> getFrontendIds() { @@ -94,12 +155,19 @@ public final class Tuner implements AutoCloseable { private Frontend openFrontendById(int id) { if (mFrontendIds == null) { - getFrontendIds(); + mFrontendIds = getFrontendIds(); } if (!mFrontendIds.contains(id)) { return null; } - return nativeOpenFrontendById(id); + mFrontend = nativeOpenFrontendById(id); + return mFrontend; + } + + private void onFrontendEvent(int eventType) { + if (mHandler != null) { + mHandler.sendMessage(mHandler.obtainMessage(MSG_ON_FRONTEND_EVENT, eventType, 0)); + } } protected class Filter { diff --git a/media/jni/android_media_MediaCrypto.cpp b/media/jni/android_media_MediaCrypto.cpp index 2d9051f5230d..517672ee6127 100644 --- a/media/jni/android_media_MediaCrypto.cpp +++ b/media/jni/android_media_MediaCrypto.cpp @@ -24,11 +24,10 @@ #include "jni.h" #include <nativehelper/JNIHelp.h> -#include <binder/IServiceManager.h> #include <cutils/properties.h> #include <media/stagefright/foundation/ADebug.h> +#include <mediadrm/DrmUtils.h> #include <mediadrm/ICrypto.h> -#include <mediadrm/IMediaDrmService.h> namespace android { @@ -64,20 +63,7 @@ JCrypto::~JCrypto() { // static sp<ICrypto> JCrypto::MakeCrypto() { - sp<IServiceManager> sm = defaultServiceManager(); - - sp<IBinder> binder = sm->getService(String16("media.drm")); - sp<IMediaDrmService> service = interface_cast<IMediaDrmService>(binder); - if (service == NULL) { - return NULL; - } - - sp<ICrypto> crypto = service->makeCrypto(); - if (crypto == NULL || (crypto->initCheck() != OK && crypto->initCheck() != NO_INIT)) { - return NULL; - } - - return crypto; + return DrmUtils::MakeCrypto(); } // static diff --git a/media/jni/android_media_MediaDrm.cpp b/media/jni/android_media_MediaDrm.cpp index f412161f418a..820fe98cafb6 100644 --- a/media/jni/android_media_MediaDrm.cpp +++ b/media/jni/android_media_MediaDrm.cpp @@ -27,14 +27,13 @@ #include "jni.h" #include <nativehelper/JNIHelp.h> -#include <binder/IServiceManager.h> #include <binder/Parcel.h> #include <binder/PersistableBundle.h> #include <cutils/properties.h> #include <media/stagefright/foundation/ADebug.h> #include <media/stagefright/MediaErrors.h> +#include <mediadrm/DrmUtils.h> #include <mediadrm/IDrm.h> -#include <mediadrm/IMediaDrmService.h> using ::android::os::PersistableBundle; @@ -486,20 +485,7 @@ JDrm::~JDrm() { // static sp<IDrm> JDrm::MakeDrm() { - sp<IServiceManager> sm = defaultServiceManager(); - - sp<IBinder> binder = sm->getService(String16("media.drm")); - sp<IMediaDrmService> service = interface_cast<IMediaDrmService>(binder); - if (service == NULL) { - return NULL; - } - - sp<IDrm> drm = service->makeDrm(); - if (drm == NULL || (drm->initCheck() != OK && drm->initCheck() != NO_INIT)) { - return NULL; - } - - return drm; + return DrmUtils::MakeDrm(); } // static diff --git a/media/jni/android_media_tv_Tuner.cpp b/media/jni/android_media_tv_Tuner.cpp index 9e96b74dd471..f8150972a413 100644 --- a/media/jni/android_media_tv_Tuner.cpp +++ b/media/jni/android_media_tv_Tuner.cpp @@ -36,6 +36,7 @@ struct fields_t { jfieldID context; jmethodID frontendInitID; jmethodID filterInitID; + jmethodID onFrontendEventID; }; static fields_t gFields; @@ -52,7 +53,32 @@ Return<void> FilterCallback::onFilterStatus(const DemuxFilterStatus /*status*/) return Void(); } +/////////////// FrontendCallback /////////////////////// + +FrontendCallback::FrontendCallback(jweak tunerObj, FrontendId id) : mObject(tunerObj), mId(id) {} + +Return<void> FrontendCallback::onEvent(FrontendEventType frontendEventType) { + ALOGD("FrontendCallback::onEvent, type=%d", frontendEventType); + JNIEnv *env = AndroidRuntime::getJNIEnv(); + env->CallVoidMethod( + mObject, + gFields.onFrontendEventID, + (jint)frontendEventType); + return Void(); +} +Return<void> FrontendCallback::onDiseqcMessage(const hidl_vec<uint8_t>& /*diseqcMessage*/) { + ALOGD("FrontendCallback::onDiseqcMessage"); + return Void(); +} + +Return<void> FrontendCallback::onScanMessage( + FrontendScanMessageType type, const FrontendScanMessage& /*message*/) { + ALOGD("FrontendCallback::onScanMessage, type=%d", type); + return Void(); +} + /////////////// Tuner /////////////////////// + sp<ITuner> JTuner::mTuner; JTuner::JTuner(JNIEnv *env, jobject thiz) @@ -89,11 +115,10 @@ sp<ITuner> JTuner::getTunerService() { jobject JTuner::getFrontendIds() { ALOGD("JTuner::getFrontendIds()"); - hidl_vec<FrontendId> feIds; mTuner->getFrontendIds([&](Result, const hidl_vec<FrontendId>& frontendIds) { - feIds = frontendIds; + mFeIds = frontendIds; }); - if (feIds.size() == 0) { + if (mFeIds.size() == 0) { ALOGW("Frontend isn't available"); return NULL; } @@ -106,21 +131,25 @@ jobject JTuner::getFrontendIds() { jclass integerClazz = env->FindClass("java/lang/Integer"); jmethodID intInit = env->GetMethodID(integerClazz, "<init>", "(I)V"); - for (int i=0; i < feIds.size(); i++) { - jobject idObj = env->NewObject(integerClazz, intInit, feIds[i]); + for (int i=0; i < mFeIds.size(); i++) { + jobject idObj = env->NewObject(integerClazz, intInit, mFeIds[i]); env->CallBooleanMethod(obj, arrayListAdd, idObj); } return obj; } jobject JTuner::openFrontendById(int id) { + sp<IFrontend> fe; mTuner->openFrontendById(id, [&](Result, const sp<IFrontend>& frontend) { - mFe = frontend; + fe = frontend; }); - if (mFe == nullptr) { + if (fe == nullptr) { ALOGE("Failed to open frontend"); return NULL; } + mFe = fe; + sp<FrontendCallback> feCb = new FrontendCallback(mObject, id); + fe->setCallback(feCb); jint jId = (jint) id; JNIEnv *env = AndroidRuntime::getJNIEnv(); @@ -128,6 +157,7 @@ jobject JTuner::openFrontendById(int id) { return env->NewObject( env->FindClass("android/media/tv/tuner/Tuner$Frontend"), gFields.frontendInitID, + mObject, (jint) jId); } @@ -210,8 +240,11 @@ static void android_media_tv_Tuner_native_init(JNIEnv *env) { gFields.context = env->GetFieldID(clazz, "mNativeContext", "J"); CHECK(gFields.context != NULL); + gFields.onFrontendEventID = env->GetMethodID(clazz, "onFrontendEvent", "(I)V"); + jclass frontendClazz = env->FindClass("android/media/tv/tuner/Tuner$Frontend"); - gFields.frontendInitID = env->GetMethodID(frontendClazz, "<init>", "(I)V"); + gFields.frontendInitID = + env->GetMethodID(frontendClazz, "<init>", "(Landroid/media/tv/tuner/Tuner;I)V"); jclass filterClazz = env->FindClass("android/media/tv/tuner/Tuner$Filter"); gFields.filterInitID = diff --git a/media/jni/android_media_tv_Tuner.h b/media/jni/android_media_tv_Tuner.h index b23b39492ac0..7a889c3534da 100644 --- a/media/jni/android_media_tv_Tuner.h +++ b/media/jni/android_media_tv_Tuner.h @@ -24,14 +24,19 @@ #include "jni.h" using ::android::hardware::Return; +using ::android::hardware::hidl_vec; using ::android::hardware::tv::tuner::V1_0::DemuxFilterEvent; using ::android::hardware::tv::tuner::V1_0::DemuxFilterStatus; using ::android::hardware::tv::tuner::V1_0::DemuxFilterType; +using ::android::hardware::tv::tuner::V1_0::FrontendEventType; using ::android::hardware::tv::tuner::V1_0::FrontendId; +using ::android::hardware::tv::tuner::V1_0::FrontendScanMessage; +using ::android::hardware::tv::tuner::V1_0::FrontendScanMessageType; using ::android::hardware::tv::tuner::V1_0::IDemux; using ::android::hardware::tv::tuner::V1_0::IFilter; using ::android::hardware::tv::tuner::V1_0::IFilterCallback; using ::android::hardware::tv::tuner::V1_0::IFrontend; +using ::android::hardware::tv::tuner::V1_0::IFrontendCallback; using ::android::hardware::tv::tuner::V1_0::ITuner; namespace android { @@ -41,6 +46,18 @@ struct FilterCallback : public IFilterCallback { virtual Return<void> onFilterStatus(const DemuxFilterStatus status); }; +struct FrontendCallback : public IFrontendCallback { + FrontendCallback(jweak tunerObj, FrontendId id); + + virtual Return<void> onEvent(FrontendEventType frontendEventType); + virtual Return<void> onDiseqcMessage(const hidl_vec<uint8_t>& diseqcMessage); + virtual Return<void> onScanMessage( + FrontendScanMessageType type, const FrontendScanMessage& message); + + jweak mObject; + FrontendId mId; +}; + struct JTuner : public RefBase { JTuner(JNIEnv *env, jobject thiz); sp<ITuner> getTunerService(); @@ -55,6 +72,7 @@ private: jclass mClass; jweak mObject; static sp<ITuner> mTuner; + hidl_vec<FrontendId> mFeIds; sp<IFrontend> mFe; sp<IDemux> mDemux; int mDemuxId; diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java index 110b32b57878..fc0b317d04ff 100644 --- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java +++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBar.java @@ -92,6 +92,7 @@ import com.android.systemui.statusbar.NotificationRemoteInputManager; import com.android.systemui.statusbar.NotificationViewHierarchyManager; import com.android.systemui.statusbar.PulseExpansionHandler; import com.android.systemui.statusbar.StatusBarState; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; @@ -131,7 +132,6 @@ import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler; import com.android.systemui.statusbar.policy.RemoteInputUriController; import com.android.systemui.statusbar.policy.UserSwitcherController; import com.android.systemui.statusbar.policy.ZenModeController; -import com.android.systemui.util.InjectionInflationController; import java.io.FileDescriptor; import java.io.PrintWriter; @@ -244,7 +244,6 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt KeyguardUpdateMonitor keyguardUpdateMonitor, StatusBarIconController statusBarIconController, DozeLog dozeLog, - InjectionInflationController injectionInflationController, PulseExpansionHandler pulseExpansionHandler, NotificationWakeUpCoordinator notificationWakeUpCoordinator, KeyguardBypassController keyguardBypassController, @@ -303,6 +302,7 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt CommandQueue commandQueue, PluginManager pluginManager, RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory, /* Car Settings injected components. */ CarNavigationBarController carNavigationBarController) { super( @@ -313,7 +313,6 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt keyguardUpdateMonitor, statusBarIconController, dozeLog, - injectionInflationController, pulseExpansionHandler, notificationWakeUpCoordinator, keyguardBypassController, @@ -372,7 +371,8 @@ public class CarStatusBar extends StatusBar implements CarBatteryController.Batt dozeScrimController, commandQueue, pluginManager, - remoteInputUriController); + remoteInputUriController, + superStatusBarViewFactory); mScrimController = scrimController; mCarNavigationBarController = carNavigationBarController; } diff --git a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java index 9b49ff49864e..b19fae891a58 100644 --- a/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java +++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java @@ -48,6 +48,7 @@ import com.android.systemui.statusbar.NotificationRemoteInputManager; import com.android.systemui.statusbar.NotificationViewHierarchyManager; import com.android.systemui.statusbar.PulseExpansionHandler; import com.android.systemui.statusbar.StatusBarDependenciesModule; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; @@ -85,7 +86,6 @@ import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler; import com.android.systemui.statusbar.policy.RemoteInputUriController; import com.android.systemui.statusbar.policy.UserSwitcherController; import com.android.systemui.statusbar.policy.ZenModeController; -import com.android.systemui.util.InjectionInflationController; import javax.inject.Named; import javax.inject.Singleton; @@ -112,7 +112,6 @@ public class CarStatusBarModule { KeyguardUpdateMonitor keyguardUpdateMonitor, StatusBarIconController statusBarIconController, DozeLog dozeLog, - InjectionInflationController injectionInflationController, PulseExpansionHandler pulseExpansionHandler, NotificationWakeUpCoordinator notificationWakeUpCoordinator, KeyguardBypassController keyguardBypassController, @@ -171,6 +170,7 @@ public class CarStatusBarModule { CommandQueue commandQueue, PluginManager pluginManager, RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory, CarNavigationBarController carNavigationBarController) { return new CarStatusBar( context, @@ -180,7 +180,6 @@ public class CarStatusBarModule { keyguardUpdateMonitor, statusBarIconController, dozeLog, - injectionInflationController, pulseExpansionHandler, notificationWakeUpCoordinator, keyguardBypassController, @@ -239,6 +238,7 @@ public class CarStatusBarModule { commandQueue, pluginManager, remoteInputUriController, + superStatusBarViewFactory, carNavigationBarController); } } diff --git a/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java b/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java index 5dc9061a81a0..de45ea536e27 100644 --- a/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java +++ b/packages/SettingsLib/search/processor-src/com/android/settingslib/search/IndexableProcessor.java @@ -21,7 +21,6 @@ import com.squareup.javapoet.FieldSpec; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterizedTypeName; -import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import java.io.IOException; @@ -73,10 +72,12 @@ public class IndexableProcessor extends AbstractProcessor { } mRanOnce = true; + final ClassName searchIndexableData = ClassName.get(PACKAGE, "SearchIndexableData"); + final FieldSpec providers = FieldSpec.builder( ParameterizedTypeName.get( ClassName.get(Set.class), - TypeName.get(Class.class)), + searchIndexableData), "mProviders", Modifier.PRIVATE, Modifier.FINAL) .initializer("new $T()", HashSet.class) @@ -84,7 +85,7 @@ public class IndexableProcessor extends AbstractProcessor { final MethodSpec addIndex = MethodSpec.methodBuilder("addIndex") .addModifiers(Modifier.PUBLIC) - .addParameter(ClassName.get(Class.class), "indexClass") + .addParameter(searchIndexableData, "indexClass") .addCode("$N.add(indexClass);\n", providers) .build(); @@ -113,19 +114,25 @@ public class IndexableProcessor extends AbstractProcessor { SearchIndexable searchIndexable = element.getAnnotation(SearchIndexable.class); int forTarget = searchIndexable.forTarget(); + MethodSpec.Builder builder = baseConstructorBuilder; + if (forTarget == SearchIndexable.ALL) { - baseConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = baseConstructorBuilder; } else if ((forTarget & SearchIndexable.MOBILE) != 0) { - mobileConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = mobileConstructorBuilder; } else if ((forTarget & SearchIndexable.TV) != 0) { - tvConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = tvConstructorBuilder; } else if ((forTarget & SearchIndexable.WEAR) != 0) { - wearConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = wearConstructorBuilder; } else if ((forTarget & SearchIndexable.AUTO) != 0) { - autoConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = autoConstructorBuilder; } else if ((forTarget & SearchIndexable.ARC) != 0) { - arcConstructorBuilder.addCode("$N($L.class);\n", addIndex, className); + builder = arcConstructorBuilder; } + builder.addCode( + "$N(new SearchIndexableData($L.class, $L" + + ".SEARCH_INDEX_DATA_PROVIDER));\n", + addIndex, className, className); } else { throw new IllegalStateException("Null classname from " + element); } @@ -137,7 +144,7 @@ public class IndexableProcessor extends AbstractProcessor { .addModifiers(Modifier.PUBLIC) .returns(ParameterizedTypeName.get( ClassName.get(Collection.class), - TypeName.get(Class.class))) + searchIndexableData)) .addCode("return $N;\n", providers) .build(); diff --git a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableData.java b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableData.java new file mode 100644 index 000000000000..8b8f2688b93f --- /dev/null +++ b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableData.java @@ -0,0 +1,48 @@ +/* + * Copyright (C) 2019 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.settingslib.search; + +/** + * A Bundle class used in {@link SearchIndexableResources} to provide search Index data. + */ +public class SearchIndexableData { + private final Class mTargetClass; + private final Indexable.SearchIndexProvider mSearchIndexProvider; + + /** + * Constructs a SearchIndexableData + * + * @param targetClass The target opening class of the {@link Indexable.SearchIndexProvider}. It + * should be a {@link android.app.Activity} or fragment {@link + * androidx.fragment.app.Fragment}. + * But fragment is only supported in Android Settings. Other apps should use + * {@link android.app.Activity} + * @param provider provides searchable data for Android Settings + */ + public SearchIndexableData(Class targetClass, Indexable.SearchIndexProvider provider) { + mTargetClass = targetClass; + mSearchIndexProvider = provider; + } + + public Class getTargetClass() { + return mTargetClass; + } + + public Indexable.SearchIndexProvider getSearchIndexProvider() { + return mSearchIndexProvider; + } +} diff --git a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java index 976647b3e88f..e00ca718ce1c 100644 --- a/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java +++ b/packages/SettingsLib/search/src/com/android/settingslib/search/SearchIndexableResources.java @@ -21,15 +21,12 @@ import java.util.Collection; public interface SearchIndexableResources { /** - * Returns a collection of classes that should be indexed for search. - * - * Each class should have the SEARCH_INDEX_DATA_PROVIDER public static member. + * Returns a Collection of {@link SearchIndexableData} that should be indexed for search. */ - Collection<Class> getProviderValues(); + Collection<SearchIndexableData> getProviderValues(); /** - * For testing. Can't use @VisibleForTesting here because this builds as a host binary as well - * as a device binary. + * Add {@link SearchIndexableData} for search in Android Settings. */ - void addIndex(Class indexClass); + void addIndex(SearchIndexableData indexBundle); }
\ No newline at end of file diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java index f5f1fad71b14..84a592d68627 100644 --- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java +++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthBiometricView.java @@ -298,7 +298,10 @@ public abstract class AuthBiometricView extends LinearLayout { .getDimension(R.dimen.biometric_dialog_icon_padding); mIconView.setY(getHeight() - mIconView.getHeight() - iconPadding); - final int newHeight = mIconView.getHeight() + 2 * (int) iconPadding; + // Subtract the vertical padding from the new height since it's only used to create + // extra space between the other elements, and not part of the actual icon. + final int newHeight = mIconView.getHeight() + 2 * (int) iconPadding + - mIconView.getPaddingTop() - mIconView.getPaddingBottom(); mPanelController.updateForContentDimensions(mMediumWidth, newHeight, 0 /* animateDurationMs */); diff --git a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java index 516de709c34f..6b0d3c807079 100644 --- a/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java +++ b/packages/SystemUI/src/com/android/systemui/biometrics/AuthController.java @@ -23,7 +23,10 @@ import android.app.ActivityManager; import android.app.ActivityTaskManager; import android.app.IActivityTaskManager; import android.app.TaskStackListener; +import android.content.BroadcastReceiver; import android.content.Context; +import android.content.Intent; +import android.content.IntentFilter; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.hardware.biometrics.Authenticator; @@ -85,6 +88,28 @@ public class AuthController extends SystemUI implements CommandQueue.Callbacks, } } + @VisibleForTesting + final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() { + @Override + public void onReceive(Context context, Intent intent) { + if (mCurrentDialog != null + && Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(intent.getAction())) { + Log.w(TAG, "ACTION_CLOSE_SYSTEM_DIALOGS received"); + mCurrentDialog.dismissWithoutCallback(true /* animate */); + mCurrentDialog = null; + + try { + if (mReceiver != null) { + mReceiver.onDialogDismissed(BiometricPrompt.DISMISSED_REASON_USER_CANCEL); + mReceiver = null; + } + } catch (RemoteException e) { + Log.e(TAG, "Remote exception", e); + } + } + } + }; + private final Runnable mTaskStackChangedRunnable = () -> { if (mCurrentDialog != null) { try { @@ -204,6 +229,11 @@ public class AuthController extends SystemUI implements CommandQueue.Callbacks, super(context); mCommandQueue = commandQueue; mInjector = injector; + + IntentFilter filter = new IntentFilter(); + filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); + + context.registerReceiver(mBroadcastReceiver, filter); } @Override diff --git a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java index 264d644f9057..46358841c70f 100644 --- a/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java +++ b/packages/SystemUI/src/com/android/systemui/screenshot/GlobalScreenshot.java @@ -101,6 +101,7 @@ import java.io.OutputStream; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; +import java.util.Optional; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @@ -109,6 +110,7 @@ import java.util.function.Function; import javax.inject.Inject; import javax.inject.Singleton; +import dagger.Lazy; /** * POD used in the AsyncTask which saves an image in the background. @@ -1041,8 +1043,9 @@ public class GlobalScreenshot { private final StatusBar mStatusBar; @Inject - public ActionProxyReceiver(StatusBar statusBar) { - mStatusBar = statusBar; + public ActionProxyReceiver(Optional<Lazy<StatusBar>> statusBarLazy) { + Lazy<StatusBar> statusBar = statusBarLazy.orElse(null); + mStatusBar = statusBar != null ? statusBar.get() : null; } @Override @@ -1067,8 +1070,13 @@ public class GlobalScreenshot { context.startActivityAsUser(actionIntent, opts.toBundle(), UserHandle.CURRENT); }; - mStatusBar.executeRunnableDismissingKeyguard(startActivityRunnable, null, - true /* dismissShade */, true /* afterKeyguardGone */, true /* deferred */); + if (mStatusBar != null) { + mStatusBar.executeRunnableDismissingKeyguard(startActivityRunnable, null, + true /* dismissShade */, true /* afterKeyguardGone */, + true /* deferred */); + } else { + startActivityRunnable.run(); + } } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/SuperStatusBarViewFactory.java b/packages/SystemUI/src/com/android/systemui/statusbar/SuperStatusBarViewFactory.java new file mode 100644 index 000000000000..bc7c22d65a44 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/SuperStatusBarViewFactory.java @@ -0,0 +1,92 @@ +/* + * Copyright (C) 2019 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; + +import android.content.Context; +import android.view.LayoutInflater; +import android.view.ViewGroup; + +import com.android.systemui.R; +import com.android.systemui.statusbar.phone.StatusBarWindowView; +import com.android.systemui.util.InjectionInflationController; + +import javax.inject.Inject; +import javax.inject.Singleton; + +/** + * Creates a single instance of super_status_bar that can be shared across various system ui + * objects. + */ +@Singleton +public class SuperStatusBarViewFactory { + + private final Context mContext; + private final InjectionInflationController mInjectionInflationController; + + private StatusBarWindowView mStatusBarWindowView; + private NotificationShelf mNotificationShelf; + + @Inject + public SuperStatusBarViewFactory(Context context, + InjectionInflationController injectionInflationController) { + mContext = context; + mInjectionInflationController = injectionInflationController; + } + + /** + * Gets the inflated {@link StatusBarWindowView} from {@link R.layout#super_status_bar}. Returns + * a cached instance, if it has already been inflated. + */ + public StatusBarWindowView getStatusBarWindowView() { + if (mStatusBarWindowView != null) { + return mStatusBarWindowView; + } + + mStatusBarWindowView = (StatusBarWindowView) mInjectionInflationController.injectable( + LayoutInflater.from(mContext)).inflate(R.layout.super_status_bar, + /* root= */ null); + if (mStatusBarWindowView == null) { + throw new IllegalStateException( + "R.layout.super_status_bar could not be properly inflated"); + } + return mStatusBarWindowView; + } + + /** + * Gets the inflated {@link NotificationShelf} from + * {@link R.layout#status_bar_notification_shelf}. + * Returns a cached instance, if it has already been inflated. + * + * @param container the expected container to hold the {@link NotificationShelf}. The view + * isn't immediately attached, but the layout params of this view is used + * during inflation. + */ + public NotificationShelf getNotificationShelf(ViewGroup container) { + if (mNotificationShelf != null) { + return mNotificationShelf; + } + + mNotificationShelf = (NotificationShelf) mInjectionInflationController.injectable( + LayoutInflater.from(mContext)).inflate(R.layout.status_bar_notification_shelf, + container, /* attachToRoot= */ false); + if (mNotificationShelf == null) { + throw new IllegalStateException( + "R.layout.status_bar_notification_shelf could not be properly inflated"); + } + return mNotificationShelf; + } +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java index 09632ae5129f..b0104d65a278 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBar.java @@ -75,7 +75,6 @@ import android.content.pm.IPackageManager; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Configuration; -import android.content.res.Resources; import android.graphics.Point; import android.graphics.PointF; import android.media.AudioAttributes; @@ -109,7 +108,6 @@ import android.view.Display; import android.view.IWindowManager; import android.view.InsetsState.InternalInsetType; import android.view.KeyEvent; -import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.RemoteAnimationAdapter; import android.view.ThreadedRenderer; @@ -201,6 +199,7 @@ import com.android.systemui.statusbar.NotificationViewHierarchyManager; import com.android.systemui.statusbar.PulseExpansionHandler; import com.android.systemui.statusbar.ScrimView; import com.android.systemui.statusbar.StatusBarState; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.ActivityLaunchAnimator; @@ -242,7 +241,6 @@ import com.android.systemui.statusbar.policy.UserInfoController; import com.android.systemui.statusbar.policy.UserInfoControllerImpl; import com.android.systemui.statusbar.policy.UserSwitcherController; import com.android.systemui.statusbar.policy.ZenModeController; -import com.android.systemui.util.InjectionInflationController; import com.android.systemui.volume.VolumeComponent; import java.io.FileDescriptor; @@ -363,8 +361,6 @@ public class StatusBar extends SystemUI implements DemoMode, @Nullable private final KeyguardLiftController mKeyguardLiftController; - private int mNaturalBarHeight = -1; - private final Point mCurrentDisplaySize = new Point(); protected StatusBarWindowViewController mStatusBarWindowViewController; @@ -383,7 +379,6 @@ public class StatusBar extends SystemUI implements DemoMode, private final FeatureFlags mFeatureFlags; private final StatusBarIconController mIconController; private final DozeLog mDozeLog; - private final InjectionInflationController mInjectionInflater; private final PulseExpansionHandler mPulseExpansionHandler; private final NotificationWakeUpCoordinator mWakeUpCoordinator; private final KeyguardBypassController mKeyguardBypassController; @@ -402,6 +397,7 @@ public class StatusBar extends SystemUI implements DemoMode, private final Lazy<BiometricUnlockController> mBiometricUnlockControllerLazy; private final PluginManager mPluginManager; private final RemoteInputUriController mRemoteInputUriController; + private final SuperStatusBarViewFactory mSuperStatusBarViewFactory; // expanded notifications protected NotificationPanelView mNotificationPanel; // the sliding/resizing panel within the notification window @@ -646,7 +642,6 @@ public class StatusBar extends SystemUI implements DemoMode, KeyguardUpdateMonitor keyguardUpdateMonitor, StatusBarIconController statusBarIconController, DozeLog dozeLog, - InjectionInflationController injectionInflationController, PulseExpansionHandler pulseExpansionHandler, NotificationWakeUpCoordinator notificationWakeUpCoordinator, KeyguardBypassController keyguardBypassController, @@ -705,7 +700,8 @@ public class StatusBar extends SystemUI implements DemoMode, DozeScrimController dozeScrimController, CommandQueue commandQueue, PluginManager pluginManager, - RemoteInputUriController remoteInputUriController) { + RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory) { super(context); mFeatureFlags = featureFlags; mLightBarController = lightBarController; @@ -713,7 +709,6 @@ public class StatusBar extends SystemUI implements DemoMode, mKeyguardUpdateMonitor = keyguardUpdateMonitor; mIconController = statusBarIconController; mDozeLog = dozeLog; - mInjectionInflater = injectionInflationController; mPulseExpansionHandler = pulseExpansionHandler; mWakeUpCoordinator = notificationWakeUpCoordinator; mKeyguardBypassController = keyguardBypassController; @@ -773,6 +768,8 @@ public class StatusBar extends SystemUI implements DemoMode, mCommandQueue = commandQueue; mPluginManager = pluginManager; mRemoteInputUriController = remoteInputUriController; + mSuperStatusBarViewFactory = superStatusBarViewFactory; + mBubbleExpandListener = (isExpanding, key) -> { mEntryManager.updateNotifications("onBubbleExpandChanged"); @@ -1367,10 +1364,7 @@ public class StatusBar extends SystemUI implements DemoMode, } private void inflateShelf() { - mNotificationShelf = - (NotificationShelf) mInjectionInflater.injectable( - LayoutInflater.from(mContext)).inflate( - R.layout.status_bar_notification_shelf, mStackScroller, false); + mNotificationShelf = mSuperStatusBarViewFactory.getNotificationShelf(mStackScroller); mNotificationShelf.setOnClickListener(mGoToLockedShadeListener); } @@ -1428,10 +1422,8 @@ public class StatusBar extends SystemUI implements DemoMode, } protected void inflateStatusBarWindow(Context context) { - mStatusBarWindow = (StatusBarWindowView) mInjectionInflater.injectable( - LayoutInflater.from(context)).inflate(R.layout.super_status_bar, null); + mStatusBarWindow = mSuperStatusBarViewFactory.getStatusBarWindowView(); mStatusBarWindowViewController = mStatusBarWindowViewControllerBuilder - .setStatusBarWindowView(mStatusBarWindow) .setShadeController(this) .build(); } @@ -1469,12 +1461,7 @@ public class StatusBar extends SystemUI implements DemoMode, } public int getStatusBarHeight() { - if (mNaturalBarHeight < 0) { - final Resources res = mContext.getResources(); - mNaturalBarHeight = - res.getDimensionPixelSize(com.android.internal.R.dimen.status_bar_height); - } - return mNaturalBarHeight; + return mStatusBarWindowController.getStatusBarHeight(); } protected boolean toggleSplitScreenMode(int metricsDockAction, int metricsUndockAction) { @@ -2648,7 +2635,7 @@ public class StatusBar extends SystemUI implements DemoMode, public void createAndAddWindows(@Nullable RegisterStatusBarResult result) { makeStatusBarView(result); - mStatusBarWindowController.add(mStatusBarWindow, getStatusBarHeight()); + mStatusBarWindowController.attach(); } // called by makeStatusbar and also by PhoneStatusBarView @@ -2926,7 +2913,7 @@ public class StatusBar extends SystemUI implements DemoMode, mQSPanel.updateResources(); } - loadDimens(); + mStatusBarWindowController.refreshStatusBarHeight(); if (mStatusBarView != null) { mStatusBarView.updateResources(); @@ -2939,19 +2926,6 @@ public class StatusBar extends SystemUI implements DemoMode, } } - protected void loadDimens() { - final Resources res = mContext.getResources(); - - int oldBarHeight = mNaturalBarHeight; - mNaturalBarHeight = res.getDimensionPixelSize( - com.android.internal.R.dimen.status_bar_height); - if (mStatusBarWindowController != null && mNaturalBarHeight != oldBarHeight) { - mStatusBarWindowController.setBarHeight(mNaturalBarHeight); - } - - if (DEBUG) Log.v(TAG, "defineSlots"); - } - // Visibility reporting protected void handleVisibleToUserChanged(boolean visibleToUser) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java index 6b7c6b387b38..67f6a0ca6b72 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java @@ -49,6 +49,7 @@ import com.android.systemui.statusbar.NotificationRemoteInputManager; import com.android.systemui.statusbar.NotificationViewHierarchyManager; import com.android.systemui.statusbar.PulseExpansionHandler; import com.android.systemui.statusbar.StatusBarDependenciesModule; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; @@ -71,7 +72,6 @@ import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler; import com.android.systemui.statusbar.policy.RemoteInputUriController; import com.android.systemui.statusbar.policy.UserSwitcherController; import com.android.systemui.statusbar.policy.ZenModeController; -import com.android.systemui.util.InjectionInflationController; import javax.inject.Named; import javax.inject.Singleton; @@ -98,7 +98,6 @@ public class StatusBarModule { KeyguardUpdateMonitor keyguardUpdateMonitor, StatusBarIconController statusBarIconController, DozeLog dozeLog, - InjectionInflationController injectionInflationController, PulseExpansionHandler pulseExpansionHandler, NotificationWakeUpCoordinator notificationWakeUpCoordinator, KeyguardBypassController keyguardBypassController, @@ -157,7 +156,8 @@ public class StatusBarModule { DozeScrimController dozeScrimController, CommandQueue commandQueue, PluginManager pluginManager, - RemoteInputUriController remoteInputUriController) { + RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory) { return new StatusBar( context, featureFlags, @@ -166,7 +166,6 @@ public class StatusBarModule { keyguardUpdateMonitor, statusBarIconController, dozeLog, - injectionInflationController, pulseExpansionHandler, notificationWakeUpCoordinator, keyguardBypassController, @@ -225,6 +224,7 @@ public class StatusBarModule { dozeScrimController, commandQueue, pluginManager, - remoteInputUriController); + remoteInputUriController, + superStatusBarViewFactory); } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java index ca7a936d58f7..2ecceba2116a 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowController.java @@ -41,11 +41,13 @@ import android.view.WindowManager.LayoutParams; import com.android.systemui.Dumpable; import com.android.systemui.R; import com.android.systemui.colorextraction.SysuiColorExtractor; +import com.android.systemui.dagger.qualifiers.MainResources; import com.android.systemui.keyguard.KeyguardViewMediator; import com.android.systemui.plugins.statusbar.StatusBarStateController; import com.android.systemui.plugins.statusbar.StatusBarStateController.StateListener; import com.android.systemui.statusbar.RemoteInputController.Callback; import com.android.systemui.statusbar.StatusBarState; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.policy.ConfigurationController; import com.android.systemui.statusbar.policy.ConfigurationController.ConfigurationListener; @@ -69,6 +71,7 @@ import javax.inject.Singleton; public class StatusBarWindowController implements Callback, Dumpable, ConfigurationListener { private static final String TAG = "StatusBarWindowController"; + private static final boolean DEBUG = false; private final Context mContext; private final WindowManager mWindowManager; @@ -83,7 +86,7 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat private LayoutParams mLp; private boolean mHasTopUi; private boolean mHasTopUiChanged; - private int mBarHeight; + private int mBarHeight = -1; private float mScreenBrightnessDoze; private final State mCurrentState = new State(); private OtherwisedCollapsedListener mListener; @@ -92,13 +95,17 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat mCallbacks = Lists.newArrayList(); private final SysuiColorExtractor mColorExtractor; + private final SuperStatusBarViewFactory mSuperStatusBarViewFactory; + private final Resources mResources; @Inject public StatusBarWindowController(Context context, WindowManager windowManager, IActivityManager activityManager, DozeParameters dozeParameters, StatusBarStateController statusBarStateController, ConfigurationController configurationController, - KeyguardBypassController keyguardBypassController, SysuiColorExtractor colorExtractor) { + KeyguardBypassController keyguardBypassController, SysuiColorExtractor colorExtractor, + SuperStatusBarViewFactory superStatusBarViewFactory, + @MainResources Resources resources) { mContext = context; mWindowManager = windowManager; mActivityManager = activityManager; @@ -108,6 +115,15 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat mLpChanged = new LayoutParams(); mKeyguardBypassController = keyguardBypassController; mColorExtractor = colorExtractor; + mSuperStatusBarViewFactory = superStatusBarViewFactory; + mStatusBarView = mSuperStatusBarViewFactory.getStatusBarWindowView(); + mResources = resources; + + if (mBarHeight < 0) { + mBarHeight = mResources.getDimensionPixelSize( + com.android.internal.R.dimen.status_bar_height); + } + mLockScreenDisplayTimeout = context.getResources() .getInteger(R.integer.config_lockScreenDisplayTimeout); ((SysuiStatusBarStateController) statusBarStateController) @@ -149,20 +165,36 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat || res.getBoolean(R.bool.config_enableLockScreenRotation); } + public int getStatusBarHeight() { + return mBarHeight; + } + /** - * Adds the status bar view to the window manager. - * - * @param statusBarView The view to add. - * @param barHeight The height of the status bar in collapsed state. + * Rereads the status_bar_height from configuration and reapplys the current state if the height + * is different. */ - public void add(ViewGroup statusBarView, int barHeight) { + public void refreshStatusBarHeight() { + int heightFromConfig = mResources.getDimensionPixelSize( + com.android.internal.R.dimen.status_bar_height); + + if (mBarHeight != heightFromConfig) { + mBarHeight = heightFromConfig; + apply(mCurrentState); + } + if (DEBUG) Log.v(TAG, "defineSlots"); + } + + /** + * Adds the status bar view to the window manager. + */ + public void attach() { // Now that the status bar window encompasses the sliding panel and its // translucent backdrop, the entire thing is made TRANSLUCENT and is // hardware-accelerated. mLp = new LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, - barHeight, + mBarHeight, LayoutParams.TYPE_STATUS_BAR, LayoutParams.FLAG_NOT_FOCUSABLE | LayoutParams.FLAG_TOUCHABLE_WHEN_WAKING @@ -176,8 +208,6 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat mLp.setTitle("StatusBar"); mLp.packageName = mContext.getPackageName(); mLp.layoutInDisplayCutoutMode = LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS; - mStatusBarView = statusBarView; - mBarHeight = barHeight; mWindowManager.addView(mStatusBarView, mLp); mLpChanged.copyFrom(mLp); onThemeChanged(); @@ -534,11 +564,6 @@ public class StatusBarWindowController implements Callback, Dumpable, Configurat apply(mCurrentState); } - public void setBarHeight(int barHeight) { - mBarHeight = barHeight; - apply(mCurrentState); - } - public void setForcePluginOpen(boolean forcePluginOpen) { mCurrentState.forcePluginOpen = forcePluginOpen; apply(mCurrentState); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java index b7ada5d35a08..f716443cbfe1 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarWindowViewController.java @@ -43,6 +43,7 @@ import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.DragDownHelper; import com.android.systemui.statusbar.NotificationLockscreenUserManager; import com.android.systemui.statusbar.PulseExpansionHandler; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.notification.DynamicPrivacyController; import com.android.systemui.statusbar.notification.NotificationEntryManager; @@ -492,7 +493,8 @@ public class StatusBarWindowViewController { private final DozeLog mDozeLog; private final DozeParameters mDozeParameters; private final CommandQueue mCommandQueue; - private StatusBarWindowView mView; + private final SuperStatusBarViewFactory mSuperStatusBarViewFactory; + private final StatusBarWindowView mView; @Inject public Builder( @@ -510,7 +512,8 @@ public class StatusBarWindowViewController { StatusBarStateController statusBarStateController, DozeLog dozeLog, DozeParameters dozeParameters, - CommandQueue commandQueue) { + CommandQueue commandQueue, + SuperStatusBarViewFactory superStatusBarViewFactory) { mInjectionInflationController = injectionInflationController; mCoordinator = coordinator; mPulseExpansionHandler = pulseExpansionHandler; @@ -526,14 +529,9 @@ public class StatusBarWindowViewController { mDozeLog = dozeLog; mDozeParameters = dozeParameters; mCommandQueue = commandQueue; - } + mSuperStatusBarViewFactory = superStatusBarViewFactory; - /** - * Provide {@link StatusBarWindowView} to attach this controller to. - */ - public Builder setStatusBarWindowView(StatusBarWindowView view) { - mView = view; - return this; + mView = mSuperStatusBarViewFactory.getStatusBarWindowView(); } /** diff --git a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java index c215a43e0f3e..486fa12e0577 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/biometrics/AuthControllerTest.java @@ -35,6 +35,7 @@ import android.app.ActivityManager; import android.app.IActivityTaskManager; import android.content.ComponentName; import android.content.Context; +import android.content.Intent; import android.content.pm.PackageManager; import android.content.res.Configuration; import android.hardware.biometrics.Authenticator; @@ -403,6 +404,19 @@ public class AuthControllerTest extends SysuiTestCase { mAuthController.onDeviceCredentialPressed(); } + @Test + public void testActionCloseSystemDialogs_dismissesDialogIfShowing() throws Exception { + showDialog(Authenticator.TYPE_BIOMETRIC, BiometricPrompt.TYPE_FACE); + Intent intent = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS); + mAuthController.mBroadcastReceiver.onReceive(mContext, intent); + waitForIdleSync(); + + assertNull(mAuthController.mCurrentDialog); + assertNull(mAuthController.mReceiver); + verify(mDialog1).dismissWithoutCallback(true /* animate */); + verify(mReceiver).onDialogDismissed(eq(BiometricPrompt.DISMISSED_REASON_USER_CANCEL)); + } + // Helpers private void showDialog(int authenticators, int biometricModality) { diff --git a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java index 00681130074b..b1a6bc6d41fd 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/bubbles/BubbleControllerTest.java @@ -46,18 +46,19 @@ import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; +import android.content.res.Resources; import android.graphics.drawable.Icon; import android.hardware.face.FaceManager; import android.service.notification.ZenModeConfig; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper; import android.view.WindowManager; -import android.widget.FrameLayout; import androidx.test.filters.SmallTest; import com.android.internal.colorextraction.ColorExtractor; import com.android.systemui.R; +import com.android.systemui.SystemUIFactory; import com.android.systemui.SysuiTestCase; import com.android.systemui.colorextraction.SysuiColorExtractor; import com.android.systemui.plugins.statusbar.StatusBarStateController; @@ -65,6 +66,7 @@ import com.android.systemui.statusbar.NotificationLockscreenUserManager; import com.android.systemui.statusbar.NotificationPresenter; import com.android.systemui.statusbar.NotificationRemoveInterceptor; import com.android.systemui.statusbar.NotificationTestHelper; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.notification.NotificationEntryListener; import com.android.systemui.statusbar.notification.NotificationEntryManager; @@ -81,6 +83,7 @@ import com.android.systemui.statusbar.policy.BatteryController; import com.android.systemui.statusbar.policy.ConfigurationController; import com.android.systemui.statusbar.policy.HeadsUpManager; import com.android.systemui.statusbar.policy.ZenModeController; +import com.android.systemui.util.InjectionInflationController; import org.junit.Before; import org.junit.Test; @@ -119,7 +122,6 @@ public class BubbleControllerTest extends SysuiTestCase { @Mock private KeyguardBypassController mKeyguardBypassController; - private FrameLayout mStatusBarView; @Captor private ArgumentCaptor<NotificationEntryListener> mEntryListenerCaptor; @Captor @@ -147,22 +149,28 @@ public class BubbleControllerTest extends SysuiTestCase { private SysuiColorExtractor mColorExtractor; @Mock ColorExtractor.GradientColors mGradientColors; + @Mock + private Resources mResources; + private SuperStatusBarViewFactory mSuperStatusBarViewFactory; private BubbleData mBubbleData; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); - mStatusBarView = new FrameLayout(mContext); mDependency.injectTestDependency(NotificationEntryManager.class, mNotificationEntryManager); mContext.addMockSystemService(FaceManager.class, mFaceManager); when(mColorExtractor.getNeutralColors()).thenReturn(mGradientColors); + mSuperStatusBarViewFactory = new SuperStatusBarViewFactory(mContext, + new InjectionInflationController(SystemUIFactory.getInstance().getRootComponent())); + // Bubbles get added to status bar window view mStatusBarWindowController = new StatusBarWindowController(mContext, mWindowManager, mActivityManager, mDozeParameters, mStatusBarStateController, - mConfigurationController, mKeyguardBypassController, mColorExtractor); - mStatusBarWindowController.add(mStatusBarView, 120 /* height */); + mConfigurationController, mKeyguardBypassController, mColorExtractor, + mSuperStatusBarViewFactory, mResources); + mStatusBarWindowController.attach(); // Need notifications for bubbles mNotificationTestHelper = new NotificationTestHelper(mContext, mDependency); diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java index c21e3ab079ff..ecb2d8190cfc 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarTest.java @@ -107,6 +107,7 @@ import com.android.systemui.statusbar.PulseExpansionHandler; import com.android.systemui.statusbar.RemoteInputController; import com.android.systemui.statusbar.StatusBarState; import com.android.systemui.statusbar.StatusBarStateControllerImpl; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; import com.android.systemui.statusbar.notification.DynamicPrivacyController; @@ -134,7 +135,6 @@ import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler; import com.android.systemui.statusbar.policy.RemoteInputUriController; import com.android.systemui.statusbar.policy.UserSwitcherController; import com.android.systemui.statusbar.policy.ZenModeController; -import com.android.systemui.util.InjectionInflationController; import org.junit.Before; import org.junit.Test; @@ -208,7 +208,6 @@ public class StatusBarTest extends SysuiTestCase { @Mock private PulseExpansionHandler mPulseExpansionHandler; @Mock private NotificationWakeUpCoordinator mNotificationWakeUpCoordinator; @Mock private KeyguardBypassController mKeyguardBypassController; - @Mock private InjectionInflationController mInjectionInflationController; @Mock private DynamicPrivacyController mDynamicPrivacyController; @Mock private NewNotifPipeline mNewNotifPipeline; @Mock private ZenModeController mZenModeController; @@ -234,6 +233,7 @@ public class StatusBarTest extends SysuiTestCase { @Mock private KeyguardLiftController mKeyguardLiftController; @Mock private CommandQueue mCommandQueue; @Mock private PluginManager mPluginManager; + @Mock private SuperStatusBarViewFactory mSuperStatusBarViewFactory; @Before public void setup() throws Exception { @@ -309,7 +309,6 @@ public class StatusBarTest extends SysuiTestCase { mKeyguardUpdateMonitor, mStatusBarIconController, mDozeLog, - mInjectionInflationController, mPulseExpansionHandler, mNotificationWakeUpCoordinator, mKeyguardBypassController, @@ -372,7 +371,8 @@ public class StatusBarTest extends SysuiTestCase { mDozeScrimController, mCommandQueue, mPluginManager, - mRemoteInputUriController); + mRemoteInputUriController, + mSuperStatusBarViewFactory); when(mStatusBarWindowView.findViewById(R.id.lock_icon_container)).thenReturn( mLockIconContainer); diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java index a21a658348c4..147edf6589e9 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowControllerTest.java @@ -25,9 +25,9 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.app.IActivityManager; +import android.content.res.Resources; import android.testing.AndroidTestingRunner; import android.testing.TestableLooper.RunWithLooper; -import android.view.ViewGroup; import android.view.WindowManager; import androidx.test.filters.SmallTest; @@ -35,6 +35,7 @@ import androidx.test.filters.SmallTest; import com.android.internal.colorextraction.ColorExtractor; import com.android.systemui.SysuiTestCase; import com.android.systemui.colorextraction.SysuiColorExtractor; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.policy.ConfigurationController; @@ -52,13 +53,15 @@ public class StatusBarWindowControllerTest extends SysuiTestCase { @Mock private WindowManager mWindowManager; @Mock private DozeParameters mDozeParameters; - @Mock private ViewGroup mStatusBarView; + @Mock private StatusBarWindowView mStatusBarView; @Mock private IActivityManager mActivityManager; @Mock private SysuiStatusBarStateController mStatusBarStateController; @Mock private ConfigurationController mConfigurationController; @Mock private KeyguardBypassController mKeyguardBypassController; @Mock private SysuiColorExtractor mColorExtractor; @Mock ColorExtractor.GradientColors mGradientColors; + @Mock private SuperStatusBarViewFactory mSuperStatusBarViewFactory; + @Mock private Resources mResources; private StatusBarWindowController mStatusBarWindowController; @@ -67,11 +70,14 @@ public class StatusBarWindowControllerTest extends SysuiTestCase { MockitoAnnotations.initMocks(this); when(mDozeParameters.getAlwaysOn()).thenReturn(true); when(mColorExtractor.getNeutralColors()).thenReturn(mGradientColors); + when(mSuperStatusBarViewFactory.getStatusBarWindowView()).thenReturn(mStatusBarView); mStatusBarWindowController = new StatusBarWindowController(mContext, mWindowManager, mActivityManager, mDozeParameters, mStatusBarStateController, - mConfigurationController, mKeyguardBypassController, mColorExtractor); - mStatusBarWindowController.add(mStatusBarView, 100 /* height */); + mConfigurationController, mKeyguardBypassController, mColorExtractor, + mSuperStatusBarViewFactory, mResources); + + mStatusBarWindowController.attach(); } @Test diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java index 20fb6599f66e..bf81325eb6f8 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/phone/StatusBarWindowViewTest.java @@ -35,6 +35,7 @@ import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.DragDownHelper; import com.android.systemui.statusbar.NotificationLockscreenUserManager; import com.android.systemui.statusbar.PulseExpansionHandler; +import com.android.systemui.statusbar.SuperStatusBarViewFactory; import com.android.systemui.statusbar.SysuiStatusBarStateController; import com.android.systemui.statusbar.notification.DynamicPrivacyController; import com.android.systemui.statusbar.notification.NotificationEntryManager; @@ -72,6 +73,7 @@ public class StatusBarWindowViewTest extends SysuiTestCase { @Mock private StatusBar mStatusBar; @Mock private DozeLog mDozeLog; @Mock private DozeParameters mDozeParameters; + @Mock private SuperStatusBarViewFactory mSuperStatusBarViewFactory; @Before public void setUp() { @@ -82,6 +84,8 @@ public class StatusBarWindowViewTest extends SysuiTestCase { when(mStatusBar.isDozing()).thenReturn(false); mDependency.injectTestDependency(ShadeController.class, mShadeController); + when(mSuperStatusBarViewFactory.getStatusBarWindowView()).thenReturn(mView); + mController = new StatusBarWindowViewController.Builder( new InjectionInflationController( SystemUIFactory.getInstance().getRootComponent()), @@ -98,9 +102,9 @@ public class StatusBarWindowViewTest extends SysuiTestCase { mStatusBarStateController, mDozeLog, mDozeParameters, - new CommandQueue(mContext)) + new CommandQueue(mContext), + mSuperStatusBarViewFactory) .setShadeController(mShadeController) - .setStatusBarWindowView(mView) .build(); mController.setService(mStatusBar); mController.setDragDownHelper(mDragDownHelper); diff --git a/services/core/java/com/android/server/AlarmManagerInternal.java b/services/core/java/com/android/server/AlarmManagerInternal.java index 5b0de5e2aae0..0a735029eead 100644 --- a/services/core/java/com/android/server/AlarmManagerInternal.java +++ b/services/core/java/com/android/server/AlarmManagerInternal.java @@ -16,6 +16,8 @@ package com.android.server; +import android.app.PendingIntent; + public interface AlarmManagerInternal { // Some other components in the system server need to know about // broadcast alarms currently in flight @@ -30,4 +32,10 @@ public interface AlarmManagerInternal { boolean isIdling(); public void removeAlarmsForUid(int uid); public void registerInFlightListener(InFlightListener callback); + + /** + * Removes any alarm with the given pending intent with equality determined using + * {@link android.app.PendingIntent#equals(java.lang.Object) PendingIntent.equals} + */ + void remove(PendingIntent rec); } diff --git a/services/core/java/com/android/server/AlarmManagerService.java b/services/core/java/com/android/server/AlarmManagerService.java index e757b4e1a070..e4d477a03afc 100644 --- a/services/core/java/com/android/server/AlarmManagerService.java +++ b/services/core/java/com/android/server/AlarmManagerService.java @@ -213,7 +213,6 @@ class AlarmManagerService extends SystemService { IAlarmListener mTimeTickTrigger; PendingIntent mDateChangeSender; Random mRandom; - PendingIntent.CancelListener mOperationCancelListener; boolean mInteractive = true; long mNonInteractiveStartTime; long mNonInteractiveTime; @@ -1460,7 +1459,6 @@ class AlarmManagerService extends SystemService { synchronized (mLock) { mHandler = new AlarmHandler(); - mOperationCancelListener = (intent) -> removeImpl(intent, null); mConstants = new Constants(mHandler); mAppWakeupHistory = new AppWakeupHistory(Constants.DEFAULT_APP_STANDBY_WINDOW); @@ -1715,9 +1713,6 @@ class AlarmManagerService extends SystemService { } else { maxElapsed = triggerElapsed + windowLength; } - if (operation != null) { - operation.registerCancelListener(mOperationCancelListener); - } synchronized (mLock) { if (DEBUG_BATCH) { Slog.v(TAG, "set(" + operation + ") : type=" + type @@ -1730,8 +1725,6 @@ class AlarmManagerService extends SystemService { "Maximum limit of concurrent alarms " + mConstants.MAX_ALARMS_PER_UID + " reached for uid: " + UserHandle.formatUid(callingUid) + ", callingPackage: " + callingPackage; - mHandler.obtainMessage(AlarmHandler.UNREGISTER_CANCEL_LISTENER, - operation).sendToTarget(); Slog.w(TAG, errorMsg); throw new IllegalStateException(errorMsg); } @@ -1752,8 +1745,6 @@ class AlarmManagerService extends SystemService { if (ActivityManager.getService().isAppStartModeDisabled(callingUid, callingPackage)) { Slog.w(TAG, "Not setting alarm from " + callingUid + ":" + a + " -- package not allowed to start"); - mHandler.obtainMessage(AlarmHandler.UNREGISTER_CANCEL_LISTENER, - operation).sendToTarget(); return; } } catch (RemoteException e) { @@ -1970,6 +1961,11 @@ class AlarmManagerService extends SystemService { } @Override + public void remove(PendingIntent pi) { + mHandler.obtainMessage(AlarmHandler.REMOVE_FOR_CANCELED, pi).sendToTarget(); + } + + @Override public void registerInFlightListener(InFlightListener callback) { synchronized (mLock) { mInFlightListeners.add(callback); @@ -2074,8 +2070,6 @@ class AlarmManagerService extends SystemService { synchronized (mLock) { removeLocked(operation, listener); } - mHandler.obtainMessage(AlarmHandler.UNREGISTER_CANCEL_LISTENER, - operation).sendToTarget(); } @Override @@ -4078,7 +4072,7 @@ class AlarmManagerService extends SystemService { public static final int APP_STANDBY_BUCKET_CHANGED = 5; public static final int CHARGING_STATUS_CHANGED = 6; public static final int REMOVE_FOR_STOPPED = 7; - public static final int UNREGISTER_CANCEL_LISTENER = 8; + public static final int REMOVE_FOR_CANCELED = 8; AlarmHandler() { super(Looper.myLooper()); @@ -4161,10 +4155,10 @@ class AlarmManagerService extends SystemService { } break; - case UNREGISTER_CANCEL_LISTENER: - final PendingIntent pi = (PendingIntent) msg.obj; - if (pi != null) { - pi.unregisterCancelListener(mOperationCancelListener); + case REMOVE_FOR_CANCELED: + final PendingIntent operation = (PendingIntent) msg.obj; + synchronized (mLock) { + removeLocked(operation, null); } break; @@ -4644,11 +4638,6 @@ class AlarmManagerService extends SystemService { Intent.EXTRA_ALARM_COUNT, alarm.count), mDeliveryTracker, mHandler, null, allowWhileIdle ? mIdleOptions : null); - if (alarm.repeatInterval == 0) { - // Keep the listener for repeating alarms until they get cancelled - mHandler.obtainMessage(AlarmHandler.UNREGISTER_CANCEL_LISTENER, - alarm.operation).sendToTarget(); - } } catch (PendingIntent.CanceledException e) { if (alarm.repeatInterval > 0) { // This IntentSender is no longer valid, but this diff --git a/services/core/java/com/android/server/LocationManagerService.java b/services/core/java/com/android/server/LocationManagerService.java index 39f039af330c..e1f65979bec3 100644 --- a/services/core/java/com/android/server/LocationManagerService.java +++ b/services/core/java/com/android/server/LocationManagerService.java @@ -43,7 +43,6 @@ import android.content.pm.PackageManager.NameNotFoundException; import android.content.pm.ResolveInfo; import android.content.pm.Signature; import android.content.res.Resources; -import android.database.ContentObserver; import android.hardware.location.ActivityRecognitionHardware; import android.location.Address; import android.location.Criteria; @@ -79,7 +78,6 @@ import android.os.WorkSource.WorkChain; import android.provider.Settings; import android.stats.location.LocationStatsEnums; import android.text.TextUtils; -import android.util.ArraySet; import android.util.EventLog; import android.util.Log; import android.util.Slog; @@ -99,12 +97,12 @@ import com.android.server.location.CallerIdentity; import com.android.server.location.GeocoderProxy; import com.android.server.location.GeofenceManager; import com.android.server.location.GeofenceProxy; -import com.android.server.location.LocationBlacklist; import com.android.server.location.LocationFudger; import com.android.server.location.LocationProviderProxy; import com.android.server.location.LocationRequestStatistics; import com.android.server.location.LocationRequestStatistics.PackageProviderKey; import com.android.server.location.LocationRequestStatistics.PackageStatistics; +import com.android.server.location.LocationSettingsStore; import com.android.server.location.MockProvider; import com.android.server.location.PassiveProvider; import com.android.server.pm.permission.PermissionManagerServiceInternal; @@ -183,13 +181,6 @@ public class LocationManagerService extends ILocationManager.Stub { private static final int FOREGROUND_IMPORTANCE_CUTOFF = ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND_SERVICE; - // default background throttling interval if not overriden in settings - private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000; - - // Default value for maximum age of last location returned to applications with foreground-only - // location permissions. - private static final long DEFAULT_LAST_LOCATION_MAX_AGE_MS = 20 * 60 * 1000; - // Location Providers may sometimes deliver location updates // slightly faster that requested - provide grace period so // we don't unnecessarily filter events that are otherwise on @@ -208,13 +199,14 @@ public class LocationManagerService extends ILocationManager.Stub { private ActivityManager mActivityManager; private UserManager mUserManager; + private LocationSettingsStore mSettingsStore; + private GeofenceManager mGeofenceManager; private LocationFudger mLocationFudger; private GeocoderProxy mGeocodeProvider; @Nullable private GnssManagerService mGnssManagerService; private PassiveProvider mPassiveProvider; // track passive provider for special cases - private LocationBlacklist mBlacklist; @GuardedBy("mLock") private String mExtraLocationControllerPackage; private boolean mExtraLocationControllerPackageEnabled; @@ -245,10 +237,6 @@ public class LocationManagerService extends ILocationManager.Stub { private final HashMap<String, Location> mLastLocationCoarseInterval = new HashMap<>(); - private final ArraySet<String> mBackgroundThrottlePackageWhitelist = new ArraySet<>(); - - private final ArraySet<String> mIgnoreSettingsPackageWhitelist = new ArraySet<>(); - // current active user on the device - other users are denied location data private int mCurrentUserId = UserHandle.USER_SYSTEM; private int[] mCurrentUserProfiles = new int[]{UserHandle.USER_SYSTEM}; @@ -287,16 +275,19 @@ public class LocationManagerService extends ILocationManager.Stub { @GuardedBy("mLock") private void initializeLocked() { - mAppOps = (AppOpsManager) mContext.getSystemService(Context.APP_OPS_SERVICE); mPackageManager = mContext.getPackageManager(); - mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); - mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE); - mUserManager = (UserManager) mContext.getSystemService(Context.USER_SERVICE); + mAppOps = mContext.getSystemService(AppOpsManager.class); + mPowerManager = mContext.getSystemService(PowerManager.class); + mActivityManager = mContext.getSystemService(ActivityManager.class); + mUserManager = mContext.getSystemService(UserManager.class); + + mSettingsStore = new LocationSettingsStore(mContext, mHandler); mLocationFudger = new LocationFudger(mContext, mHandler); - mBlacklist = new LocationBlacklist(mContext, mHandler); - mBlacklist.init(); - mGeofenceManager = new GeofenceManager(mContext, mBlacklist); + mGeofenceManager = new GeofenceManager(mContext, mSettingsStore); + + PowerManagerInternal localPowerManager = + LocalServices.getService(PowerManagerInternal.class); // prepare providers initializeProvidersLocked(); @@ -327,7 +318,6 @@ public class LocationManagerService extends ILocationManager.Stub { } }); }); - mActivityManager.addOnUidImportanceListener( (uid, importance) -> { // listener invoked on ui thread, move to our thread to reduce risk of blocking @@ -339,63 +329,7 @@ public class LocationManagerService extends ILocationManager.Stub { }); }, FOREGROUND_IMPORTANCE_CUTOFF); - mContext.getContentResolver().registerContentObserver( - Settings.Secure.getUriFor(Settings.Secure.LOCATION_MODE), true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - onLocationModeChangedLocked(true); - } - } - }, UserHandle.USER_ALL); - mContext.getContentResolver().registerContentObserver( - Settings.Secure.getUriFor(Settings.Secure.LOCATION_PROVIDERS_ALLOWED), true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - onProviderAllowedChangedLocked(); - } - } - }, UserHandle.USER_ALL); - mContext.getContentResolver().registerContentObserver( - Settings.Global.getUriFor(Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS), - true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - onBackgroundThrottleIntervalChangedLocked(); - } - } - }, UserHandle.USER_ALL); - mContext.getContentResolver().registerContentObserver( - Settings.Global.getUriFor( - Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST), - true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - onBackgroundThrottleWhitelistChangedLocked(); - } - } - }, UserHandle.USER_ALL); - mContext.getContentResolver().registerContentObserver( - Settings.Global.getUriFor( - Settings.Global.LOCATION_IGNORE_SETTINGS_PACKAGE_WHITELIST), - true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - onIgnoreSettingsWhitelistChangedLocked(); - } - } - }, UserHandle.USER_ALL); - PowerManagerInternal localPowerManager = - LocalServices.getService(PowerManagerInternal.class); + localPowerManager.registerLowPowerModeObserver(ServiceType.LOCATION, state -> { // listener invoked on ui thread, move to our thread to reduce risk of blocking @@ -406,6 +340,33 @@ public class LocationManagerService extends ILocationManager.Stub { } }); }); + mBatterySaverMode = mPowerManager.getLocationPowerSaveMode(); + + mSettingsStore.addOnLocationEnabledChangedListener(() -> { + synchronized (mLock) { + onLocationModeChangedLocked(true); + } + }); + mSettingsStore.addOnLocationProvidersAllowedChangedListener(() -> { + synchronized (mLock) { + onProviderAllowedChangedLocked(); + } + }); + mSettingsStore.addOnBackgroundThrottleIntervalChangedListener(() -> { + synchronized (mLock) { + onBackgroundThrottleIntervalChangedLocked(); + } + }); + mSettingsStore.addOnBackgroundThrottlePackageWhitelistChangedListener(() -> { + synchronized (mLock) { + onBackgroundThrottleWhitelistChangedLocked(); + } + }); + mSettingsStore.addOnIgnoreSettingsPackageWhitelistChangedListener(() -> { + synchronized (mLock) { + onIgnoreSettingsWhitelistChangedLocked(); + } + }); new PackageMonitor() { @Override @@ -453,11 +414,6 @@ public class LocationManagerService extends ILocationManager.Stub { // provider initialization, and propagates changes until a steady state is reached mCurrentUserId = UserHandle.USER_NULL; onUserChangedLocked(ActivityManager.getCurrentUser()); - - // initialize in-memory settings values - onBackgroundThrottleWhitelistChangedLocked(); - onIgnoreSettingsWhitelistChangedLocked(); - onBatterySaverModeChangedLocked(mPowerManager.getLocationPowerSaveMode()); } @GuardedBy("mLock") @@ -479,6 +435,10 @@ public class LocationManagerService extends ILocationManager.Stub { @GuardedBy("mLock") private void onBatterySaverModeChangedLocked(int newLocationMode) { + if (mBatterySaverMode == newLocationMode) { + return; + } + if (D) { Slog.d(TAG, "Battery Saver location mode changed from " @@ -486,11 +446,8 @@ public class LocationManagerService extends ILocationManager.Stub { + locationPowerSaveModeToString(newLocationMode)); } - if (mBatterySaverMode == newLocationMode) { - return; - } - mBatterySaverMode = newLocationMode; + for (LocationProvider p : mProviders) { applyRequirementsLocked(p); } @@ -588,17 +545,6 @@ public class LocationManagerService extends ILocationManager.Stub { @GuardedBy("mLock") private void onBackgroundThrottleWhitelistChangedLocked() { - mBackgroundThrottlePackageWhitelist.clear(); - mBackgroundThrottlePackageWhitelist.addAll( - SystemConfig.getInstance().getAllowUnthrottledLocation()); - - String setting = Settings.Global.getString( - mContext.getContentResolver(), - Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST); - if (!TextUtils.isEmpty(setting)) { - mBackgroundThrottlePackageWhitelist.addAll(Arrays.asList(setting.split(","))); - } - for (LocationProvider p : mProviders) { applyRequirementsLocked(p); } @@ -606,17 +552,6 @@ public class LocationManagerService extends ILocationManager.Stub { @GuardedBy("lock") private void onIgnoreSettingsWhitelistChangedLocked() { - mIgnoreSettingsPackageWhitelist.clear(); - mIgnoreSettingsPackageWhitelist.addAll( - SystemConfig.getInstance().getAllowIgnoreLocationSettings()); - - String setting = Settings.Global.getString( - mContext.getContentResolver(), - Settings.Global.LOCATION_IGNORE_SETTINGS_PACKAGE_WHITELIST); - if (!TextUtils.isEmpty(setting)) { - mIgnoreSettingsPackageWhitelist.addAll(Arrays.asList(setting.split(","))); - } - for (LocationProvider p : mProviders) { applyRequirementsLocked(p); } @@ -859,8 +794,6 @@ public class LocationManagerService extends ILocationManager.Stub { mCurrentUserId = userId; onUserProfilesChangedLocked(); - mBlacklist.switchUser(userId); - // if the user changes, per-user settings may also have changed onLocationModeChangedLocked(false); onProviderAllowedChangedLocked(); @@ -1083,11 +1016,8 @@ public class LocationManagerService extends ILocationManager.Stub { @GuardedBy("mLock") public void onAllowedChangedLocked() { if (mIsManagedBySettings) { - String allowedProviders = Settings.Secure.getStringForUser( - mContext.getContentResolver(), - Settings.Secure.LOCATION_PROVIDERS_ALLOWED, - mCurrentUserId); - boolean allowed = TextUtils.delimitedStringContains(allowedProviders, ',', mName); + boolean allowed = mSettingsStore.getLocationProvidersAllowed( + mCurrentUserId).contains(mName); if (allowed == mAllowed) { return; @@ -1909,10 +1839,7 @@ public class LocationManagerService extends ILocationManager.Stub { long identity = Binder.clearCallingIdentity(); try { - backgroundThrottleInterval = Settings.Global.getLong( - mContext.getContentResolver(), - Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS, - DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS); + backgroundThrottleInterval = mSettingsStore.getBackgroundThrottleIntervalMs(); } finally { Binder.restoreCallingIdentity(identity); } @@ -2032,16 +1959,12 @@ public class LocationManagerService extends ILocationManager.Stub { @Override public String[] getBackgroundThrottlingWhitelist() { - synchronized (mLock) { - return mBackgroundThrottlePackageWhitelist.toArray(new String[0]); - } + return mSettingsStore.getBackgroundThrottlePackageWhitelist().toArray(new String[0]); } @Override public String[] getIgnoreSettingsWhitelist() { - synchronized (mLock) { - return mIgnoreSettingsPackageWhitelist.toArray(new String[0]); - } + return mSettingsStore.getIgnoreSettingsPackageWhitelist().toArray(new String[0]); } @GuardedBy("mLock") @@ -2050,7 +1973,8 @@ public class LocationManagerService extends ILocationManager.Stub { return true; } - if (mBackgroundThrottlePackageWhitelist.contains(callerIdentity.mPackageName)) { + if (mSettingsStore.getBackgroundThrottlePackageWhitelist().contains( + callerIdentity.mPackageName)) { return true; } @@ -2064,7 +1988,7 @@ public class LocationManagerService extends ILocationManager.Stub { return false; } - if (mIgnoreSettingsPackageWhitelist.contains( + if (mSettingsStore.getIgnoreSettingsPackageWhitelist().contains( record.mReceiver.mCallerIdentity.mPackageName)) { return true; } @@ -2081,23 +2005,13 @@ public class LocationManagerService extends ILocationManager.Stub { private boolean mIsForegroundUid; private Location mLastFixBroadcast; private Throwable mStackTrace; // for debugging only + private long mExpirationRealtimeMs; /** * Note: must be constructed with lock held. */ private UpdateRecord(String provider, LocationRequest request, Receiver receiver) { - // translate expireIn value into expireAt - long elapsedRealtime = SystemClock.elapsedRealtime(); - long expireAt; - // Check for > Long.MAX_VALUE overflow (elapsedRealtime > 0): - if (request.getExpireIn() > Long.MAX_VALUE - elapsedRealtime) { - expireAt = Long.MAX_VALUE; - } else { - expireAt = Math.max(request.getExpireIn() + elapsedRealtime, 0); - } - request.setExpireAt(Math.min(request.getExpireAt(), expireAt)); - request.setExpireIn(Long.MAX_VALUE); - + mExpirationRealtimeMs = request.getExpirationRealtimeMs(SystemClock.elapsedRealtime()); mProvider = provider; mRealRequest = request; mRequest = request; @@ -2472,7 +2386,8 @@ public class LocationManagerService extends ILocationManager.Stub { final int uid = Binder.getCallingUid(); final long identity = Binder.clearCallingIdentity(); try { - if (mBlacklist.isBlacklisted(packageName)) { + if (mSettingsStore.isLocationPackageBlacklisted(UserHandle.getUserId(uid), + packageName)) { if (D) { Log.d(TAG, "not returning last loc for blacklisted app: " + packageName); @@ -2513,10 +2428,7 @@ public class LocationManagerService extends ILocationManager.Stub { String op = resolutionLevelToOpStr(allowedResolutionLevel); long locationAgeMs = TimeUnit.NANOSECONDS.toMillis( SystemClock.elapsedRealtime() - location.getElapsedRealtimeNanos()); - if ((locationAgeMs > Settings.Global.getLong( - mContext.getContentResolver(), - Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS, - DEFAULT_LAST_LOCATION_MAX_AGE_MS)) + if (locationAgeMs > mSettingsStore.getMaxLastLocationAgeMs() && (mAppOps.unsafeCheckOp(op, uid, packageName) == AppOpsManager.MODE_FOREGROUND)) { return null; @@ -2575,11 +2487,7 @@ public class LocationManagerService extends ILocationManager.Stub { boolean foreground = LocationManagerServiceUtils.isImportanceForeground( mActivityManager.getPackageImportance(packageName)); if (!foreground) { - long backgroundThrottleIntervalMs = Settings.Global.getLong( - mContext.getContentResolver(), - Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS, - DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS); - if (locationAgeMs < backgroundThrottleIntervalMs) { + if (locationAgeMs < mSettingsStore.getBackgroundThrottleIntervalMs()) { // not allowed to request new locations, so we can't return anything return false; } @@ -2910,11 +2818,7 @@ public class LocationManagerService extends ILocationManager.Stub { long identity = Binder.clearCallingIdentity(); try { - return Settings.Secure.getIntForUser( - mContext.getContentResolver(), - Settings.Secure.LOCATION_MODE, - Settings.Secure.LOCATION_MODE_OFF, - userId) != Settings.Secure.LOCATION_MODE_OFF; + return mSettingsStore.isLocationEnabled(userId); } finally { Binder.restoreCallingIdentity(identity); } @@ -2969,7 +2873,7 @@ public class LocationManagerService extends ILocationManager.Stub { } // Check whether the expiry date has passed - return record.mRealRequest.getExpireAt() >= now; + return record.mExpirationRealtimeMs >= now; } @GuardedBy("mLock") @@ -3050,7 +2954,8 @@ public class LocationManagerService extends ILocationManager.Stub { continue; } - if (mBlacklist.isBlacklisted(receiver.mCallerIdentity.mPackageName)) { + if (mSettingsStore.isLocationPackageBlacklisted(receiverUserId, + receiver.mCallerIdentity.mPackageName)) { if (D) { Log.d(TAG, "skipping loc update for blacklisted app: " + receiver.mCallerIdentity.mPackageName); @@ -3100,7 +3005,7 @@ public class LocationManagerService extends ILocationManager.Stub { } // track expired records - if (r.mRealRequest.getNumUpdates() <= 0 || r.mRealRequest.getExpireAt() < now) { + if (r.mRealRequest.getNumUpdates() <= 0 || r.mExpirationRealtimeMs < now) { // notify the client it can remove this listener r.mReceiver.callRemovedLocked(); if (deadUpdateRecords == null) { @@ -3392,33 +3297,11 @@ public class LocationManagerService extends ILocationManager.Stub { ipw.decreaseIndent(); } - if (mBlacklist != null) { - mBlacklist.dump(ipw); - } - if (mExtraLocationControllerPackage != null) { ipw.println("Location Controller Extra Package: " + mExtraLocationControllerPackage + (mExtraLocationControllerPackageEnabled ? " [enabled]" : "[disabled]")); } - if (!mBackgroundThrottlePackageWhitelist.isEmpty()) { - ipw.println("Throttling Whitelisted Packages:"); - ipw.increaseIndent(); - for (String packageName : mBackgroundThrottlePackageWhitelist) { - ipw.println(packageName); - } - ipw.decreaseIndent(); - } - - if (!mIgnoreSettingsPackageWhitelist.isEmpty()) { - ipw.println("Bypass Whitelisted Packages:"); - ipw.increaseIndent(); - for (String packageName : mIgnoreSettingsPackageWhitelist) { - ipw.println(packageName); - } - ipw.decreaseIndent(); - } - if (mLocationFudger != null) { ipw.println("Location Fudger:"); ipw.increaseIndent(); @@ -3426,6 +3309,8 @@ public class LocationManagerService extends ILocationManager.Stub { ipw.decreaseIndent(); } + mSettingsStore.dump(fd, pw, args); + ipw.println("Location Providers:"); ipw.increaseIndent(); for (LocationProvider provider : mProviders) { diff --git a/services/core/java/com/android/server/am/PendingIntentController.java b/services/core/java/com/android/server/am/PendingIntentController.java index d75591cc7432..df76713d58a6 100644 --- a/services/core/java/com/android/server/am/PendingIntentController.java +++ b/services/core/java/com/android/server/am/PendingIntentController.java @@ -43,6 +43,7 @@ import android.util.Slog; import com.android.internal.os.IResultReceiver; import com.android.internal.util.function.pooled.PooledLambda; +import com.android.server.AlarmManagerInternal; import com.android.server.LocalServices; import com.android.server.wm.ActivityTaskManagerInternal; import com.android.server.wm.SafeActivityOptions; @@ -293,6 +294,8 @@ public class PendingIntentController { PendingIntentController::handlePendingIntentCancelled, this, callbacks); mH.sendMessage(m); } + final AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); + ami.remove(new PendingIntent(rec)); } private void handlePendingIntentCancelled(RemoteCallbackList<IResultReceiver> callbacks) { diff --git a/services/core/java/com/android/server/location/GeofenceManager.java b/services/core/java/com/android/server/location/GeofenceManager.java index 17a21694e725..81c06d7125f9 100644 --- a/services/core/java/com/android/server/location/GeofenceManager.java +++ b/services/core/java/com/android/server/location/GeofenceManager.java @@ -18,12 +18,11 @@ package com.android.server.location; import android.annotation.NonNull; import android.annotation.Nullable; +import android.app.ActivityManager; import android.app.AppOpsManager; import android.app.PendingIntent; -import android.content.ContentResolver; import android.content.Context; import android.content.Intent; -import android.database.ContentObserver; import android.location.Geofence; import android.location.Location; import android.location.LocationListener; @@ -31,13 +30,14 @@ import android.location.LocationManager; import android.location.LocationRequest; import android.os.Bundle; import android.os.Handler; +import android.os.Looper; import android.os.Message; import android.os.PowerManager; import android.os.SystemClock; -import android.os.UserHandle; -import android.provider.Settings; +import android.util.Log; import android.util.Slog; +import com.android.server.FgThread; import com.android.server.LocationManagerService; import com.android.server.PendingIntentUtils; @@ -48,7 +48,7 @@ import java.util.List; public class GeofenceManager implements LocationListener, PendingIntent.OnFinished { private static final String TAG = "GeofenceManager"; - private static final boolean D = LocationManagerService.D; + private static final boolean D = Log.isLoggable(TAG, Log.DEBUG); private static final int MSG_UPDATE_FENCES = 1; @@ -64,10 +64,6 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish */ private static final long MAX_AGE_NANOS = 5 * 60 * 1000000000L; // five minutes - /** - * The default value of most frequent update interval allowed. - */ - private static final long DEFAULT_MIN_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes /** * Least frequent update interval allowed. @@ -75,11 +71,13 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish private static final long MAX_INTERVAL_MS = 2 * 60 * 60 * 1000; // two hours private final Context mContext; + private final GeofenceHandler mHandler; + private final LocationManager mLocationManager; private final AppOpsManager mAppOps; private final PowerManager.WakeLock mWakeLock; - private final GeofenceHandler mHandler; - private final LocationBlacklist mBlacklist; + + private final LocationSettingsStore mSettingsStore; private final Object mLock = new Object(); @@ -113,43 +111,17 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish */ private boolean mPendingUpdate; - /** - * The actual value of most frequent update interval allowed. - */ - private long mEffectiveMinIntervalMs; - private ContentResolver mResolver; - - public GeofenceManager(Context context, LocationBlacklist blacklist) { + public GeofenceManager(Context context, LocationSettingsStore settingsStore) { mContext = context; - mLocationManager = (LocationManager) mContext.getSystemService(Context.LOCATION_SERVICE); - mAppOps = (AppOpsManager)mContext.getSystemService(Context.APP_OPS_SERVICE); - PowerManager powerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE); - mWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG); - mHandler = new GeofenceHandler(); - mBlacklist = blacklist; - mResolver = mContext.getContentResolver(); - updateMinInterval(); - mResolver.registerContentObserver( - Settings.Global.getUriFor( - Settings.Global.LOCATION_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS), - true, - new ContentObserver(mHandler) { - @Override - public void onChange(boolean selfChange) { - synchronized (mLock) { - updateMinInterval(); - } - } - }, UserHandle.USER_ALL); - } + mHandler = new GeofenceHandler(FgThread.getHandler().getLooper()); - /** - * Updates the minimal location request frequency. - */ - private void updateMinInterval() { - mEffectiveMinIntervalMs = Settings.Global.getLong(mResolver, - Settings.Global.LOCATION_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS, - DEFAULT_MIN_INTERVAL_MS); + mLocationManager = mContext.getSystemService(LocationManager.class); + mAppOps = mContext.getSystemService(AppOpsManager.class); + + mWakeLock = mContext.getSystemService(PowerManager.class).newWakeLock( + PowerManager.PARTIAL_WAKE_LOCK, TAG); + + mSettingsStore = settingsStore; } public void addFence(LocationRequest request, Geofence geofence, PendingIntent intent, @@ -161,8 +133,8 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish } GeofenceState state = new GeofenceState(geofence, - request.getExpireAt(), allowedResolutionLevel, uid, packageName, featureId, - listenerIdentifier, intent); + request.getExpirationRealtimeMs(SystemClock.elapsedRealtime()), + allowedResolutionLevel, uid, packageName, featureId, listenerIdentifier, intent); synchronized (mLock) { // first make sure it doesn't already exist for (int i = mFences.size() - 1; i >= 0; i--) { @@ -294,7 +266,8 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish double minFenceDistance = Double.MAX_VALUE; boolean needUpdates = false; for (GeofenceState state : mFences) { - if (mBlacklist.isBlacklisted(state.mPackageName)) { + if (mSettingsStore.isLocationPackageBlacklisted(ActivityManager.getCurrentUser(), + state.mPackageName)) { if (D) { Slog.d(TAG, "skipping geofence processing for blacklisted app: " + state.mPackageName); @@ -340,10 +313,11 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish // Compute a location update interval based on the distance to the nearest fence. long intervalMs; if (location != null && Double.compare(minFenceDistance, Double.MAX_VALUE) != 0) { - intervalMs = (long)Math.min(MAX_INTERVAL_MS, Math.max(mEffectiveMinIntervalMs, + intervalMs = (long) Math.min(MAX_INTERVAL_MS, Math.max( + mSettingsStore.getBackgroundThrottleProximityAlertIntervalMs(), minFenceDistance * 1000 / MAX_SPEED_M_S)); } else { - intervalMs = mEffectiveMinIntervalMs; + intervalMs = mSettingsStore.getBackgroundThrottleProximityAlertIntervalMs(); } if (!mReceivingLocationUpdates || mLocationUpdateInterval != intervalMs) { mReceivingLocationUpdates = true; @@ -436,13 +410,16 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish } @Override - public void onStatusChanged(String provider, int status, Bundle extras) { } + public void onStatusChanged(String provider, int status, Bundle extras) { + } @Override - public void onProviderEnabled(String provider) { } + public void onProviderEnabled(String provider) { + } @Override - public void onProviderDisabled(String provider) { } + public void onProviderDisabled(String provider) { + } @Override public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode, @@ -457,17 +434,14 @@ public class GeofenceManager implements LocationListener, PendingIntent.OnFinish } private final class GeofenceHandler extends Handler { - public GeofenceHandler() { - super(true /*async*/); + private GeofenceHandler(Looper looper) { + super(looper); } @Override public void handleMessage(Message msg) { - switch (msg.what) { - case MSG_UPDATE_FENCES: { - updateFences(); - break; - } + if (msg.what == MSG_UPDATE_FENCES) { + updateFences(); } } } diff --git a/services/core/java/com/android/server/location/LocationBlacklist.java b/services/core/java/com/android/server/location/LocationBlacklist.java deleted file mode 100644 index 3f3f82871c0f..000000000000 --- a/services/core/java/com/android/server/location/LocationBlacklist.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright (C) 2012 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.location; - -import android.content.Context; -import android.database.ContentObserver; -import android.os.Handler; -import android.os.UserHandle; -import android.provider.Settings; -import android.util.Log; -import android.util.Slog; - -import com.android.server.LocationManagerService; - -import java.io.PrintWriter; -import java.util.ArrayList; -import java.util.Arrays; - -/** - * Allows applications to be blacklisted from location updates at run-time. - * - * This is a silent blacklist. Applications can still call Location Manager - * API's, but they just won't receive any locations. - */ -public final class LocationBlacklist extends ContentObserver { - private static final String TAG = "LocationBlacklist"; - private static final boolean D = LocationManagerService.D; - private static final String BLACKLIST_CONFIG_NAME = "locationPackagePrefixBlacklist"; - private static final String WHITELIST_CONFIG_NAME = "locationPackagePrefixWhitelist"; - - private final Context mContext; - private final Object mLock = new Object(); - - // all fields below synchronized on mLock - private String[] mWhitelist = new String[0]; - private String[] mBlacklist = new String[0]; - - private int mCurrentUserId = UserHandle.USER_SYSTEM; - - public LocationBlacklist(Context context, Handler handler) { - super(handler); - mContext = context; - } - - public void init() { - mContext.getContentResolver().registerContentObserver(Settings.Secure.getUriFor( - BLACKLIST_CONFIG_NAME), false, this, UserHandle.USER_ALL); -// mContext.getContentResolver().registerContentObserver(Settings.Secure.getUriFor( -// WHITELIST_CONFIG_NAME), false, this, UserHandle.USER_ALL); - reloadBlacklist(); - } - - private void reloadBlacklistLocked() { - mWhitelist = getStringArrayLocked(WHITELIST_CONFIG_NAME); - if (D) Slog.d(TAG, "whitelist: " + Arrays.toString(mWhitelist)); - mBlacklist = getStringArrayLocked(BLACKLIST_CONFIG_NAME); - if (D) Slog.d(TAG, "blacklist: " + Arrays.toString(mBlacklist)); - } - - private void reloadBlacklist() { - synchronized (mLock) { - reloadBlacklistLocked(); - } - } - - /** - * Return true if in blacklist - * (package name matches blacklist, and does not match whitelist) - */ - public boolean isBlacklisted(String packageName) { - synchronized (mLock) { - for (String black : mBlacklist) { - if (packageName.startsWith(black)) { - if (inWhitelist(packageName)) { - continue; - } else { - if (D) Log.d(TAG, "dropping location (blacklisted): " - + packageName + " matches " + black); - return true; - } - } - } - } - return false; - } - - /** - * Return true if any of packages are in whitelist - */ - private boolean inWhitelist(String pkg) { - synchronized (mLock) { - for (String white : mWhitelist) { - if (pkg.startsWith(white)) return true; - } - } - return false; - } - - @Override - public void onChange(boolean selfChange) { - reloadBlacklist(); - } - - public void switchUser(int userId) { - synchronized(mLock) { - mCurrentUserId = userId; - reloadBlacklistLocked(); - } - } - - private String[] getStringArrayLocked(String key) { - String flatString; - synchronized(mLock) { - flatString = Settings.Secure.getStringForUser(mContext.getContentResolver(), key, - mCurrentUserId); - } - if (flatString == null) { - return new String[0]; - } - String[] splitStrings = flatString.split(","); - ArrayList<String> result = new ArrayList<String>(); - for (String pkg : splitStrings) { - pkg = pkg.trim(); - if (pkg.isEmpty()) { - continue; - } - result.add(pkg); - } - return result.toArray(new String[result.size()]); - } - - public void dump(PrintWriter pw) { - pw.println("mWhitelist=" + Arrays.toString(mWhitelist) + " mBlacklist=" + - Arrays.toString(mBlacklist)); - } -} diff --git a/services/core/java/com/android/server/location/LocationSettingsStore.java b/services/core/java/com/android/server/location/LocationSettingsStore.java new file mode 100644 index 000000000000..a4b6d97e9471 --- /dev/null +++ b/services/core/java/com/android/server/location/LocationSettingsStore.java @@ -0,0 +1,461 @@ +/* + * Copyright (C) 2019 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.location; + +import static android.provider.Settings.Global.LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS; +import static android.provider.Settings.Global.LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST; +import static android.provider.Settings.Global.LOCATION_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS; +import static android.provider.Settings.Global.LOCATION_IGNORE_SETTINGS_PACKAGE_WHITELIST; +import static android.provider.Settings.Global.LOCATION_LAST_LOCATION_MAX_AGE_MILLIS; +import static android.provider.Settings.Secure.LOCATION_MODE; +import static android.provider.Settings.Secure.LOCATION_MODE_OFF; +import static android.provider.Settings.Secure.LOCATION_PROVIDERS_ALLOWED; + +import android.app.ActivityManager; +import android.content.Context; +import android.database.ContentObserver; +import android.net.Uri; +import android.os.Handler; +import android.os.UserHandle; +import android.provider.Settings; +import android.text.TextUtils; + +import com.android.internal.util.IndentingPrintWriter; + +import java.io.FileDescriptor; +import java.io.PrintWriter; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.concurrent.CopyOnWriteArrayList; + +/** + * Provides accessors and listeners for all location related settings. + */ +public class LocationSettingsStore { + + private static final String LOCATION_PACKAGE_BLACKLIST = "locationPackagePrefixBlacklist"; + private static final String LOCATION_PACKAGE_WHITELIST = "locationPackagePrefixWhitelist"; + + private static final long DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS = 30 * 60 * 1000; + private static final long DEFAULT_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS = + 30 * 60 * 1000; + private static final long DEFAULT_MAX_LAST_LOCATION_AGE_MS = 20 * 60 * 1000; + + private final Context mContext; + + private final IntegerSecureSetting mLocationMode; + private final StringListCachedSecureSetting mLocationProvidersAllowed; + private final LongGlobalSetting mBackgroundThrottleIntervalMs; + private final StringListCachedSecureSetting mLocationPackageBlacklist; + private final StringListCachedSecureSetting mLocationPackageWhitelist; + private final StringListCachedGlobalSetting mBackgroundThrottlePackageWhitelist; + private final StringListCachedGlobalSetting mIgnoreSettingsPackageWhitelist; + + public LocationSettingsStore(Context context, Handler handler) { + mContext = context; + + mLocationMode = new IntegerSecureSetting(context, LOCATION_MODE, handler); + mLocationProvidersAllowed = new StringListCachedSecureSetting(context, + LOCATION_PROVIDERS_ALLOWED, handler); + mBackgroundThrottleIntervalMs = new LongGlobalSetting(context, + LOCATION_BACKGROUND_THROTTLE_INTERVAL_MS, handler); + mLocationPackageBlacklist = new StringListCachedSecureSetting(context, + LOCATION_PACKAGE_BLACKLIST, handler); + mLocationPackageWhitelist = new StringListCachedSecureSetting(context, + LOCATION_PACKAGE_WHITELIST, handler); + mBackgroundThrottlePackageWhitelist = new StringListCachedGlobalSetting(context, + LOCATION_BACKGROUND_THROTTLE_PACKAGE_WHITELIST, handler); + mIgnoreSettingsPackageWhitelist = new StringListCachedGlobalSetting(context, + LOCATION_IGNORE_SETTINGS_PACKAGE_WHITELIST, handler); + } + + /** + * Retrieve if location is enabled or not. + */ + public boolean isLocationEnabled(int userId) { + return mLocationMode.getValueForUser(LOCATION_MODE_OFF, userId) != LOCATION_MODE_OFF; + } + + /** + * Add a listener for changes to the location enabled setting. + */ + public void addOnLocationEnabledChangedListener(Runnable listener) { + mLocationMode.addListener(listener); + } + + /** + * Remove a listener for changes to the location enabled setting. + */ + public void removeOnLocationEnabledChangedListener(Runnable listener) { + mLocationMode.addListener(listener); + } + + /** + * Retrieve the currently allowed location providers. + */ + public List<String> getLocationProvidersAllowed(int userId) { + return mLocationProvidersAllowed.getValueForUser(userId); + } + + /** + * Add a listener for changes to the currently allowed location providers. + */ + public void addOnLocationProvidersAllowedChangedListener(Runnable runnable) { + mLocationProvidersAllowed.addListener(runnable); + } + + /** + * Remove a listener for changes to the currently allowed location providers. + */ + public void removeOnLocationProvidersAllowedChangedListener(Runnable runnable) { + mLocationProvidersAllowed.removeListener(runnable); + } + + /** + * Retrieve the background throttle interval. + */ + public long getBackgroundThrottleIntervalMs() { + return mBackgroundThrottleIntervalMs.getValue(DEFAULT_BACKGROUND_THROTTLE_INTERVAL_MS); + } + + /** + * Add a listener for changes to the background throttle interval. + */ + public void addOnBackgroundThrottleIntervalChangedListener(Runnable listener) { + mBackgroundThrottleIntervalMs.addListener(listener); + } + + /** + * Remove a listener for changes to the background throttle interval. + */ + public void removeOnBackgroundThrottleIntervalChangedListener(Runnable listener) { + mBackgroundThrottleIntervalMs.removeListener(listener); + } + + /** + * Check if the given package is blacklisted for location access. + */ + public boolean isLocationPackageBlacklisted(int userId, String packageName) { + List<String> locationPackageBlacklist = mLocationPackageBlacklist.getValueForUser(userId); + if (locationPackageBlacklist.isEmpty()) { + return false; + } + + List<String> locationPackageWhitelist = mLocationPackageWhitelist.getValueForUser(userId); + for (String locationWhitelistPackage : locationPackageWhitelist) { + if (packageName.startsWith(locationWhitelistPackage)) { + return false; + } + } + + for (String locationBlacklistPackage : locationPackageBlacklist) { + if (packageName.startsWith(locationBlacklistPackage)) { + return true; + } + } + + return false; + } + + /** + * Retrieve the background throttle package whitelist. + */ + public List<String> getBackgroundThrottlePackageWhitelist() { + return mBackgroundThrottlePackageWhitelist.getValue(); + } + + /** + * Add a listener for changes to the background throttle package whitelist. + */ + public void addOnBackgroundThrottlePackageWhitelistChangedListener(Runnable listener) { + mBackgroundThrottlePackageWhitelist.addListener(listener); + } + + /** + * Remove a listener for changes to the background throttle package whitelist. + */ + public void removeOnBackgroundThrottlePackageWhitelistChangedListener(Runnable listener) { + mBackgroundThrottlePackageWhitelist.removeListener(listener); + } + + /** + * Retrieve the ignore settings package whitelist. + */ + public List<String> getIgnoreSettingsPackageWhitelist() { + return mIgnoreSettingsPackageWhitelist.getValue(); + } + + /** + * Add a listener for changes to the ignore settings package whitelist. + */ + public void addOnIgnoreSettingsPackageWhitelistChangedListener(Runnable listener) { + mIgnoreSettingsPackageWhitelist.addListener(listener); + } + + /** + * Remove a listener for changes to the ignore settings package whitelist. + */ + public void removeOnIgnoreSettingsPackageWhitelistChangedListener(Runnable listener) { + mIgnoreSettingsPackageWhitelist.removeListener(listener); + } + + /** + * Retrieve the background throttling proximity alert interval. + */ + public long getBackgroundThrottleProximityAlertIntervalMs() { + return Settings.Global.getLong(mContext.getContentResolver(), + LOCATION_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS, + DEFAULT_BACKGROUND_THROTTLE_PROXIMITY_ALERT_INTERVAL_MS); + } + + public long getMaxLastLocationAgeMs() { + return Settings.Global.getLong( + mContext.getContentResolver(), + LOCATION_LAST_LOCATION_MAX_AGE_MILLIS, + DEFAULT_MAX_LAST_LOCATION_AGE_MS); + } + + /** + * Dump info for debugging. + */ + public void dump(FileDescriptor fd, PrintWriter pw, String[] args) { + IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); + int userId = ActivityManager.getCurrentUser(); + + ipw.println("--Location Settings--"); + ipw.increaseIndent(); + + ipw.print("Location Enabled: "); + ipw.println(isLocationEnabled(userId)); + + ipw.print("Location Providers Allowed: "); + ipw.println(getLocationProvidersAllowed(userId)); + + List<String> locationPackageBlacklist = mLocationPackageBlacklist.getValueForUser(userId); + if (!locationPackageBlacklist.isEmpty()) { + ipw.println("Location Blacklisted Packages:"); + ipw.increaseIndent(); + for (String packageName : locationPackageBlacklist) { + ipw.println(packageName); + } + ipw.decreaseIndent(); + + List<String> locationPackageWhitelist = mLocationPackageWhitelist.getValueForUser( + userId); + if (!locationPackageWhitelist.isEmpty()) { + ipw.println("Location Whitelisted Packages:"); + ipw.increaseIndent(); + for (String packageName : locationPackageWhitelist) { + ipw.println(packageName); + } + ipw.decreaseIndent(); + } + } + + List<String> backgroundThrottlePackageWhitelist = + mBackgroundThrottlePackageWhitelist.getValue(); + if (!backgroundThrottlePackageWhitelist.isEmpty()) { + ipw.println("Throttling Whitelisted Packages:"); + ipw.increaseIndent(); + for (String packageName : backgroundThrottlePackageWhitelist) { + ipw.println(packageName); + } + ipw.decreaseIndent(); + } + + List<String> ignoreSettingsPackageWhitelist = mIgnoreSettingsPackageWhitelist.getValue(); + if (!ignoreSettingsPackageWhitelist.isEmpty()) { + ipw.println("Bypass Whitelisted Packages:"); + ipw.increaseIndent(); + for (String packageName : ignoreSettingsPackageWhitelist) { + ipw.println(packageName); + } + ipw.decreaseIndent(); + } + } + + private abstract static class ObservingSetting extends ContentObserver { + + private final CopyOnWriteArrayList<Runnable> mListeners; + + private ObservingSetting(Context context, String settingName, Handler handler) { + super(handler); + mListeners = new CopyOnWriteArrayList<>(); + + context.getContentResolver().registerContentObserver( + getUriFor(settingName), false, this, UserHandle.USER_ALL); + } + + public void addListener(Runnable listener) { + mListeners.add(listener); + } + + public void removeListener(Runnable listener) { + mListeners.remove(listener); + } + + protected abstract Uri getUriFor(String settingName); + + @Override + public void onChange(boolean selfChange, Uri uri, int userId) { + for (Runnable listener : mListeners) { + listener.run(); + } + } + } + + private static class IntegerSecureSetting extends ObservingSetting { + + private final Context mContext; + private final String mSettingName; + + private IntegerSecureSetting(Context context, String settingName, Handler handler) { + super(context, settingName, handler); + mContext = context; + mSettingName = settingName; + } + + public int getValueForUser(int defaultValue, int userId) { + return Settings.Secure.getIntForUser(mContext.getContentResolver(), mSettingName, + defaultValue, userId); + } + + @Override + protected Uri getUriFor(String settingName) { + return Settings.Secure.getUriFor(settingName); + } + } + + private static class StringListCachedSecureSetting extends ObservingSetting { + + private final Context mContext; + private final String mSettingName; + + private int mCachedUserId = UserHandle.USER_NULL; + private List<String> mCachedValue; + + private StringListCachedSecureSetting(Context context, String settingName, + Handler handler) { + super(context, settingName, handler); + mContext = context; + mSettingName = settingName; + } + + public synchronized List<String> getValueForUser(int userId) { + if (userId != mCachedUserId) { + String setting = Settings.Secure.getStringForUser(mContext.getContentResolver(), + mSettingName, userId); + if (TextUtils.isEmpty(setting)) { + mCachedValue = Collections.emptyList(); + } else { + mCachedValue = Arrays.asList(setting.split(",")); + } + mCachedUserId = userId; + } + + return mCachedValue; + } + + public synchronized void invalidateForUser(int userId) { + if (mCachedUserId == userId) { + mCachedUserId = UserHandle.USER_NULL; + mCachedValue = null; + } + } + + @Override + public void onChange(boolean selfChange, Uri uri, int userId) { + invalidateForUser(userId); + super.onChange(selfChange, uri, userId); + } + + @Override + protected Uri getUriFor(String settingName) { + return Settings.Secure.getUriFor(settingName); + } + } + + private static class LongGlobalSetting extends ObservingSetting { + + private final Context mContext; + private final String mSettingName; + + private LongGlobalSetting(Context context, String settingName, Handler handler) { + super(context, settingName, handler); + mContext = context; + mSettingName = settingName; + } + + public long getValue(long defaultValue) { + return Settings.Global.getLong(mContext.getContentResolver(), mSettingName, + defaultValue); + } + + @Override + protected Uri getUriFor(String settingName) { + return Settings.Global.getUriFor(settingName); + } + } + + private static class StringListCachedGlobalSetting extends ObservingSetting { + + private final Context mContext; + private final String mSettingName; + + private boolean mValid; + private List<String> mCachedValue; + + private StringListCachedGlobalSetting(Context context, String settingName, + Handler handler) { + super(context, settingName, handler); + mContext = context; + mSettingName = settingName; + } + + public synchronized List<String> getValue() { + if (!mValid) { + String setting = Settings.Global.getString(mContext.getContentResolver(), + mSettingName); + if (TextUtils.isEmpty(setting)) { + mCachedValue = Collections.emptyList(); + } else { + mCachedValue = Arrays.asList(setting.split(",")); + } + mValid = true; + } + + return mCachedValue; + } + + public synchronized void invalidate() { + mValid = false; + mCachedValue = null; + } + + @Override + public void onChange(boolean selfChange, Uri uri, int userId) { + invalidate(); + super.onChange(selfChange, uri, userId); + } + + @Override + protected Uri getUriFor(String settingName) { + return Settings.Global.getUriFor(settingName); + } + } +} diff --git a/services/core/java/com/android/server/wm/ActivityDisplay.java b/services/core/java/com/android/server/wm/ActivityDisplay.java index 48a7b73a5fc1..12681133d9c4 100644 --- a/services/core/java/com/android/server/wm/ActivityDisplay.java +++ b/services/core/java/com/android/server/wm/ActivityDisplay.java @@ -41,7 +41,6 @@ import static com.android.server.am.ActivityDisplayProto.RESUMED_ACTIVITY; import static com.android.server.am.ActivityDisplayProto.SINGLE_TASK_INSTANCE; import static com.android.server.am.ActivityDisplayProto.STACKS; import static com.android.server.wm.ActivityStack.ActivityState.RESUMED; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE; import static com.android.server.wm.ActivityStackSupervisor.TAG_TASKS; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_STACK; @@ -1523,7 +1522,7 @@ class ActivityDisplay extends ConfigurationContainer<ActivityStack> { final ActivityStack stack = getChildAt(i); final ArrayList<TaskRecord> tasks = stack.getAllTasks(); for (int j = tasks.size() - 1; j >= 0; --j) { - stack.removeTask(tasks.get(j), "removeAllTasks", REMOVE_TASK_MODE_DESTROYING); + stack.removeChild(tasks.get(j), "removeAllTasks"); } } } diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index db219fd4c5b5..d36004101b0e 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -1148,56 +1148,11 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } } - // TODO(task-unify): Remove once TaskRecord and Task are unified. TaskRecord getTaskRecord() { return task; } /** - * Sets reference to the {@link TaskRecord} the {@link ActivityRecord} will treat as its parent. - * Note that this does not actually add the {@link ActivityRecord} as a {@link TaskRecord} - * children. However, this method will clean up references to this {@link ActivityRecord} in - * {@link ActivityStack}. - * @param task The new parent {@link TaskRecord}. - */ - // TODO(task-unify): Can be remove after task level unification. Callers can just use addChild - void setTask(TaskRecord task) { - // Do nothing if the {@link TaskRecord} is the same as the current {@link getTaskRecord}. - if (task != null && task == getTaskRecord()) { - return; - } - - final ActivityStack oldStack = getActivityStack(); - final ActivityStack newStack = task != null ? task.getStack() : null; - - // Inform old stack (if present) of activity removal and new stack (if set) of activity - // addition. - if (oldStack != newStack) { - if (oldStack != null) { - oldStack.onActivityRemovedFromStack(this); - } - - if (newStack != null) { - newStack.onActivityAddedToStack(this); - } - } - - final TaskRecord oldTask = this.task; - this.task = task; - - // This is attaching the activity to the task which we only want to do once. - // TODO(task-unify): Need to re-work after unifying the task level since it will already - // have a parent then. Just need to restructure the re-parent case not to do this. NOTE that - // the reparenting flag passed in can't be used directly for this as it isn't set in - // ActivityRecord#reparent() case that ends up calling this method. - if (task != null && getParent() == null) { - task.addChild(this); - } else { - onParentChanged(task, oldTask); - } - } - - /** * Sets the Task on this activity for the purposes of re-use during launch where we will * re-use another activity instead of this one for the launch. */ @@ -1220,8 +1175,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @Override void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { - final TaskRecord oldTask = (oldParent != null) ? ((Task) oldParent).mTaskRecord : null; - final TaskRecord newTask = (newParent != null) ? ((Task) newParent).mTaskRecord : null; + final TaskRecord oldTask = oldParent != null ? (TaskRecord) oldParent : null; + final TaskRecord newTask = newParent != null ? (TaskRecord) newParent : null; this.task = newTask; super.onParentChanged(newParent, oldParent); @@ -1230,14 +1185,12 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A if (oldParent == null && newParent != null) { // First time we are adding the activity to the system. - // TODO(task-unify): See if mVoiceInteraction variable is really needed after task level - // unification. - mVoiceInteraction = task.mTaskRecord != null && task.mTaskRecord.voiceSession != null; + mVoiceInteraction = newTask.voiceSession != null; mInputDispatchingTimeoutNanos = getInputDispatchingTimeoutLocked(this) * 1000000L; onDisplayChanged(task.getDisplayContent()); - if (task.mTaskRecord != null) { - task.mTaskRecord.updateOverrideConfigurationFromLaunchBounds(); - } + // TODO(b/36505427): Maybe this call should be moved inside + // updateOverrideConfiguration() + newTask.updateOverrideConfigurationFromLaunchBounds(); // Make sure override configuration is up-to-date before using to create window // controller. updateSizeCompatMode(); @@ -1279,8 +1232,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // Inform old stack (if present) of activity removal and new stack (if set) of activity // addition. if (oldStack != newStack) { - // TODO(task-unify): Might be better to use onChildAdded and onChildRemoved signal for - // this once task level is unified. if (oldStack != null) { oldStack.onActivityRemovedFromStack(this); } @@ -1964,15 +1915,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A ProtoLog.i(WM_DEBUG_ADD_REMOVE, "reparent: moving activity=%s" + " to task=%d at %d", this, task.mTaskId, position); - - reparent(newTask.getTask(), position); - } - - // TODO(task-unify): Remove once Task level is unified. - void onParentChanged(TaskRecord newParent, TaskRecord oldParent) { - onParentChanged( - newParent != null ? newParent.mTask : null, - oldParent != null ? oldParent.mTask : null); + reparent(newTask, position); } private boolean isHomeIntent(Intent intent) { @@ -2051,7 +1994,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A /** * @return Stack value from current task, null if there is no task. */ - // TODO: Remove once ActivityStack and TaskStack are unified. + // TODO(stack-unify): Remove once ActivityStack and TaskStack are unified. <T extends ActivityStack> T getActivityStack() { return task != null ? (T) task.getStack() : null; } @@ -2339,7 +2282,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A /** Finish all activities in the task with the same affinity as this one. */ void finishActivityAffinity() { - final ArrayList<ActivityRecord> activities = getTaskRecord().mActivities; + final ArrayList<ActivityRecord> activities = getTaskRecord().mChildren; for (int index = activities.indexOf(this); index >= 0; --index) { final ActivityRecord cur = activities.get(index); if (!Objects.equals(cur.taskAffinity, taskAffinity)) { @@ -2451,7 +2394,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A EventLog.writeEvent(EventLogTags.AM_FINISH_ACTIVITY, mUserId, System.identityHashCode(this), task.mTaskId, shortComponentName, reason); - final ArrayList<ActivityRecord> activities = task.mActivities; + final ArrayList<ActivityRecord> activities = task.mChildren; final int index = activities.indexOf(this); if (index < (task.getChildCount() - 1)) { if ((intent.getFlags() & Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET) != 0) { @@ -2505,7 +2448,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // When finishing the activity preemptively take the snapshot before the app window // is marked as hidden and any configuration changes take place if (mAtmService.mWindowManager.mTaskSnapshotController != null) { - final ArraySet<Task> tasks = Sets.newArraySet(task.mTask); + final ArraySet<Task> tasks = Sets.newArraySet(task); mAtmService.mWindowManager.mTaskSnapshotController.snapshotTasks(tasks); mAtmService.mWindowManager.mTaskSnapshotController .addSkipClosingAppSnapshotTasks(tasks); @@ -2547,7 +2490,8 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // In this case, we can set the visibility of all the task overlay activities when // we detect the last one is finishing to keep them in sync. if (task.onlyHasTaskOverlayActivities(true /* excludeFinishing */)) { - for (ActivityRecord taskOverlay : task.mActivities) { + for (int i = task.getChildCount() - 1; i >= 0 ; --i) { + final ActivityRecord taskOverlay = task.getChildAt(i); if (!taskOverlay.mTaskOverlay) { continue; } @@ -2819,8 +2763,6 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } /** Note: call {@link #cleanUp(boolean, boolean)} before this method. */ - // TODO(task-unify): Look into consolidating this with TaskRecord.removeChild once we unify - // task level. void removeFromHistory(String reason) { finishActivityResults(Activity.RESULT_CANCELED, null /* resultData */); makeFinishingLocked(); @@ -4668,7 +4610,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } // Check if position in task allows to become paused - final int positionInTask = task.mActivities.indexOf(this); + final int positionInTask = task.mChildren.indexOf(this); if (positionInTask == -1) { throw new IllegalStateException("Activity not found in its task"); } @@ -5396,7 +5338,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A return INVALID_TASK_ID; } final TaskRecord task = r.task; - final int activityNdx = task.mActivities.indexOf(r); + final int activityNdx = task.mChildren.indexOf(r); if (activityNdx < 0 || (onlyRoot && activityNdx > task.findRootIndex(true /* effectiveRoot */))) { return INVALID_TASK_ID; @@ -5760,7 +5702,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A @Override boolean isWaitingForTransitionStart() { final DisplayContent dc = getDisplayContent(); - // TODO: Test for null can be removed once unification is done. + // TODO(display-unify): Test for null can be removed once unification is done. if (dc == null) return false; return dc.mAppTransition.isTransitionSet() && (dc.mOpeningApps.contains(this) @@ -6568,8 +6510,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A // If the changes come from change-listener, the incoming parent configuration is // still the old one. Make sure their orientations are the same to reduce computing // the compatibility bounds for the intermediate state. - && (task.mTaskRecord == null || task.mTaskRecord - .getConfiguration().orientation == newParentConfig.orientation)) { + && (task.getConfiguration().orientation == newParentConfig.orientation)) { final Rect taskBounds = task.getBounds(); // Since we only center the activity horizontally, if only the fixed height is smaller // than its container, the override bounds don't need to take effect. @@ -6887,8 +6828,7 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A preserveWindow &= isResizeOnlyChange(changes); final boolean hasResizeChange = hasResizeChange(changes & ~info.getRealConfigChanged()); if (hasResizeChange) { - final boolean isDragResizing = - getTaskRecord().getTask().isDragResizing(); + final boolean isDragResizing = getTaskRecord().isDragResizing(); mRelaunchReason = isDragResizing ? RELAUNCH_REASON_FREE_RESIZE : RELAUNCH_REASON_WINDOWING_MODE_RESIZE; } else { diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java index edf8789b3688..593318de34e1 100644 --- a/services/core/java/com/android/server/wm/ActivityStack.java +++ b/services/core/java/com/android/server/wm/ActivityStack.java @@ -254,7 +254,11 @@ class ActivityStack extends ConfigurationContainer { @Override protected void onParentChanged( ConfigurationContainer newParent, ConfigurationContainer oldParent) { - ActivityDisplay display = getParent(); + if (oldParent != null) { + mPrevDisplayId = ((ActivityDisplay) oldParent).mDisplayId; + } + + final ActivityDisplay display = getParent(); if (display != null) { // Rotations are relative to the display. This means if there are 2 displays rotated // differently (eg. 2 monitors with one landscape and one portrait), moving a stack @@ -292,18 +296,6 @@ class ActivityStack extends ConfigurationContainer { RESTARTING_PROCESS } - @VisibleForTesting - /* The various modes for the method {@link #removeTask}. */ - // Task is being completely removed from all stacks in the system. - protected static final int REMOVE_TASK_MODE_DESTROYING = 0; - // Task is being removed from this stack so we can add it to another stack. In the case we are - // moving we don't want to perform some operations on the task like removing it from window - // manager or recents. - static final int REMOVE_TASK_MODE_MOVING = 1; - // Similar to {@link #REMOVE_TASK_MODE_MOVING} and the task will be added to the top of its new - // stack and the new stack will be on top of all stacks. - static final int REMOVE_TASK_MODE_MOVING_TO_TOP = 2; - final ActivityTaskManagerService mService; final WindowManagerService mWindowManager; @@ -381,6 +373,8 @@ class ActivityStack extends ConfigurationContainer { final int mStackId; /** The attached Display's unique identifier, or -1 if detached */ int mDisplayId; + // Id of the previous display the stack was on. + int mPrevDisplayId = INVALID_DISPLAY; /** Stores the override windowing-mode from before a transient mode change (eg. split) */ private int mRestoreOverrideWindowingMode = WINDOWING_MODE_UNDEFINED; @@ -962,7 +956,7 @@ class ActivityStack extends ConfigurationContainer { void positionChildWindowContainerAtTop(TaskRecord child) { if (mTaskStack != null) { // TODO: Remove after unification. This cannot be false after that. - mTaskStack.positionChildAtTop(child.getTask(), true /* includingParents */); + mTaskStack.positionChildAtTop(child, true /* includingParents */); } } @@ -974,7 +968,7 @@ class ActivityStack extends ConfigurationContainer { child.getStack(), true /* ignoreCurrent */); if (mTaskStack != null) { // TODO: Remove after unification. This cannot be false after that. - mTaskStack.positionChildAtBottom(child.getTask(), + mTaskStack.positionChildAtBottom(child, nextFocusableStack == null /* includingParents */); } } @@ -1168,7 +1162,7 @@ class ActivityStack extends ConfigurationContainer { } final TaskRecord task = r.getTaskRecord(); final ActivityStack stack = r.getActivityStack(); - if (stack != null && task.mActivities.contains(r) && mTaskHistory.contains(task)) { + if (stack != null && task.mChildren.contains(r) && mTaskHistory.contains(task)) { if (stack != this) Slog.w(TAG, "Illegal state! task does not point to stack it is in."); return r; @@ -1183,7 +1177,8 @@ class ActivityStack extends ConfigurationContainer { /** Checks if there are tasks with specific UID in the stack. */ boolean isUidPresent(int uid) { for (TaskRecord task : mTaskHistory) { - for (ActivityRecord r : task.mActivities) { + for (int i = task.getChildCount() - 1; i >= 0 ; --i) { + final ActivityRecord r = task.getChildAt(i); if (r.getUid() == uid) { return true; } @@ -1195,7 +1190,8 @@ class ActivityStack extends ConfigurationContainer { /** Get all UIDs that are present in the stack. */ void getPresentUIDs(IntArray presentUIDs) { for (TaskRecord task : mTaskHistory) { - for (ActivityRecord r : task.mActivities) { + for (int i = task.getChildCount() - 1; i >= 0 ; --i) { + final ActivityRecord r = task.getChildAt(i); presentUIDs.add(r.getUid()); } } @@ -1207,12 +1203,6 @@ class ActivityStack extends ConfigurationContainer { return display != null && display.isSingleTaskInstance(); } - private void removeActivitiesFromLRUList(TaskRecord task) { - for (ActivityRecord r : task.mActivities) { - mLRUActivities.remove(r); - } - } - /** @return {@code true} if LRU list contained the specified activity. */ final boolean removeActivityFromLRUList(ActivityRecord activity) { return mLRUActivities.remove(activity); @@ -3015,19 +3005,19 @@ class ActivityStack extends ConfigurationContainer { mTaskHistory.remove(task); mTaskHistory.add(position, task); if (mTaskStack != null) { - // TODO: this could not be false after unification. - mTaskStack.positionChildAt(task.getTask(), position); + // TODO: this can not be false after unification Stack. + mTaskStack.positionChildAt(task, position); } - updateTaskMovement(task, true); + task.updateTaskMovement(true); } - private void insertTaskAtTop(TaskRecord task, ActivityRecord starting) { - // TODO: Better place to put all the code below...may be addTask... + void insertTaskAtTop(TaskRecord task, ActivityRecord starting) { + // TODO: Better place to put all the code below...may be addChild... mTaskHistory.remove(task); // Now put task at top. final int position = getAdjustedPositionForTask(task, mTaskHistory.size(), starting); mTaskHistory.add(position, task); - updateTaskMovement(task, true); + task.updateTaskMovement(true); positionChildWindowContainerAtTop(task); } @@ -3035,7 +3025,7 @@ class ActivityStack extends ConfigurationContainer { mTaskHistory.remove(task); final int position = getAdjustedPositionForTask(task, 0, null); mTaskHistory.add(position, task); - updateTaskMovement(task, true); + task.updateTaskMovement(true); positionChildWindowContainerAtBottom(task); } @@ -3069,7 +3059,7 @@ class ActivityStack extends ConfigurationContainer { if (!startIt) { if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to task " + task, new RuntimeException("here").fillInStackTrace()); - r.setTask(rTask); + rTask.positionChildAtTop(r); ActivityOptions.abort(options); return; } @@ -3096,7 +3086,7 @@ class ActivityStack extends ConfigurationContainer { // Slot the activity into the history stack and proceed if (DEBUG_ADD_REMOVE) Slog.i(TAG, "Adding activity " + r + " to stack to task " + task, new RuntimeException("here").fillInStackTrace()); - r.setTask(task); + task.positionChildAtTop(r); // The transition animation and starting window are not needed if {@code allowMoveToFront} // is false, because the activity won't be visible. @@ -3271,7 +3261,7 @@ class ActivityStack extends ConfigurationContainer { // with the same affinity is unlikely to be in the same stack. final TaskRecord targetTask; final ActivityRecord bottom = - !mTaskHistory.isEmpty() && !mTaskHistory.get(0).mActivities.isEmpty() ? + !mTaskHistory.isEmpty() && mTaskHistory.get(0).hasChild() ? mTaskHistory.get(0).getChildAt(0) : null; if (bottom != null && target.taskAffinity.equals(bottom.getTaskRecord().affinity)) { // If the activity currently at the bottom has the @@ -3482,7 +3472,7 @@ class ActivityStack extends ConfigurationContainer { // instance of the same activity? Then we drop the instance // below so it remains singleTop. if (target.info.launchMode == ActivityInfo.LAUNCH_SINGLE_TOP) { - final ArrayList<ActivityRecord> taskActivities = task.mActivities; + final ArrayList<ActivityRecord> taskActivities = task.mChildren; final int targetNdx = taskActivities.indexOf(target); if (targetNdx > 0) { final ActivityRecord p = taskActivities.get(targetNdx - 1); @@ -3636,7 +3626,7 @@ class ActivityStack extends ConfigurationContainer { finishedTask = r.getTaskRecord(); int taskNdx = mTaskHistory.indexOf(finishedTask); final TaskRecord task = finishedTask; - int activityNdx = task.mActivities.indexOf(r); + int activityNdx = task.mChildren.indexOf(r); getDisplay().mDisplayContent.prepareAppTransition( TRANSIT_CRASHING_ACTIVITY_CLOSE, false /* alwaysKeepCurrent */); r.finishIfPossible(reason, false /* oomAdj */); @@ -3773,7 +3763,7 @@ class ActivityStack extends ConfigurationContainer { final boolean navigateUpToLocked(ActivityRecord srec, Intent destIntent, int resultCode, Intent resultData) { final TaskRecord task = srec.getTaskRecord(); - final ArrayList<ActivityRecord> activities = task.mActivities; + final ArrayList<ActivityRecord> activities = task.mChildren; final int start = activities.indexOf(srec); if (!mTaskHistory.contains(task) || (start < 0)) { return false; @@ -3867,8 +3857,16 @@ class ActivityStack extends ConfigurationContainer { * an activity moves away from the stack. */ void onActivityRemovedFromStack(ActivityRecord r) { + removeActivityFromLRUList(r); removeTimeoutsForActivity(r); + // TODO(stack-unify): null check will no longer be needed. + if (mTaskStack != null) { + mTaskStack.mExitingActivities.remove(r); + } + // TODO(stack-unify): Remove if no bugs showed up... + //r.mIsExiting = false; + if (mResumedActivity != null && mResumedActivity == r) { setResumedActivity(null, "onActivityRemovedFromStack"); } @@ -4061,7 +4059,7 @@ class ActivityStack extends ConfigurationContainer { if (DEBUG_CLEANUP) Slog.v(TAG_CLEANUP, "Removing app " + app + " from history with " + i + " entries"); for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { - final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; + final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mChildren; mTmpActivities.clear(); mTmpActivities.addAll(activities); @@ -4150,19 +4148,6 @@ class ActivityStack extends ConfigurationContainer { getDisplay().mDisplayContent.prepareAppTransition(transit, false); } - private void updateTaskMovement(TaskRecord task, boolean toFront) { - if (task.isPersistable) { - task.mLastTimeMoved = System.currentTimeMillis(); - // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most - // recently will be most negative, tasks sent to the bottom before that will be less - // negative. Similarly for recent tasks moved to the top which will be most positive. - if (!toFront) { - task.mLastTimeMoved *= -1; - } - } - mRootActivityContainer.invalidateTaskLayers(); - } - final void moveTaskToFrontLocked(TaskRecord tr, boolean noAnimation, ActivityOptions options, AppTimeTracker timeTracker, String reason) { if (DEBUG_SWITCH) Slog.v(TAG_SWITCH, "moveTaskToFront: " + tr); @@ -4295,7 +4280,7 @@ class ActivityStack extends ConfigurationContainer { mTaskHistory.remove(tr); mTaskHistory.add(0, tr); - updateTaskMovement(tr, false); + tr.updateTaskMovement(false); getDisplay().mDisplayContent.prepareAppTransition(TRANSIT_TASK_TO_BACK, false); moveToBack("moveTaskToBackLocked", tr); @@ -4334,7 +4319,7 @@ class ActivityStack extends ConfigurationContainer { for (int taskIndex = mTaskHistory.indexOf(startTask); taskIndex >= 0; --taskIndex) { final TaskRecord task = mTaskHistory.get(taskIndex); - final ArrayList<ActivityRecord> activities = task.mActivities; + final ArrayList<ActivityRecord> activities = task.mChildren; int activityIndex = (start.getTaskRecord() == task) ? activities.indexOf(start) : activities.size() - 1; for (; activityIndex >= 0; --activityIndex) { @@ -4374,10 +4359,10 @@ class ActivityStack extends ConfigurationContainer { final TaskRecord task = mTaskHistory.get(i); if (task.isResizeable()) { if (tempTaskInsetBounds != null && !tempTaskInsetBounds.isEmpty()) { - task.setDisplayedBounds(taskBounds); + task.setOverrideDisplayedBounds(taskBounds); task.setBounds(tempTaskInsetBounds); } else { - task.setDisplayedBounds(null); + task.setOverrideDisplayedBounds(null); task.setBounds(taskBounds); } } @@ -4429,9 +4414,9 @@ class ActivityStack extends ConfigurationContainer { for (int i = mTaskHistory.size() - 1; i >= 0; i--) { final TaskRecord task = mTaskHistory.get(i); if (bounds == null || bounds.isEmpty()) { - task.setDisplayedBounds(null); + task.setOverrideDisplayedBounds(null); } else if (task.isResizeable()) { - task.setDisplayedBounds(bounds); + task.setOverrideDisplayedBounds(bounds); } } } @@ -4476,7 +4461,7 @@ class ActivityStack extends ConfigurationContainer { TaskRecord lastTask = null; ComponentName homeActivity = null; for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { - final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mActivities; + final ArrayList<ActivityRecord> activities = mTaskHistory.get(taskNdx).mChildren; mTmpActivities.clear(); mTmpActivities.addAll(activities); @@ -4674,7 +4659,7 @@ class ActivityStack extends ConfigurationContainer { pw.println(prefix + "mLastNonFullscreenBounds=" + task.mLastNonFullscreenBounds); pw.println(prefix + "* " + task); task.dump(pw, prefix + " "); - dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mActivities, + dumpHistoryList(fd, pw, mTaskHistory.get(taskNdx).mChildren, prefix, "Hist", true, !dumpAll, dumpClient, dumpPackage, false, null, task); } return true; @@ -4685,15 +4670,15 @@ class ActivityStack extends ConfigurationContainer { if ("all".equals(name)) { for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { - activities.addAll(mTaskHistory.get(taskNdx).mActivities); + activities.addAll(mTaskHistory.get(taskNdx).mChildren); } } else if ("top".equals(name)) { final int top = mTaskHistory.size() - 1; if (top >= 0) { - final ArrayList<ActivityRecord> list = mTaskHistory.get(top).mActivities; - int listTop = list.size() - 1; + final TaskRecord task = mTaskHistory.get(top); + int listTop = task.getChildCount() - 1; if (listTop >= 0) { - activities.add(list.get(listTop)); + activities.add(task.getChildAt(listTop)); } } } else { @@ -4701,7 +4686,9 @@ class ActivityStack extends ConfigurationContainer { matcher.build(name); for (int taskNdx = mTaskHistory.size() - 1; taskNdx >= 0; --taskNdx) { - for (ActivityRecord r1 : mTaskHistory.get(taskNdx).mActivities) { + final TaskRecord task = mTaskHistory.get(taskNdx); + for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { + final ActivityRecord r1 = task.getChildAt(activityNdx); if (matcher.match(r1, r1.intent.getComponent())) { activities.add(r1); } @@ -4733,58 +4720,51 @@ class ActivityStack extends ConfigurationContainer { return starting; } - /** - * Removes the input task from this stack. - * - * @param task to remove. - * @param reason for removal. - * @param mode task removal mode. Either {@link #REMOVE_TASK_MODE_DESTROYING}, - * {@link #REMOVE_TASK_MODE_MOVING}, {@link #REMOVE_TASK_MODE_MOVING_TO_TOP}. - */ - void removeTask(TaskRecord task, String reason, int mode) { - if (!mTaskHistory.remove(task)) { - // Not really in this stack anymore... - return; + // TODO(stack-unify): Merge into removeChild method below. + void onChildRemoved(TaskRecord child, DisplayContent dc) { + mTaskHistory.remove(child); + EventLog.writeEvent(EventLogTags.AM_REMOVE_TASK, child.mTaskId, mStackId); + + ActivityDisplay display = getDisplay(); + if (display == null && dc != null) { + display = dc.mActivityDisplay; } - EventLog.writeEvent(EventLogTags.AM_REMOVE_TASK, task.mTaskId, getStackId()); + if (display.isSingleTaskInstance()) { + mService.notifySingleTaskDisplayEmpty(display.mDisplayId); + } - removeActivitiesFromLRUList(task); - updateTaskMovement(task, true); + display.mDisplayContent.setLayoutNeeded(); - if (mode == REMOVE_TASK_MODE_DESTROYING) { - task.cleanUpResourcesForDestroy(); + if (mTaskHistory.isEmpty()) { + // Stack is now empty... + remove(); } + } + /** + * Removes the input task from this stack. + * + * @param task to remove. + * @param reason for removal. + */ + void removeChild(TaskRecord task, String reason) { final ActivityDisplay display = getDisplay(); - if (mTaskHistory.isEmpty()) { - if (DEBUG_STACK) Slog.i(TAG_STACK, "removeTask: removing stack=" + this); + final boolean topFocused = mRootActivityContainer.isTopDisplayFocusedStack(this); + mTaskStack.removeChild(task); + moveHomeStackToFrontIfNeeded(topFocused, display, reason); + } + + void moveHomeStackToFrontIfNeeded( + boolean wasTopFocusedStack, ActivityDisplay display, String reason) { + if (mTaskHistory.isEmpty() && wasTopFocusedStack) { // We only need to adjust focused stack if this stack is in focus and we are not in the // process of moving the task to the top of the stack that will be focused. - if (mode != REMOVE_TASK_MODE_MOVING_TO_TOP - && mRootActivityContainer.isTopDisplayFocusedStack(this)) { - String myReason = reason + " leftTaskHistoryEmpty"; - if (!inMultiWindowMode() || adjustFocusToNextFocusableStack(myReason) == null) { - display.moveHomeStackToFront(myReason); - } - } - if (isAttached()) { - display.positionChildAtBottom(this); - } - if (!isActivityTypeHome() || !isAttached()) { - remove(); + String myReason = reason + " leftTaskHistoryEmpty"; + if (!inMultiWindowMode() || adjustFocusToNextFocusableStack(myReason) == null) { + display.moveHomeStackToFront(myReason); } } - - task.setStack(null); - - // Notify if a task from the pinned stack is being removed (or moved depending on the mode) - if (inPinnedWindowingMode()) { - mService.getTaskChangeNotificationController().notifyActivityUnpinned(); - } - if (display != null && display.isSingleTaskInstance()) { - mService.notifySingleTaskDisplayEmpty(display.mDisplayId); - } } TaskRecord createTaskRecord(int taskId, ActivityInfo info, Intent intent, @@ -4799,9 +4779,9 @@ class ActivityStack extends ConfigurationContainer { boolean toTop, ActivityRecord activity, ActivityRecord source, ActivityOptions options) { final TaskRecord task = TaskRecord.create( - mService, taskId, info, intent, voiceSession, voiceInteractor); + mService, taskId, info, intent, voiceSession, voiceInteractor, this); // add the task to stack first, mTaskPositioner might need the stack association - addTask(task, toTop, "createTaskRecord"); + addChild(task, toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0); final int displayId = mDisplayId != INVALID_DISPLAY ? mDisplayId : DEFAULT_DISPLAY; final boolean isLockscreenShown = mService.mStackSupervisor.getKeyguardController() .isKeyguardOrAodShowing(displayId); @@ -4810,7 +4790,6 @@ class ActivityStack extends ConfigurationContainer { && !matchParentBounds() && task.isResizeable() && !isLockscreenShown) { task.setBounds(getRequestedOverrideBounds()); } - task.createTask(toTop, (info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0); return task; } @@ -4818,34 +4797,31 @@ class ActivityStack extends ConfigurationContainer { return new ArrayList<>(mTaskHistory); } - void addTask(final TaskRecord task, final boolean toTop, String reason) { - addTask(task, toTop ? MAX_VALUE : 0, true /* schedulePictureInPictureModeChange */, reason); - if (toTop) { - // TODO: figure-out a way to remove this call. - positionChildWindowContainerAtTop(task); - } + // TODO(stack-unify): Merge with addChild below. + void onChildAdded(TaskRecord task, int position) { + final boolean toTop = position >= mTaskHistory.size(); + mTaskHistory.add(position, task); + + // TODO: Feels like this should go in TaskRecord#onParentChanged + task.updateTaskMovement(toTop); } - // TODO: This shouldn't allow automatic reparenting. Remove the call to preAddTask and deal - // with the fall-out... - void addTask(final TaskRecord task, int position, boolean schedulePictureInPictureModeChange, - String reason) { - // TODO: Is this remove really needed? Need to look into the call path for the other addTask - mTaskHistory.remove(task); + void addChild(final TaskRecord task, final boolean toTop, boolean showForAllUsers) { if (isSingleTaskInstance() && !mTaskHistory.isEmpty()) { throw new IllegalStateException("Can only have one child on stack=" + this); } - position = getAdjustedPositionForTask(task, position, null /* starting */); - final boolean toTop = position >= mTaskHistory.size(); - final ActivityStack prevStack = preAddTask(task, reason, toTop); - - mTaskHistory.add(position, task); - task.setStack(this); + final int position = + getAdjustedPositionForTask(task, toTop ? MAX_VALUE : 0, null /* starting */); - updateTaskMovement(task, toTop); + // We only want to move the parents to the parents if we are creating this task at the + // top of its stack. + mTaskStack.addChild(task, position, showForAllUsers, toTop /*moveParents*/); - postAddTask(task, prevStack, schedulePictureInPictureModeChange); + if (toTop) { + // TODO: figure-out a way to remove this call. + positionChildWindowContainerAtTop(task); + } } void positionChildAt(TaskRecord task, int index) { @@ -4860,8 +4836,14 @@ class ActivityStack extends ConfigurationContainer { final ActivityRecord topRunningActivity = task.topRunningActivityLocked(); final boolean wasResumed = topRunningActivity == task.getStack().mResumedActivity; insertTaskAtPosition(task, index); - task.setStack(this); - postAddTask(task, null /* prevStack */, true /* schedulePictureInPictureModeChange */); + + // TODO: Investigate if this random code is really needed. + if (task.voiceSession != null) { + try { + task.voiceSession.taskStarted(task.intent, task.mTaskId); + } catch (RemoteException e) { + } + } if (wasResumed) { if (mResumedActivity != null) { @@ -4878,32 +4860,6 @@ class ActivityStack extends ConfigurationContainer { mRootActivityContainer.resumeFocusedStacksTopActivities(); } - private ActivityStack preAddTask(TaskRecord task, String reason, boolean toTop) { - final ActivityStack prevStack = task.getStack(); - if (prevStack != null && prevStack != this) { - prevStack.removeTask(task, reason, - toTop ? REMOVE_TASK_MODE_MOVING_TO_TOP : REMOVE_TASK_MODE_MOVING); - } - return prevStack; - } - - /** - * @param schedulePictureInPictureModeChange specifies whether or not to schedule the PiP mode - * change. Callers may set this to false if they are explicitly scheduling PiP mode - * changes themselves, like during the PiP animation - */ - private void postAddTask(TaskRecord task, ActivityStack prevStack, - boolean schedulePictureInPictureModeChange) { - if (schedulePictureInPictureModeChange && prevStack != null) { - mStackSupervisor.scheduleUpdatePictureInPictureModeIfNeeded(task, prevStack); - } else if (task.voiceSession != null) { - try { - task.voiceSession.taskStarted(task.intent, task.mTaskId); - } catch (RemoteException e) { - } - } - } - public void setAlwaysOnTop(boolean alwaysOnTop) { if (isAlwaysOnTop() == alwaysOnTop) { return; diff --git a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java index dc3d2631a5d7..f8a7397f10df 100644 --- a/services/core/java/com/android/server/wm/ActivityStackSupervisor.java +++ b/services/core/java/com/android/server/wm/ActivityStackSupervisor.java @@ -52,7 +52,6 @@ import static android.view.WindowManager.TRANSIT_DOCK_TASK_FROM_RECENTS; import static com.android.server.wm.ActivityStack.ActivityState.PAUSED; import static com.android.server.wm.ActivityStack.ActivityState.PAUSING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_ALL; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_IDLE; import static com.android.server.wm.ActivityTaskManagerDebugConfig.DEBUG_PAUSE; @@ -83,6 +82,7 @@ import static com.android.server.wm.TaskRecord.REPARENT_KEEP_STACK_AT_FRONT; import static com.android.server.wm.TaskRecord.REPARENT_LEAVE_STACK_IN_PLACE; import static com.android.server.wm.TaskRecord.REPARENT_MOVE_STACK_TO_FRONT; import static com.android.server.wm.WindowContainer.AnimationFlags.TRANSITION; +import static com.android.server.wm.WindowContainer.POSITION_TOP; import android.Manifest; import android.app.Activity; @@ -1420,7 +1420,7 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { // WM resizeTask must be done after the task is moved to the correct stack, // because Task's setBounds() also updates dim layer's bounds, but that has // dependency on the stack. - task.resizeWindowContainer(); + task.resize(false /* relayout */, false /* forced */); } } @@ -1885,26 +1885,22 @@ public class ActivityStackSupervisor implements RecentTasks.Callbacks { final ActivityStack stack = mRootActivityContainer.getLaunchStack(null, aOptions, task, onTop); final ActivityStack currentStack = task.getStack(); + + if (currentStack == stack) { + // Nothing else to do since it is already restored in the right stack. + return true; + } + if (currentStack != null) { - // Task has already been restored once. See if we need to do anything more - if (currentStack == stack) { - // Nothing else to do since it is already restored in the right stack. - return true; - } - // Remove current stack association, so we can re-associate the task with the - // right stack below. - currentStack.removeTask(task, "restoreRecentTaskLocked", REMOVE_TASK_MODE_MOVING); + // Task has already been restored once. Just re-parent it to the new stack. + task.reparent(stack.mTaskStack, + POSITION_TOP, true /*moveParents*/, "restoreRecentTaskLocked"); + return true; } - stack.addTask(task, onTop, "restoreRecentTask"); - // TODO: move call for creation here and other place into Stack.addTask() - task.createTask(onTop, true /* showForAllUsers */); + stack.addChild(task, onTop, true /* showForAllUsers */); if (DEBUG_RECENTS) Slog.v(TAG_RECENTS, "Added restored task=" + task + " to stack=" + stack); - for (int activityNdx = task.getChildCount() - 1; activityNdx >= 0; --activityNdx) { - final ActivityRecord r = task.getChildAt(activityNdx); - r.setTask(task); - } return true; } diff --git a/services/core/java/com/android/server/wm/ActivityStarter.java b/services/core/java/com/android/server/wm/ActivityStarter.java index d1bb2559e5be..6edcb0298938 100644 --- a/services/core/java/com/android/server/wm/ActivityStarter.java +++ b/services/core/java/com/android/server/wm/ActivityStarter.java @@ -50,6 +50,7 @@ import static android.content.Intent.FLAG_ACTIVITY_RETAIN_IN_RECENTS; import static android.content.Intent.FLAG_ACTIVITY_SINGLE_TOP; import static android.content.Intent.FLAG_ACTIVITY_TASK_ON_HOME; import static android.content.pm.ActivityInfo.DOCUMENT_LAUNCH_ALWAYS; +import static android.content.pm.ActivityInfo.FLAG_SHOW_FOR_ALL_USERS; import static android.content.pm.ActivityInfo.LAUNCH_MULTIPLE; import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_INSTANCE; import static android.content.pm.ActivityInfo.LAUNCH_SINGLE_TASK; @@ -1842,7 +1843,7 @@ class ActivityStarter { // {@code ActivityRecord} removing its reference to the {@code TaskRecord}. The task // reference is needed in the call below to {@link setTargetStackAndMoveToFrontIfNeeded} if (targetTaskTop.getTaskRecord() == null) { - targetTaskTop.setTask(targetTask); + targetTask.addChild(targetTaskTop); } if (top != null) { @@ -1862,8 +1863,8 @@ class ActivityStarter { // Go ahead and reset it. mTargetStack = computeStackFocus(mSourceRecord, false /* newTask */, mLaunchFlags, mOptions); - mTargetStack.addTask(targetTask, - !mLaunchTaskBehind /* toTop */, "complyActivityFlags"); + mTargetStack.addChild(targetTask, !mLaunchTaskBehind /* toTop */, + (mStartActivity.info.flags & FLAG_SHOW_FOR_ALL_USERS) != 0); } } } else if ((mLaunchFlags & FLAG_ACTIVITY_CLEAR_TOP) == 0 && !mAddingToTask diff --git a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java index 222f26edaf5d..da7af5fdd369 100644 --- a/services/core/java/com/android/server/wm/ActivityTaskManagerService.java +++ b/services/core/java/com/android/server/wm/ActivityTaskManagerService.java @@ -85,7 +85,6 @@ import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.Scr import static com.android.server.am.ActivityManagerServiceDumpProcessesProto.ScreenCompatPackage.PACKAGE; import static com.android.server.wm.ActivityStack.ActivityState.DESTROYED; import static com.android.server.wm.ActivityStack.ActivityState.DESTROYING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.wm.ActivityStackSupervisor.DEFER_RESUME; import static com.android.server.wm.ActivityStackSupervisor.ON_TOP; import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS; @@ -1996,7 +1995,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { return false; } final TaskRecord task = r.getTaskRecord(); - int index = task.mActivities.lastIndexOf(r); + int index = task.mChildren.lastIndexOf(r); if (index > 0) { ActivityRecord under = task.getChildAt(index - 1); under.returningOptions = safeOptions != null ? safeOptions.getOptions(r) : null; @@ -2221,18 +2220,10 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { Slog.w(TAG, "getTaskBounds: taskId=" + taskId + " not found"); return rect; } - if (task.getStack() != null) { - // Return the bounds from window manager since it will be adjusted for various - // things like the presense of a docked stack for tasks that aren't resizeable. - task.getWindowContainerBounds(rect); - } else { - // Task isn't in window manager yet since it isn't associated with a stack. - // Return the persist value from activity manager - if (!task.matchParentBounds()) { - rect.set(task.getBounds()); - } else if (task.mLastNonFullscreenBounds != null) { - rect.set(task.mLastNonFullscreenBounds); - } + if (task.getParent() != null) { + rect.set(task.getBounds()); + } else if (task.mLastNonFullscreenBounds != null) { + rect.set(task.mLastNonFullscreenBounds); } } } finally { @@ -2249,7 +2240,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { final TaskRecord tr = mRootActivityContainer.anyTaskForId(id, MATCH_TASK_IN_STACKS_OR_RECENT_TASKS); if (tr != null) { - return tr.mTaskDescription; + return tr.getTaskDescription(); } } return null; @@ -3168,10 +3159,10 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { null /* voiceSession */, null /* voiceInteractor */, !ON_TOP); if (!mRecentTasks.addToBottom(task)) { // The app has too many tasks already and we can't add any more - stack.removeTask(task, "addAppTask", REMOVE_TASK_MODE_DESTROYING); + stack.removeChild(task, "addAppTask"); return INVALID_TASK_ID; } - task.mTaskDescription.copyFrom(description); + task.getTaskDescription().copyFrom(description); // TODO: Send the thumbnail to WM to store it. @@ -4489,7 +4480,7 @@ public class ActivityTaskManagerService extends IActivityTaskManager.Stub { Slog.w(TAG, "cancelTaskWindowTransition: taskId=" + taskId + " not found"); return; } - task.cancelWindowTransition(); + task.cancelTaskWindowTransition(); } } finally { Binder.restoreCallingIdentity(ident); diff --git a/services/core/java/com/android/server/wm/ConfigurationContainer.java b/services/core/java/com/android/server/wm/ConfigurationContainer.java index 8b4f7cc571f8..30f3bc5e70fb 100644 --- a/services/core/java/com/android/server/wm/ConfigurationContainer.java +++ b/services/core/java/com/android/server/wm/ConfigurationContainer.java @@ -134,9 +134,9 @@ public abstract class ConfigurationContainer<E extends ConfigurationContainer> { onConfigurationChanged(newParentConfig, true /*forwardToChildren*/); } - // TODO: Consolidate with onConfigurationChanged() method above once unification is done. This - // is only currently need during the process of unification where we don't want configuration - // forwarded to a child from both parents. + // TODO(root-unify): Consolidate with onConfigurationChanged() method above once unification is + // done. This is only currently need during the process of unification where we don't want + // configuration forwarded to a child from both parents. public void onConfigurationChanged(Configuration newParentConfig, boolean forwardToChildren) { mResolvedTmpConfig.setTo(mResolvedOverrideConfiguration); resolveOverrideConfiguration(newParentConfig); diff --git a/services/core/java/com/android/server/wm/DisplayContent.java b/services/core/java/com/android/server/wm/DisplayContent.java index 89568ebf4277..d1d468b5ae3d 100644 --- a/services/core/java/com/android/server/wm/DisplayContent.java +++ b/services/core/java/com/android/server/wm/DisplayContent.java @@ -2409,7 +2409,19 @@ class DisplayContent extends WindowContainer<DisplayContent.DisplayChildWindowCo /** Returns true if a removal action is still being deferred. */ @Override boolean checkCompleteDeferredRemoval() { - final boolean stillDeferringRemoval = super.checkCompleteDeferredRemoval(); + boolean stillDeferringRemoval = false; + + for (int i = getChildCount() - 1; i >= 0; --i) { + final DisplayChildWindowContainer child = getChildAt(i); + stillDeferringRemoval |= child.checkCompleteDeferredRemoval(); + if (getChildCount() == 0) { + // If this display is pending to be removed because it contains an activity with + // {@link ActivityRecord#mIsExiting} is true, this display may be removed when + // completing the removal of the last activity from + // {@link ActivityRecord#checkCompleteDeferredRemoval}. + return false; + } + } if (!stillDeferringRemoval && mDeferredRemoval) { removeImmediately(); diff --git a/services/core/java/com/android/server/wm/RecentsAnimation.java b/services/core/java/com/android/server/wm/RecentsAnimation.java index 2dae12642be3..01cbc5d1e880 100644 --- a/services/core/java/com/android/server/wm/RecentsAnimation.java +++ b/services/core/java/com/android/server/wm/RecentsAnimation.java @@ -211,9 +211,9 @@ class RecentsAnimation implements RecentsAnimationCallbacks, // If there are multiple tasks in the target stack (ie. the home stack, with 3p // and default launchers coexisting), then move the task to the top as a part of // moving the stack to the front - if (targetStack.topTask() != targetActivity.getTaskRecord()) { - targetStack.addTask(targetActivity.getTaskRecord(), true /* toTop */, - "startRecentsActivity"); + final TaskRecord task = targetActivity.getTaskRecord(); + if (targetStack.topTask() != task) { + targetStack.insertTaskAtTop(task, targetActivity); } } else { // No recents activity, create the new recents activity bottom most diff --git a/services/core/java/com/android/server/wm/RootActivityContainer.java b/services/core/java/com/android/server/wm/RootActivityContainer.java index 51a3e7205489..dc78922ef4fc 100644 --- a/services/core/java/com/android/server/wm/RootActivityContainer.java +++ b/services/core/java/com/android/server/wm/RootActivityContainer.java @@ -1265,8 +1265,7 @@ class RootActivityContainer extends ConfigurationContainer : task.realActivity != null ? task.realActivity.flattenToString() : task.getTopActivity() != null ? task.getTopActivity().packageName : "unknown"; - taskBounds[i] = new Rect(); - task.getWindowContainerBounds(taskBounds[i]); + taskBounds[i] = mService.getTaskBounds(task.mTaskId); taskUserIds[i] = task.mUserId; } info.taskIds = taskIds; @@ -1876,7 +1875,12 @@ class RootActivityContainer extends ConfigurationContainer ActivityStack getNextFocusableStack(@NonNull ActivityStack currentFocus, boolean ignoreCurrent) { // First look for next focusable stack on the same display - final ActivityDisplay preferredDisplay = currentFocus.getDisplay(); + ActivityDisplay preferredDisplay = currentFocus.getDisplay(); + if (preferredDisplay == null) { + // Stack is currently detached because it is being removed. Use the previous display it + // was on. + preferredDisplay = getActivityDisplay(currentFocus.mPrevDisplayId); + } final ActivityStack preferredFocusableStack = preferredDisplay.getNextFocusableStack( currentFocus, ignoreCurrent); if (preferredFocusableStack != null) { diff --git a/services/core/java/com/android/server/wm/RootWindowContainer.java b/services/core/java/com/android/server/wm/RootWindowContainer.java index f5d3affa89ef..149bcfb991ea 100644 --- a/services/core/java/com/android/server/wm/RootWindowContainer.java +++ b/services/core/java/com/android/server/wm/RootWindowContainer.java @@ -206,7 +206,7 @@ class RootWindowContainer extends WindowContainer<DisplayContent> } @Override - void onChildPositionChanged() { + void onChildPositionChanged(WindowContainer child) { mWmService.updateFocusedWindowLocked(UPDATE_FOCUS_NORMAL, !mWmService.mPerDisplayFocusEnabled /* updateInputWindows */); } diff --git a/services/core/java/com/android/server/wm/Task.java b/services/core/java/com/android/server/wm/Task.java index 634990b5fdf2..dce15bc8acf8 100644 --- a/services/core/java/com/android/server/wm/Task.java +++ b/services/core/java/com/android/server/wm/Task.java @@ -16,6 +16,7 @@ package com.android.server.wm; +import static android.app.ActivityTaskManager.INVALID_STACK_ID; import static android.app.ActivityTaskManager.RESIZE_MODE_SYSTEM_SCREEN_ROTATION; import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_LANDSCAPE_ONLY; import static android.content.pm.ActivityInfo.RESIZE_MODE_FORCE_RESIZABLE_PORTRAIT_ONLY; @@ -24,6 +25,7 @@ import static android.content.pm.ActivityInfo.SCREEN_ORIENTATION_UNSET; import static android.content.res.Configuration.EMPTY; import static android.view.SurfaceControl.METADATA_TASK_ID; +import static com.android.server.EventLogTags.WM_TASK_CREATED; import static com.android.server.EventLogTags.WM_TASK_REMOVED; import static com.android.server.wm.DragResizeMode.DRAG_RESIZE_MODE_DOCKED_DIVIDER; import static com.android.server.wm.TaskProto.APP_WINDOW_TOKENS; @@ -63,17 +65,21 @@ import java.util.function.Consumer; class Task extends WindowContainer<ActivityRecord> implements ConfigurationContainerListener{ static final String TAG = TAG_WITH_CLASS_NAME ? "Task" : TAG_WM; + final ActivityTaskManagerService mAtmService; + // TODO: Track parent marks like this in WindowContainer. TaskStack mStack; /* Unique identifier for this task. */ final int mTaskId; /* User for which this task was created. */ - final int mUserId; + // TODO: Make final + int mUserId; final Rect mPreparedFrozenBounds = new Rect(); final Configuration mPreparedFrozenMergedConfig = new Configuration(); // If non-empty, bounds used to display the task during animations/interactions. + // TODO(b/119687367): This member is temporary. private final Rect mOverrideDisplayedBounds = new Rect(); /** ID of the display which rotation {@link #mRotation} has. */ @@ -90,11 +96,12 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta private Rect mTmpRect2 = new Rect(); // Resize mode of the task. See {@link ActivityInfo#resizeMode} - private int mResizeMode; + // Based on the {@link ActivityInfo#resizeMode} of the root activity. + int mResizeMode; - // Whether the task supports picture-in-picture. - // See {@link ActivityInfo#FLAG_SUPPORTS_PICTURE_IN_PICTURE} - private boolean mSupportsPictureInPicture; + // Whether or not this task and its activities support PiP. Based on the + // {@link ActivityInfo#FLAG_SUPPORTS_PICTURE_IN_PICTURE} flag of the root activity. + boolean mSupportsPictureInPicture; // Whether the task is currently being drag-resized private boolean mDragResizing; @@ -116,40 +123,23 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta /** @see #setCanAffectSystemUiFlags */ private boolean mCanAffectSystemUiFlags = true; - // TODO: remove after unification - TaskRecord mTaskRecord; - - // TODO: Remove after unification. - @Override - public void onConfigurationChanged(Configuration newParentConfig, boolean forwardToChildren) { - // Forward configuration changes in cases - // - children won't get it from TaskRecord - // - it's a pinned task - forwardToChildren &= (mTaskRecord == null) || inPinnedWindowingMode(); - super.onConfigurationChanged(newParentConfig, forwardToChildren); - } - - Task(int taskId, TaskStack stack, int userId, WindowManagerService service, int resizeMode, - boolean supportsPictureInPicture, TaskDescription taskDescription, - TaskRecord taskRecord) { - super(service); + Task(int taskId, TaskStack stack, int userId, int resizeMode, boolean supportsPictureInPicture, + TaskDescription taskDescription, ActivityTaskManagerService atm) { + super(atm.mWindowManager); + mAtmService = atm; mTaskId = taskId; mStack = stack; mUserId = userId; mResizeMode = resizeMode; mSupportsPictureInPicture = supportsPictureInPicture; - mTaskRecord = taskRecord; mTaskDescription = taskDescription; + EventLog.writeEvent(WM_TASK_CREATED, mTaskId, + stack != null ? stack.mStackId : INVALID_STACK_ID); // Tasks have no set orientation value (including SCREEN_ORIENTATION_UNSPECIFIED). setOrientation(SCREEN_ORIENTATION_UNSET); - if (mTaskRecord != null) { - // This can be null when we call createTaskInStack in WindowTestUtils. Remove this after - // unification. - mTaskRecord.registerConfigurationChangeListener(this); - } else { - setBounds(getResolvedOverrideBounds()); - } + // TODO(task-merge): Is this really needed? + setBounds(getResolvedOverrideBounds()); } @Override @@ -157,37 +147,40 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta return mStack != null ? mStack.getDisplayContent() : null; } - private int getAdjustedAddPosition(int suggestedPosition) { - final int size = mChildren.size(); - if (suggestedPosition >= size) { - return Math.min(size, suggestedPosition); + int getAdjustedAddPosition(ActivityRecord r, int suggestedPosition) { + int maxPosition = mChildren.size(); + if (!r.mTaskOverlay) { + // We want to place all non-overlay activities below overlays. + while (maxPosition > 0) { + final ActivityRecord current = mChildren.get(maxPosition - 1); + if (current.mTaskOverlay && !current.removed) { + --maxPosition; + continue; + } + break; + } + if (maxPosition < 0) { + maxPosition = 0; + } } - for (int pos = 0; pos < size && pos < suggestedPosition; ++pos) { + if (suggestedPosition >= maxPosition) { + return Math.min(maxPosition, suggestedPosition); + } + + for (int pos = 0; pos < maxPosition && pos < suggestedPosition; ++pos) { // TODO: Confirm that this is the behavior we want long term. if (mChildren.get(pos).removed) { // suggestedPosition assumes removed tokens are actually gone. ++suggestedPosition; } } - return Math.min(size, suggestedPosition); - } - - @Override - void addChild(ActivityRecord child, int position) { - position = getAdjustedAddPosition(position); - super.addChild(child, position); - - // Inform the TaskRecord side of the child addition - // TODO(task-unify): Will be removed after task unification. - if (mTaskRecord != null) { - mTaskRecord.onChildAdded(child, position); - } + return Math.min(maxPosition, suggestedPosition); } @Override void positionChildAt(int position, ActivityRecord child, boolean includingParents) { - position = getAdjustedAddPosition(position); + position = getAdjustedAddPosition(child, position); super.positionChildAt(position, child, includingParents); } @@ -222,47 +215,34 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta void removeImmediately() { if (DEBUG_STACK) Slog.i(TAG, "removeTask: removing taskId=" + mTaskId); EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "removeTask"); - if (mTaskRecord != null) { - mTaskRecord.unregisterConfigurationChangeListener(this); - } - super.removeImmediately(); } - void reparent(TaskStack stack, int position, boolean moveParents) { - if (stack == mStack) { - throw new IllegalArgumentException( - "task=" + this + " already child of stack=" + mStack); - } - if (stack == null) { - throw new IllegalArgumentException("reparent: could not find stack."); - } + // TODO: Consolidate this with TaskRecord.reparent() + void reparent(TaskStack stack, int position, boolean moveParents, String reason) { if (DEBUG_STACK) Slog.i(TAG, "reParentTask: removing taskId=" + mTaskId + " from stack=" + mStack); EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "reParentTask"); - final DisplayContent prevDisplayContent = getDisplayContent(); - - // If we are moving from the fullscreen stack to the pinned stack - // then we want to preserve our insets so that there will not - // be a jump in the area covered by system decorations. We rely - // on the pinned animation to later unset this value. - if (stack.inPinnedWindowingMode()) { - mPreserveNonFloatingState = true; - } else { - mPreserveNonFloatingState = false; - } - getParent().removeChild(this); - stack.addTask(this, position, showForAllUsers(), moveParents); + final ActivityStack prevStack = mStack.mActivityStack; + final boolean wasTopFocusedStack = + mAtmService.mRootActivityContainer.isTopDisplayFocusedStack(prevStack); + final ActivityDisplay prevStackDisplay = prevStack.getDisplay(); - // Relayout display(s). - final DisplayContent displayContent = stack.getDisplayContent(); - displayContent.setLayoutNeeded(); - if (prevDisplayContent != displayContent) { - onDisplayChanged(displayContent); - prevDisplayContent.setLayoutNeeded(); + reparent(stack, position); + + if (!moveParents) { + // Only move home stack forward if we are not going to move the new parent forward. + prevStack.moveHomeStackToFrontIfNeeded(wasTopFocusedStack, prevStackDisplay, reason); } - getDisplayContent().layoutAndAssignWindowLayersIfNeeded(); + + mStack = stack; + stack.positionChildAt(position, this, moveParents); + + // If we are moving from the fullscreen stack to the pinned stack then we want to preserve + // our insets so that there will not be a jump in the area covered by system decorations. + // We rely on the pinned animation to later unset this value. + mPreserveNonFloatingState = stack.inPinnedWindowingMode(); } /** @see ActivityTaskManagerService#positionTaskInStack(int, int, int). */ @@ -270,46 +250,6 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta mStack.positionChildAt(position, this, false /* includingParents */); } - @Override - void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { - super.onParentChanged(newParent, oldParent); - - // Update task bounds if needed. - adjustBoundsForDisplayChangeIfNeeded(getDisplayContent()); - - if (getWindowConfiguration().windowsAreScaleable()) { - // We force windows out of SCALING_MODE_FREEZE so that we can continue to animate them - // while a resize is pending. - forceWindowsScaleable(true /* force */); - } else { - forceWindowsScaleable(false /* force */); - } - } - - @Override - void removeChild(ActivityRecord child) { - if (!mChildren.contains(child)) { - Slog.e(TAG, "removeChild: token=" + this + " not found."); - return; - } - - super.removeChild(child); - - // Inform the TaskRecord side of the child removal - // TODO(task-unify): Will be removed after task unification. - if (mTaskRecord != null) { - mTaskRecord.onChildRemoved(child); - } - - // TODO(task-unify): Need to make this account for what we are doing in - // ActivityRecord.removeFromHistory so that the task isn't removed in some situations when - // we unify task level. - if (mChildren.isEmpty()) { - EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, "removeActivity: last activity"); - removeIfPossible(); - } - } - void setSendingToBottom(boolean toBottom) { for (int appTokenNdx = 0; appTokenNdx < mChildren.size(); appTokenNdx++) { mChildren.get(appTokenNdx).sendingToBottom = toBottom; @@ -331,7 +271,7 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta @Override public int setBounds(Rect bounds) { int rotation = Surface.ROTATION_0; - final DisplayContent displayContent = mStack.getDisplayContent(); + final DisplayContent displayContent = mStack != null ? mStack.getDisplayContent() : null; if (displayContent != null) { rotation = displayContent.getDisplayInfo().rotation; } else if (bounds == null) { @@ -355,9 +295,8 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta // No one in higher hierarchy handles this request, let's adjust our bounds to fulfill // it if possible. - // TODO: Move to TaskRecord after unification is done. - if (mTaskRecord != null && mTaskRecord.getParent() != null) { - mTaskRecord.onConfigurationChanged(mTaskRecord.getParent().getConfiguration()); + if (getParent() != null) { + onConfigurationChanged(getParent().getConfiguration()); return true; } return false; @@ -379,8 +318,9 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta } /** - * Sets bounds that override where the task is displayed. Used during transient operations - * like animation / interaction. + * Displayed bounds are used to set where the task is drawn at any given time. This is + * separate from its actual bounds so that the app doesn't see any meaningful configuration + * changes during transitionary periods. */ void setOverrideDisplayedBounds(Rect overrideDisplayedBounds) { if (overrideDisplayedBounds != null) { @@ -399,13 +339,13 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta return mOverrideDisplayedBounds; } - void setResizeable(int resizeMode) { - mResizeMode = resizeMode; + boolean isResizeable(boolean checkSupportsPip) { + return (mAtmService.mForceResizableActivities || ActivityInfo.isResizeableMode(mResizeMode) + || (checkSupportsPip && mSupportsPictureInPicture)); } boolean isResizeable() { - return ActivityInfo.isResizeableMode(mResizeMode) || mSupportsPictureInPicture - || mWmService.mAtmService.mForceResizableActivities; + return isResizeable(true /* checkSupportsPip */); } /** @@ -462,6 +402,10 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta } } + /** + * Gets the current overridden displayed bounds. These will be empty if the task is not + * currently overriding where it is displayed. + */ @Override public Rect getDisplayedBounds() { if (mOverrideDisplayedBounds.isEmpty()) { @@ -577,7 +521,7 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta setDragResizing(resizing, DRAG_RESIZE_MODE_DOCKED_DIVIDER); } - private void adjustBoundsForDisplayChangeIfNeeded(final DisplayContent displayContent) { + void adjustBoundsForDisplayChangeIfNeeded(final DisplayContent displayContent) { if (displayContent == null) { return; } @@ -618,9 +562,7 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta displayContent.rotateBounds(mRotation, newRotation, mTmpRect2); if (setBounds(mTmpRect2) != BOUNDS_CHANGE_NONE) { - if (mTaskRecord != null) { - mTaskRecord.requestResize(getBounds(), RESIZE_MODE_SYSTEM_SCREEN_ROTATION); - } + mAtmService.resizeTask(mTaskId, getBounds(), RESIZE_MODE_SYSTEM_SCREEN_ROTATION); } } @@ -758,7 +700,8 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta } void onSnapshotChanged(ActivityManager.TaskSnapshot snapshot) { - mTaskRecord.onSnapshotChanged(snapshot); + mAtmService.getTaskChangeNotificationController().notifyTaskSnapshotChanged( + mTaskId, snapshot); } TaskDescription getTaskDescription() { @@ -794,11 +737,6 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta mDimmer.dontAnimateExit(); } - @Override - public String toString() { - return "{taskId=" + mTaskId + " appTokens=" + mChildren + "}"; - } - String getName() { return toShortString(); } @@ -825,9 +763,8 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta } } - @CallSuper - @Override - public void writeToProto(ProtoOutputStream proto, long fieldId, + // TODO(proto-merge): Remove once protos for TaskRecord and Task are merged. + void writeToProtoInnerTaskOnly(ProtoOutputStream proto, long fieldId, @WindowTraceLogLevel int logLevel) { if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) { return; @@ -843,8 +780,10 @@ class Task extends WindowContainer<ActivityRecord> implements ConfigurationConta proto.write(FILLS_PARENT, matchParentBounds()); getBounds().writeToProto(proto, BOUNDS); mOverrideDisplayedBounds.writeToProto(proto, DISPLAYED_BOUNDS); - proto.write(SURFACE_WIDTH, mSurfaceControl.getWidth()); - proto.write(SURFACE_HEIGHT, mSurfaceControl.getHeight()); + if (mSurfaceControl != null) { + proto.write(SURFACE_WIDTH, mSurfaceControl.getWidth()); + proto.write(SURFACE_HEIGHT, mSurfaceControl.getHeight()); + } proto.end(token); } diff --git a/services/core/java/com/android/server/wm/TaskRecord.java b/services/core/java/com/android/server/wm/TaskRecord.java index 6920d9d3a770..672827fbb5ee 100644 --- a/services/core/java/com/android/server/wm/TaskRecord.java +++ b/services/core/java/com/android/server/wm/TaskRecord.java @@ -52,11 +52,10 @@ import static android.os.Trace.TRACE_TAG_WINDOW_MANAGER; import static android.provider.Settings.Secure.USER_SETUP_COMPLETE; import static android.view.Display.DEFAULT_DISPLAY; -import static com.android.server.EventLogTags.WM_TASK_CREATED; +import static com.android.server.EventLogTags.WM_TASK_REMOVED; import static com.android.server.am.TaskRecordProto.ACTIVITIES; import static com.android.server.am.TaskRecordProto.ACTIVITY_TYPE; import static com.android.server.am.TaskRecordProto.BOUNDS; -import static com.android.server.am.TaskRecordProto.CONFIGURATION_CONTAINER; import static com.android.server.am.TaskRecordProto.FULLSCREEN; import static com.android.server.am.TaskRecordProto.ID; import static com.android.server.am.TaskRecordProto.LAST_NON_FULLSCREEN_BOUNDS; @@ -66,11 +65,9 @@ import static com.android.server.am.TaskRecordProto.ORIG_ACTIVITY; import static com.android.server.am.TaskRecordProto.REAL_ACTIVITY; import static com.android.server.am.TaskRecordProto.RESIZE_MODE; import static com.android.server.am.TaskRecordProto.STACK_ID; +import static com.android.server.am.TaskRecordProto.TASK; import static com.android.server.wm.ActivityRecord.FINISH_RESULT_REMOVED; import static com.android.server.wm.ActivityRecord.STARTING_WINDOW_SHOWN; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING_TO_TOP; import static com.android.server.wm.ActivityStackSupervisor.ON_TOP; import static com.android.server.wm.ActivityStackSupervisor.PRESERVE_WINDOWS; import static com.android.server.wm.ActivityStackSupervisor.REMOVE_FROM_RECENTS; @@ -85,10 +82,6 @@ import static com.android.server.wm.ActivityTaskManagerDebugConfig.POSTFIX_TASKS import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_ATM; import static com.android.server.wm.ActivityTaskManagerDebugConfig.TAG_WITH_CLASS_NAME; import static com.android.server.wm.ProtoLogGroup.WM_DEBUG_ADD_REMOVE; -import static com.android.server.wm.WindowContainer.POSITION_BOTTOM; -import static com.android.server.wm.WindowContainer.POSITION_TOP; -import static com.android.server.wm.WindowManagerDebugConfig.DEBUG_STACK; -import static com.android.server.wm.WindowManagerDebugConfig.TAG_WM; import static java.lang.Integer.MAX_VALUE; @@ -143,7 +136,7 @@ import java.lang.annotation.RetentionPolicy; import java.util.ArrayList; import java.util.Objects; -class TaskRecord extends ConfigurationContainer { +class TaskRecord extends Task { private static final String TAG = TAG_WITH_CLASS_NAME ? "TaskRecord" : TAG_ATM; private static final String TAG_ADD_REMOVE = TAG + POSTFIX_ADD_REMOVE; private static final String TAG_RECENTS = TAG + POSTFIX_RECENTS; @@ -212,7 +205,6 @@ class TaskRecord extends ConfigurationContainer { */ private static TaskRecordFactory sTaskRecordFactory; - final int mTaskId; // Unique identifier for this task. String affinity; // The affinity name for this task, or null; may change identity. String rootAffinity; // Initial base affinity, or null; does not change from initial root. final IVoiceInteractionSession voiceSession; // Voice interaction session driving task @@ -238,17 +230,11 @@ class TaskRecord extends ConfigurationContainer { boolean hasBeenVisible; // Set if any activities in the task have been visible to the user. String stringName; // caching of toString() result. - int mUserId; // user for which this task was created boolean mUserSetupComplete; // The user set-up is complete as of the last time the task activity // was changed. int numFullscreen; // Number of fullscreen activities. - int mResizeMode; // The resize mode of this task and its activities. - // Based on the {@link ActivityInfo#resizeMode} of the root activity. - private boolean mSupportsPictureInPicture; // Whether or not this task and its activities - // support PiP. Based on the {@link ActivityInfo#FLAG_SUPPORTS_PICTURE_IN_PICTURE} flag - // of the root activity. /** Can't be put in lockTask mode. */ final static int LOCK_TASK_AUTH_DONT_LOCK = 0; /** Can enter app pinning with user approval. Can never start over existing lockTask task. */ @@ -264,13 +250,6 @@ class TaskRecord extends ConfigurationContainer { int mLockTaskUid = -1; // The uid of the application that called startLockTask(). - // This represents the last resolved activity values for this task - // NOTE: This value needs to be persisted with each task - TaskDescription mTaskDescription; - - /** List of all activities in the task arranged in history order */ - final ArrayList<ActivityRecord> mActivities; - /** Current stack. Setter must always be used to update the value. */ private ActivityStack mStack; @@ -308,8 +287,6 @@ class TaskRecord extends ConfigurationContainer { int mCallingUid; String mCallingPackage; - final ActivityTaskManagerService mAtmService; - private final Rect mTmpStableBounds = new Rect(); private final Rect mTmpNonDecorBounds = new Rect(); private final Rect mTmpBounds = new Rect(); @@ -328,17 +305,9 @@ class TaskRecord extends ConfigurationContainer { // This number will be assigned when we evaluate OOM scores for all visible tasks. int mLayerRank = -1; - // When non-empty, this represents the bounds this task will be drawn at. This gets set during - // transient operations such as split-divider dragging and animations. - // TODO(b/119687367): This member is temporary. - final Rect mDisplayedBounds = new Rect(); - /** Helper object used for updating override configuration. */ private Configuration mTmpConfig = new Configuration(); - // TODO: remove after unification - Task mTask; - /** Used by fillTaskInfo */ final TaskActivitiesReport mReuseActivitiesReport = new TaskActivitiesReport(); @@ -346,21 +315,21 @@ class TaskRecord extends ConfigurationContainer { * Don't use constructor directly. Use {@link #create(ActivityTaskManagerService, int, * ActivityInfo, Intent, TaskDescription)} instead. */ - TaskRecord(ActivityTaskManagerService atmService, int _taskId, ActivityInfo info, - Intent _intent, IVoiceInteractionSession _voiceSession, - IVoiceInteractor _voiceInteractor, TaskDescription _taskDescription) { + TaskRecord(ActivityTaskManagerService atmService, int _taskId, ActivityInfo info, Intent _intent, + IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, + TaskDescription _taskDescription, ActivityStack stack) { this(atmService, _taskId, _intent, null /*_affinityIntent*/, null /*_affinity*/, null /*_rootAffinity*/, null /*_realActivity*/, null /*_origActivity*/, false /*_rootWasReset*/, false /*_autoRemoveRecents*/, false /*_askedCompatMode*/, UserHandle.getUserId(info.applicationInfo.uid), 0 /*_effectiveUid*/, - null /*_lastDescription*/, new ArrayList<>(), System.currentTimeMillis(), + null /*_lastDescription*/, System.currentTimeMillis(), true /*neverRelinquishIdentity*/, _taskDescription != null ? _taskDescription : new TaskDescription(), _taskId, INVALID_TASK_ID, INVALID_TASK_ID, 0 /*taskAffiliationColor*/, info.applicationInfo.uid, info.packageName, info.resizeMode, info.supportsPictureInPicture(), false /*_realActivitySuspended*/, false /*userSetupComplete*/, INVALID_MIN_SIZE, INVALID_MIN_SIZE, info, - _voiceSession, _voiceInteractor); + _voiceSession, _voiceInteractor, stack); } /** Don't use constructor directly. This is only used by XML parser. */ @@ -368,15 +337,16 @@ class TaskRecord extends ConfigurationContainer { Intent _affinityIntent, String _affinity, String _rootAffinity, ComponentName _realActivity, ComponentName _origActivity, boolean _rootWasReset, boolean _autoRemoveRecents, boolean _askedCompatMode, int _userId, - int _effectiveUid, String _lastDescription, ArrayList<ActivityRecord> activities, + int _effectiveUid, String _lastDescription, long lastTimeMoved, boolean neverRelinquishIdentity, TaskDescription _lastTaskDescription, int taskAffiliation, int prevTaskId, int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, int resizeMode, boolean supportsPictureInPicture, boolean _realActivitySuspended, boolean userSetupComplete, int minWidth, int minHeight, ActivityInfo info, - IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor) { - mAtmService = atmService; - mTaskId = _taskId; + IVoiceInteractionSession _voiceSession, IVoiceInteractor _voiceInteractor, + ActivityStack stack) { + super(_taskId, stack != null ? stack.mTaskStack : null, _userId, resizeMode, + supportsPictureInPicture, _lastTaskDescription, atmService); mRemoteToken = new RemoteToken(this); affinityIntent = _affinityIntent; affinity = _affinity; @@ -390,15 +360,12 @@ class TaskRecord extends ConfigurationContainer { isAvailable = true; autoRemoveRecents = _autoRemoveRecents; askedCompatMode = _askedCompatMode; - mUserId = _userId; mUserSetupComplete = userSetupComplete; effectiveUid = _effectiveUid; touchActiveTime(); lastDescription = _lastDescription; - mActivities = activities; mLastTimeMoved = lastTimeMoved; mNeverRelinquishIdentity = neverRelinquishIdentity; - mTaskDescription = _lastTaskDescription; mAffiliatedTaskId = taskAffiliation; mAffiliatedTaskColor = taskAffiliationColor; mPrevAffiliateTaskId = prevTaskId; @@ -406,7 +373,6 @@ class TaskRecord extends ConfigurationContainer { mCallingUid = callingUid; mCallingPackage = callingPackage; mResizeMode = resizeMode; - mSupportsPictureInPicture = supportsPictureInPicture; if (info != null) { setIntent(_intent, info); setMinDimensions(info); @@ -418,39 +384,6 @@ class TaskRecord extends ConfigurationContainer { mAtmService.getTaskChangeNotificationController().notifyTaskCreated(_taskId, realActivity); } - Task getTask() { - return mTask; - } - - void createTask(boolean onTop, boolean showForAllUsers) { - if (mTask != null) { - throw new IllegalArgumentException("mTask=" + mTask - + " already created for task=" + this); - } - - final Rect bounds = updateOverrideConfigurationFromLaunchBounds(); - final TaskStack stack = getStack().getTaskStack(); - - if (stack == null) { - throw new IllegalArgumentException("TaskRecord: invalid stack=" + mStack); - } - EventLog.writeEvent(WM_TASK_CREATED, mTaskId, stack.mStackId); - mTask = new Task(mTaskId, stack, mUserId, mAtmService.mWindowManager, mResizeMode, - mSupportsPictureInPicture, mTaskDescription, this); - final int position = onTop ? POSITION_TOP : POSITION_BOTTOM; - - if (!mDisplayedBounds.isEmpty()) { - mTask.setOverrideDisplayedBounds(mDisplayedBounds); - } - // We only want to move the parents to the parents if we are creating this task at the - // top of its stack. - stack.addTask(mTask, position, showForAllUsers, onTop /* moveParents */); - } - - void setTask(Task task) { - mTask = task; - } - void cleanUpResourcesForDestroy() { if (hasChild()) { return; @@ -473,60 +406,33 @@ class TaskRecord extends ConfigurationContainer { mAtmService.mStackSupervisor.mRecentTasks.remove(this); } - removeWindowContainer(); + removeIfPossible(); } @VisibleForTesting - void removeWindowContainer() { + @Override + void removeIfPossible() { mAtmService.getLockTaskController().clearLockedTask(this); - if (mTask == null) { - if (DEBUG_STACK) Slog.i(TAG_WM, "removeTask: could not find taskId=" + mTaskId); - return; - } - mTask.removeIfPossible(); - mTask = null; - if (!getWindowConfiguration().persistTaskBounds()) { - // Reset current bounds for task whose bounds shouldn't be persisted so it uses - // default configuration the next time it launches. - setBounds(null); - } + super.removeIfPossible(); mAtmService.getTaskChangeNotificationController().notifyTaskRemoved(mTaskId); } - void onSnapshotChanged(TaskSnapshot snapshot) { - mAtmService.getTaskChangeNotificationController().notifyTaskSnapshotChanged(mTaskId, snapshot); - } - void setResizeMode(int resizeMode) { if (mResizeMode == resizeMode) { return; } mResizeMode = resizeMode; - mTask.setResizeable(resizeMode); mAtmService.mRootActivityContainer.ensureActivitiesVisible(null, 0, !PRESERVE_WINDOWS); mAtmService.mRootActivityContainer.resumeFocusedStacksTopActivities(); } - void setTaskDockedResizing(boolean resizing) { - if (mTask == null) { - Slog.w(TAG_WM, "setTaskDockedResizing: taskId " + mTaskId + " not found."); - return; - } - mTask.setTaskDockedResizing(resizing); - } - - // TODO: Consolidate this with the resize() method below. - public void requestResize(Rect bounds, int resizeMode) { - mAtmService.resizeTask(mTaskId, bounds, resizeMode); - } - boolean resize(Rect bounds, int resizeMode, boolean preserveWindow, boolean deferResume) { mAtmService.deferWindowLayout(); try { final boolean forced = (resizeMode & RESIZE_MODE_FORCED) != 0; - if (mTask == null) { + if (getParent() == null) { // Task doesn't exist in window manager yet (e.g. was restored from recents). // All we can do for now is update the bounds so it can be used when the task is // added to window manager. @@ -577,7 +483,7 @@ class TaskRecord extends ConfigurationContainer { } } } - mTask.resize(kept, forced); + resize(kept, forced); saveLaunchingStateIfNeeded(); @@ -588,19 +494,6 @@ class TaskRecord extends ConfigurationContainer { } } - // TODO: Investigate combining with the resize() method above. - void resizeWindowContainer() { - mTask.resize(false /* relayout */, false /* forced */); - } - - void getWindowContainerBounds(Rect bounds) { - if (mTask != null) { - mTask.getBounds(bounds); - } else { - bounds.setEmpty(); - } - } - /** * Convenience method to reparent a task to the top or bottom position of the stack. */ @@ -708,32 +601,16 @@ class TaskRecord extends ConfigurationContainer { // Adjust the position for the new parent stack as needed. position = toStack.getAdjustedPositionForTask(this, position, null /* starting */); - // Must reparent first in window manager to avoid a situation where AM can delete the - // we are coming from in WM before we reparent because it became empty. - mTask.reparent(toStack.getTaskStack(), position, - moveStackMode == REPARENT_MOVE_STACK_TO_FRONT); - final boolean moveStackToFront = moveStackMode == REPARENT_MOVE_STACK_TO_FRONT || (moveStackMode == REPARENT_KEEP_STACK_AT_FRONT && (wasFocused || wasFront)); - // Move the task - sourceStack.removeTask(this, reason, moveStackToFront - ? REMOVE_TASK_MODE_MOVING_TO_TOP : REMOVE_TASK_MODE_MOVING); - toStack.addTask(this, position, false /* schedulePictureInPictureModeChange */, reason); + + reparent(toStack.getTaskStack(), position, moveStackToFront, reason); if (schedulePictureInPictureModeChange) { // Notify of picture-in-picture mode changes supervisor.scheduleUpdatePictureInPictureModeIfNeeded(this, sourceStack); } - // TODO: Ensure that this is actually necessary here - // Notify the voice session if required - if (voiceSession != null) { - try { - voiceSession.taskStarted(intent, mTaskId); - } catch (RemoteException e) { - } - } - // If the task had focus before (or we're requested to move focus), move focus to the // new stack by moving the stack to the front. if (r != null) { @@ -809,14 +686,6 @@ class TaskRecord extends ConfigurationContainer { || targetWindowingMode == WINDOWING_MODE_FREEFORM; } - void cancelWindowTransition() { - if (mTask == null) { - Slog.w(TAG_WM, "cancelWindowTransition: taskId " + mTaskId + " not found."); - return; - } - mTask.cancelTaskWindowTransition(); - } - /** * DO NOT HOLD THE ACTIVITY MANAGER LOCK WHEN CALLING THIS METHOD! */ @@ -970,65 +839,103 @@ class TaskRecord extends ConfigurationContainer { return (T) mStack; } - /** - * Must be used for setting parent stack because it performs configuration updates. - * Must be called after adding task as a child to the stack. - */ - // TODO(task-unify): Remove or rework after task level unification. - void setStack(ActivityStack stack) { - if (stack != null && !stack.isInStackLocked(this)) { - throw new IllegalStateException("Task must be added as a Stack child first."); - } - final ActivityStack oldStack = mStack; - mStack = stack; + // TODO(stack-unify): Can be removed on stack unified. + void onParentChanged(ActivityStack newParent, ActivityStack oldParent) { + onParentChanged( + newParent != null ? newParent.mTaskStack : null, + oldParent != null ? oldParent.mTaskStack : null); + } + + @Override + void onParentChanged(ConfigurationContainer newParent, ConfigurationContainer oldParent) { + final ActivityStack oldStack = (oldParent != null) + ? ((TaskStack) oldParent).mActivityStack : null; + final ActivityStack newStack = (newParent != null) + ? ((TaskStack) newParent).mActivityStack : null; + + mStack = newStack; - // If the new {@link TaskRecord} is from a different {@link ActivityStack}, remove this - // {@link ActivityRecord} from its current {@link ActivityStack}. + super.onParentChanged(newParent, oldParent); - if (oldStack != mStack) { + if (oldStack != null) { for (int i = getChildCount() - 1; i >= 0; --i) { final ActivityRecord activity = getChildAt(i); + oldStack.onActivityRemovedFromStack(activity); + } - if (oldStack != null) { - oldStack.onActivityRemovedFromStack(activity); - } + updateTaskMovement(true /*toFront*/); - if (mStack != null) { - stack.onActivityAddedToStack(activity); + if (oldStack.inPinnedWindowingMode() + && (newStack == null || !newStack.inPinnedWindowingMode())) { + // Notify if a task from the pinned stack is being removed + // (or moved depending on the mode). + mAtmService.getTaskChangeNotificationController().notifyActivityUnpinned(); + } + } + + if (newStack != null) { + for (int i = getChildCount() - 1; i >= 0; --i) { + final ActivityRecord activity = getChildAt(i); + newStack.onActivityAddedToStack(activity); + } + + // TODO: Ensure that this is actually necessary here + // Notify the voice session if required + if (voiceSession != null) { + try { + voiceSession.taskStarted(intent, mTaskId); + } catch (RemoteException e) { } } } - onParentChanged(mStack, oldStack); - } + // First time we are adding the task to the system. + if (oldParent == null && newParent != null) { - /** - * @return Id of current stack, {@link INVALID_STACK_ID} if no stack is set. - */ - int getStackId() { - return mStack != null ? mStack.mStackId : INVALID_STACK_ID; - } + // TODO: Super random place to be doing this, but aligns with what used to be done + // before we unified Task level. Look into if this can be done in a better place. + updateOverrideConfigurationFromLaunchBounds(); + } - @Override - protected int getChildCount() { - return mActivities.size(); - } + // Task is being removed. + if (oldParent != null && newParent == null) { + cleanUpResourcesForDestroy(); + } - @Override - protected ActivityRecord getChildAt(int index) { - return mActivities.get(index); + + // Update task bounds if needed. + adjustBoundsForDisplayChangeIfNeeded(getDisplayContent()); + + if (getWindowConfiguration().windowsAreScaleable()) { + // We force windows out of SCALING_MODE_FREEZE so that we can continue to animate them + // while a resize is pending. + forceWindowsScaleable(true /* force */); + } else { + forceWindowsScaleable(false /* force */); + } + + mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); } - @Override - protected ConfigurationContainer getParent() { - return mStack; + /** TODO(task-merge): Consolidate into {@link TaskStack#onChildPositionChanged}. */ + void updateTaskMovement(boolean toFront) { + if (isPersistable) { + mLastTimeMoved = System.currentTimeMillis(); + // Sign is used to keep tasks sorted when persisted. Tasks sent to the bottom most + // recently will be most negative, tasks sent to the bottom before that will be less + // negative. Similarly for recent tasks moved to the top which will be most positive. + if (!toFront) { + mLastTimeMoved *= -1; + } + } + mAtmService.mRootActivityContainer.invalidateTaskLayers(); } - @Override - protected void onParentChanged( - ConfigurationContainer newParent, ConfigurationContainer oldParent) { - super.onParentChanged(newParent, oldParent); - mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); + /** + * @return Id of current stack, {@link ActivityTaskManager#INVALID_STACK_ID} if no stack is set. + */ + int getStackId() { + return mStack != null ? mStack.mStackId : INVALID_STACK_ID; } // Close up recents linked list. @@ -1121,16 +1028,6 @@ class TaskRecord extends ConfigurationContainer { return null; } - boolean isVisible() { - for (int i = getChildCount() - 1; i >= 0; --i) { - final ActivityRecord r = getChildAt(i); - if (r.visible) { - return true; - } - } - return false; - } - /** * Return true if any activities in this task belongs to input uid. */ @@ -1210,15 +1107,10 @@ class TaskRecord extends ConfigurationContainer { * Reorder the history stack so that the passed activity is brought to the front. */ final void moveActivityToFrontLocked(ActivityRecord newTop) { - if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, - "Removing and adding activity " + newTop - + " to stack at top callers=" + Debug.getCallers(4)); - - mActivities.remove(newTop); - mActivities.add(newTop); + if (DEBUG_ADD_REMOVE) Slog.i(TAG_ADD_REMOVE, "Removing and adding activity " + + newTop + " to stack at top callers=" + Debug.getCallers(4)); - // Make sure window manager is aware of the position change. - mTask.positionChildAtTop(newTop); + positionChildAtTop(newTop); updateEffectiveIntent(); } @@ -1232,19 +1124,29 @@ class TaskRecord extends ConfigurationContainer { return getChildAt(0).getActivityType(); } - /** Called when a Task child is added from the Task.java side. */ - // TODO(task-unify): Just override addChild to do what is needed when someone calls to add a - // child. - void onChildAdded(ActivityRecord r, int index) { + @Override + void addChild(ActivityRecord r, int index) { + if (r.getParent() != null) { + // Shouldn't already have a parent since we are just adding to the task...Maybe you + // meant to use reparent? + throw new IllegalStateException( + "r=" + r + " parent=" + r.getParent() + " task=" + this); + } + + // If this task had any child before we added this one. + boolean hadChild = hasChild(); + + index = getAdjustedAddPosition(r, index); + super.addChild(r, index); + + ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addChild: %s at top.", this); r.inHistory = true; - // Remove r first, and if it wasn't already in the list and it's fullscreen, count it. - if (!mActivities.remove(r) && r.occludesParent()) { - // Was not previously in list. + if (r.occludesParent()) { numFullscreen++; } // Only set this based on the first activity - if (!hasChild()) { + if (!hadChild) { if (r.getActivityType() == ACTIVITY_TYPE_UNDEFINED) { // Normally non-standard activity type for the activity record will be set when the // object is created, however we delay setting the standard application type until @@ -1264,20 +1166,6 @@ class TaskRecord extends ConfigurationContainer { r.setActivityType(getActivityType()); } - final int size = getChildCount(); - - if (index == size && size > 0) { - final ActivityRecord top = getChildAt(size - 1); - if (top.mTaskOverlay) { - // Place below the task overlay activity since the overlay activity should always - // be on top. - index--; - } - } - - index = Math.min(size, index); - mActivities.add(index, r); - updateEffectiveIntent(); if (r.isPersistable()) { mAtmService.notifyTaskPersisterLocked(this, false); @@ -1288,31 +1176,23 @@ class TaskRecord extends ConfigurationContainer { mAtmService.mRootActivityContainer.updateUIDsPresentOnDisplay(); } - // TODO(task-unify): Merge onChildAdded method below into this since task will be a single - // object. void addChild(ActivityRecord r) { - if (r.getParent() != null) { - // Shouldn't already have a parent since we are just adding to the task... - throw new IllegalStateException( - "r=" + r + " parent=" + r.getParent() + " task=" + this); - } + addChild(r, Integer.MAX_VALUE /* add on top */); + } - ProtoLog.v(WM_DEBUG_ADD_REMOVE, "addChild: %s at top.", this); - // This means the activity isn't attached to Task.java yet. Go ahead and do that. - // TODO(task-unify): Remove/call super once we unify task level. - if (mTask != null) { - mTask.addChild(r, Integer.MAX_VALUE /* add on top */); - } else { - onChildAdded(r, Integer.MAX_VALUE); - } + @Override + void removeChild(ActivityRecord r) { + removeChild(r, "removeChild"); } - /** Called when a Task child is removed from the Task.java side. */ - // TODO(task-unify): Just override removeChild to do what is needed when someone calls to remove - // a child. - void onChildRemoved(ActivityRecord r) { - if (mActivities.remove(r) && r.occludesParent()) { - // Was previously in list. + void removeChild(ActivityRecord r, String reason) { + if (!mChildren.contains(r)) { + Slog.e(TAG, "removeChild: r=" + r + " not found in t=" + this); + return; + } + + super.removeChild(r); + if (r.occludesParent()) { numFullscreen--; } if (r.isPersistable()) { @@ -1336,16 +1216,19 @@ class TaskRecord extends ConfigurationContainer { // When destroying a task, tell the supervisor to remove it so that any activity it // has can be cleaned up correctly. This is currently the only place where we remove // a task with the DESTROYING mode, so instead of passing the onlyHasTaskOverlays - // state into removeTask(), we just clear the task here before the other residual + // state into removeChild(), we just clear the task here before the other residual // work. - // TODO: If the callers to removeTask() changes such that we have multiple places - // where we are destroying the task, move this back into removeTask() + // TODO: If the callers to removeChild() changes such that we have multiple places + // where we are destroying the task, move this back into removeChild() mAtmService.mStackSupervisor.removeTaskByIdLocked(mTaskId, false /* killProcess */, - !REMOVE_FROM_RECENTS, "onChildRemoved"); + !REMOVE_FROM_RECENTS, reason); } } else if (!mReuseTask) { // Remove entire task if it doesn't have any activity left and it isn't marked for reuse - mStack.removeTask(this, "onChildRemoved", REMOVE_TASK_MODE_DESTROYING); + mStack.removeChild(this, reason); + EventLog.writeEvent(WM_TASK_REMOVED, mTaskId, + "removeChild: last r=" + r + " in t=" + this); + removeIfPossible(); } } @@ -1380,7 +1263,7 @@ class TaskRecord extends ConfigurationContainer { * Completely remove all activities associated with an existing * task starting at a specified index. */ - final void performClearTaskAtIndexLocked(int activityNdx, String reason) { + private void performClearTaskAtIndexLocked(int activityNdx, String reason) { int numActivities = getChildCount(); for ( ; activityNdx < numActivities; ++activityNdx) { final ActivityRecord r = getChildAt(activityNdx); @@ -1390,7 +1273,7 @@ class TaskRecord extends ConfigurationContainer { if (mStack == null) { // Task was restored from persistent storage. r.takeFromHistory(); - mActivities.remove(activityNdx); + removeChild(r); --activityNdx; --numActivities; } else if (r.finishIfPossible(Activity.RESULT_CANCELED, null /* resultData */, reason, @@ -1526,20 +1409,13 @@ class TaskRecord extends ConfigurationContainer { " mLockTaskAuth=" + lockTaskAuthToString()); } - private boolean isResizeable(boolean checkSupportsPip) { - return (mAtmService.mForceResizableActivities || ActivityInfo.isResizeableMode(mResizeMode) - || (checkSupportsPip && mSupportsPictureInPicture)); - } - - boolean isResizeable() { - return isResizeable(true /* checkSupportsPip */); - } - @Override public boolean supportsSplitScreenWindowingMode() { // A task can not be docked even if it is considered resizeable because it only supports // picture-in-picture mode but has a non-resizeable resizeMode return super.supportsSplitScreenWindowingMode() + // TODO(task-group): Probably makes sense to move this and associated code into + // WindowContainer so it affects every node. && mAtmService.mSupportsSplitScreenMultiWindow && (mAtmService.mForceResizableActivities || (isResizeable(false /* checkSupportsPip */) @@ -1672,15 +1548,13 @@ class TaskRecord extends ConfigurationContainer { } topActivity = false; } - mTaskDescription = new TaskDescription(label, null, iconResource, iconFilename, - colorPrimary, colorBackground, statusBarColor, navigationBarColor, + final TaskDescription taskDescription = new TaskDescription(label, null, iconResource, + iconFilename, colorPrimary, colorBackground, statusBarColor, navigationBarColor, statusBarContrastWhenTransparent, navigationBarContrastWhenTransparent); - if (mTask != null) { - mTask.setTaskDescription(mTaskDescription); - } + setTaskDescription(taskDescription); // Update the task affiliation color if we are the parent of the group if (mTaskId == mAffiliatedTaskId) { - mAffiliatedTaskColor = mTaskDescription.getPrimaryColor(); + mAffiliatedTaskColor = taskDescription.getPrimaryColor(); } } } @@ -1903,38 +1777,6 @@ class TaskRecord extends ConfigurationContainer { } /** - * Displayed bounds are used to set where the task is drawn at any given time. This is - * separate from its actual bounds so that the app doesn't see any meaningful configuration - * changes during transitionary periods. - */ - void setDisplayedBounds(Rect bounds) { - if (bounds == null) { - mDisplayedBounds.setEmpty(); - } else { - mDisplayedBounds.set(bounds); - } - if (mTask != null) { - mTask.setOverrideDisplayedBounds( - mDisplayedBounds.isEmpty() ? null : mDisplayedBounds); - } - } - - /** - * Gets the current overridden displayed bounds. These will be empty if the task is not - * currently overriding where it is displayed. - */ - Rect getDisplayedBounds() { - return mDisplayedBounds; - } - - /** - * @return {@code true} if this has overridden displayed bounds. - */ - boolean hasDisplayedBounds() { - return !mDisplayedBounds.isEmpty(); - } - - /** * Intersects inOutBounds with intersectBounds-intersectInsets. If inOutBounds is larger than * intersectBounds on a side, then the respective side will not be intersected. * @@ -2190,16 +2032,10 @@ class TaskRecord extends ConfigurationContainer { computeConfigResourceOverrides(getResolvedOverrideConfiguration(), newParentConfig); } - /** @see WindowContainer#handlesOrientationChangeFromDescendant */ - boolean handlesOrientationChangeFromDescendant() { - return mTask != null && mTask.getParent() != null - && mTask.getParent().handlesOrientationChangeFromDescendant(); - } - /** - * Compute bounds (letterbox or pillarbox) for {@link #WINDOWING_MODE_FULLSCREEN} when the - * parent doesn't handle the orientation change and the requested orientation is different from - * the parent. + * Compute bounds (letterbox or pillarbox) for + * {@link WindowConfiguration#WINDOWING_MODE_FULLSCREEN} when the parent doesn't handle the + * orientation change and the requested orientation is different from the parent. */ void computeFullscreenBounds(@NonNull Rect outBounds, @Nullable ActivityRecord refActivity, @NonNull Rect parentBounds, int parentOrientation) { @@ -2345,7 +2181,7 @@ class TaskRecord extends ConfigurationContainer { info.realActivity = realActivity; info.numActivities = mReuseActivitiesReport.numActivities; info.lastActiveTime = lastActiveTime; - info.taskDescription = new ActivityManager.TaskDescription(mTaskDescription); + info.taskDescription = new ActivityManager.TaskDescription(getTaskDescription()); info.supportsSplitScreenMultiWindow = supportsSplitScreenWindowingMode(); info.resizeMode = mResizeMode; info.configuration.setTo(getConfiguration()); @@ -2435,7 +2271,7 @@ class TaskRecord extends ConfigurationContainer { } pw.println(")"); } - pw.print(prefix); pw.print("Activities="); pw.println(mActivities); + pw.print(prefix); pw.print("Activities="); pw.println(mChildren); if (!askedCompatMode || !inRecents || !isAvailable) { pw.print(prefix); pw.print("askedCompatMode="); pw.print(askedCompatMode); pw.print(" inRecents="); pw.print(inRecents); @@ -2490,6 +2326,7 @@ class TaskRecord extends ConfigurationContainer { return toString(); } + @Override public void writeToProto(ProtoOutputStream proto, long fieldId, @WindowTraceLogLevel int logLevel) { if (logLevel == WindowTraceLogLevel.CRITICAL && !isVisible()) { @@ -2497,13 +2334,13 @@ class TaskRecord extends ConfigurationContainer { } final long token = proto.start(fieldId); - super.writeToProto(proto, CONFIGURATION_CONTAINER, logLevel); + writeToProtoInnerTaskOnly(proto, TASK, logLevel); proto.write(ID, mTaskId); for (int i = getChildCount() - 1; i >= 0; i--) { - ActivityRecord activity = getChildAt(i); + final ActivityRecord activity = getChildAt(i); activity.writeToProto(proto, ACTIVITIES); } - proto.write(STACK_ID, mStack.mStackId); + proto.write(STACK_ID, getStackId()); if (mLastNonFullscreenBounds != null) { mLastNonFullscreenBounds.writeToProto(proto, LAST_NON_FULLSCREEN_BOUNDS); } @@ -2579,8 +2416,8 @@ class TaskRecord extends ConfigurationContainer { if (lastDescription != null) { out.attribute(null, ATTR_LASTDESCRIPTION, lastDescription.toString()); } - if (mTaskDescription != null) { - mTaskDescription.saveToXml(out); + if (getTaskDescription() != null) { + getTaskDescription().saveToXml(out); } out.attribute(null, ATTR_TASK_AFFILIATION_COLOR, String.valueOf(mAffiliatedTaskColor)); out.attribute(null, ATTR_TASK_AFFILIATION, String.valueOf(mAffiliatedTaskId)); @@ -2641,14 +2478,14 @@ class TaskRecord extends ConfigurationContainer { static TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, Intent intent, IVoiceInteractionSession voiceSession, - IVoiceInteractor voiceInteractor) { + IVoiceInteractor voiceInteractor, ActivityStack stack) { return getTaskRecordFactory().create( - service, taskId, info, intent, voiceSession, voiceInteractor); + service, taskId, info, intent, voiceSession, voiceInteractor, stack); } static TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, TaskDescription taskDescription) { - return getTaskRecordFactory().create(service, taskId, info, intent, taskDescription); + Intent intent, TaskDescription taskDescription, ActivityStack stack) { + return getTaskRecordFactory().create(service, taskId, info, intent, taskDescription, stack); } static TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) @@ -2665,15 +2502,15 @@ class TaskRecord extends ConfigurationContainer { TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, Intent intent, IVoiceInteractionSession voiceSession, - IVoiceInteractor voiceInteractor) { + IVoiceInteractor voiceInteractor, ActivityStack stack) { return new TaskRecord(service, taskId, info, intent, voiceSession, voiceInteractor, - null /*taskDescription*/); + null /*taskDescription*/, stack); } TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, TaskDescription taskDescription) { + Intent intent, TaskDescription taskDescription, ActivityStack stack) { return new TaskRecord(service, taskId, info, intent, null /*voiceSession*/, - null /*voiceInteractor*/, taskDescription); + null /*voiceInteractor*/, taskDescription, stack); } /** @@ -2683,20 +2520,20 @@ class TaskRecord extends ConfigurationContainer { Intent affinityIntent, String affinity, String rootAffinity, ComponentName realActivity, ComponentName origActivity, boolean rootWasReset, boolean autoRemoveRecents, boolean askedCompatMode, int userId, - int effectiveUid, String lastDescription, ArrayList<ActivityRecord> activities, + int effectiveUid, String lastDescription, long lastTimeMoved, boolean neverRelinquishIdentity, TaskDescription lastTaskDescription, int taskAffiliation, int prevTaskId, int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, int resizeMode, boolean supportsPictureInPicture, boolean realActivitySuspended, - boolean userSetupComplete, int minWidth, int minHeight) { + boolean userSetupComplete, int minWidth, int minHeight, ActivityStack stack) { return new TaskRecord(service, taskId, intent, affinityIntent, affinity, rootAffinity, realActivity, origActivity, rootWasReset, autoRemoveRecents, - askedCompatMode, userId, effectiveUid, lastDescription, activities, + askedCompatMode, userId, effectiveUid, lastDescription, lastTimeMoved, neverRelinquishIdentity, lastTaskDescription, taskAffiliation, prevTaskId, nextTaskId, taskAffiliationColor, callingUid, callingPackage, resizeMode, supportsPictureInPicture, realActivitySuspended, userSetupComplete, minWidth, minHeight, null /*ActivityInfo*/, null /*_voiceSession*/, - null /*_voiceInteractor*/); + null /*_voiceInteractor*/, stack); } TaskRecord restoreFromXml(XmlPullParser in, ActivityStackSupervisor stackSupervisor) @@ -2908,15 +2745,15 @@ class TaskRecord extends ConfigurationContainer { taskId, intent, affinityIntent, affinity, rootAffinity, realActivity, origActivity, rootHasReset, autoRemoveRecents, askedCompatMode, userId, effectiveUid, lastDescription, - activities, lastTimeOnTop, neverRelinquishIdentity, taskDescription, + lastTimeOnTop, neverRelinquishIdentity, taskDescription, taskAffiliation, prevTaskId, nextTaskId, taskAffiliationColor, callingUid, callingPackage, resizeMode, supportsPictureInPicture, realActivitySuspended, - userSetupComplete, minWidth, minHeight); + userSetupComplete, minWidth, minHeight, null /*stack*/); task.mLastNonFullscreenBounds = lastNonFullscreenBounds; task.setBounds(lastNonFullscreenBounds); for (int activityNdx = activities.size() - 1; activityNdx >=0; --activityNdx) { - activities.get(activityNdx).setTask(task); + task.addChild(activities.get(activityNdx)); } if (DEBUG_RECENTS) Slog.d(TAG_RECENTS, "Restored task=" + task); diff --git a/services/core/java/com/android/server/wm/TaskStack.java b/services/core/java/com/android/server/wm/TaskStack.java index 56211e25f421..68b76fb14174 100644 --- a/services/core/java/com/android/server/wm/TaskStack.java +++ b/services/core/java/com/android/server/wm/TaskStack.java @@ -116,7 +116,6 @@ public class TaskStack extends WindowContainer<Task> implements /** ActivityRecords that are exiting, but still on screen for animations. */ final ArrayList<ActivityRecord> mExitingActivities = new ArrayList<>(); - final ArrayList<ActivityRecord> mTmpActivities = new ArrayList<>(); /** Detach this stack from its display when animation completes. */ // TODO: maybe tie this to WindowContainer#removeChild some how... @@ -330,7 +329,7 @@ public class TaskStack extends WindowContainer<Task> implements } /** Bounds of the stack with other system factors taken into consideration. */ - public void getDimBounds(Rect out) { + void getDimBounds(Rect out) { getBounds(out); } @@ -482,11 +481,6 @@ public class TaskStack extends WindowContainer<Task> implements dividerSize); } - // TODO: Checkout the call points of this method and the ones below to see how they can fit in WC. - void addTask(Task task, int position) { - addTask(task, position, task.showForAllUsers(), true /* moveParents */); - } - /** * Put a Task in this stack. Used for adding only. * When task is added to top of the stack, the entire branch of the hierarchy (including stack @@ -495,22 +489,21 @@ public class TaskStack extends WindowContainer<Task> implements * @param position Target position to add the task to. * @param showForAllUsers Whether to show the task regardless of the current user. */ - void addTask(Task task, int position, boolean showForAllUsers, boolean moveParents) { - final TaskStack currentStack = task.mStack; - // TODO: We pass stack to task's constructor, but we still need to call this method. - // This doesn't make sense, mStack will already be set equal to "this" at this point. - if (currentStack != null && currentStack.mStackId != mStackId) { - throw new IllegalStateException("Trying to add taskId=" + task.mTaskId - + " to stackId=" + mStackId - + ", but it is already attached to stackId=" + task.mStack.mStackId); - } - + void addChild(Task task, int position, boolean showForAllUsers, boolean moveParents) { // Add child task. task.mStack = this; addChild(task, null); // Move child to a proper position, as some restriction for position might apply. - positionChildAt(position, task, moveParents /* includingParents */, showForAllUsers); + position = positionChildAt( + position, task, moveParents /* includingParents */, showForAllUsers); + // TODO(task-merge): Remove cast. + mActivityStack.onChildAdded((TaskRecord) task, position); + } + + @Override + void addChild(Task task, int position) { + addChild(task, position, task.showForAllUsers(), false /* includingParents */); } void positionChildAt(Task child, int position) { @@ -563,13 +556,12 @@ public class TaskStack extends WindowContainer<Task> implements /** * Overridden version of {@link TaskStack#positionChildAt(int, Task, boolean)}. Used in - * {@link TaskStack#addTask(Task, int, boolean showForAllUsers, boolean)}, as it can receive - * showForAllUsers param from {@link AppWindowToken} instead of {@link Task#showForAllUsers()}. + * {@link TaskStack#addChild(Task, int, boolean showForAllUsers, boolean)}, as it can receive + * showForAllUsers param from {@link ActivityRecord} instead of {@link Task#showForAllUsers()}. */ - private void positionChildAt(int position, Task child, boolean includingParents, + int positionChildAt(int position, Task child, boolean includingParents, boolean showForAllUsers) { - final int targetPosition = findPositionForTask(child, position, showForAllUsers, - false /* addingNew */); + final int targetPosition = findPositionForTask(child, position, showForAllUsers); super.positionChildAt(targetPosition, child, includingParents); // Log positioning. @@ -578,6 +570,14 @@ public class TaskStack extends WindowContainer<Task> implements final int toTop = targetPosition == mChildren.size() - 1 ? 1 : 0; EventLog.writeEvent(EventLogTags.WM_TASK_MOVED, child.mTaskId, toTop, targetPosition); + + return targetPosition; + } + + @Override + void onChildPositionChanged(WindowContainer child) { + // TODO(task-merge): Read comment on updateTaskMovement method. + //((TaskRecord) child).updateTaskMovement(true); } void reparent(int displayId, Rect outStackBounds, boolean onTop) { @@ -597,14 +597,13 @@ public class TaskStack extends WindowContainer<Task> implements // TODO: We should really have users as a window container in the hierarchy so that we don't // have to do complicated things like we are doing in this method. - private int findPositionForTask(Task task, int targetPosition, boolean showForAllUsers, - boolean addingNew) { + private int findPositionForTask(Task task, int targetPosition, boolean showForAllUsers) { final boolean canShowTask = showForAllUsers || mWmService.isCurrentProfileLocked(task.mUserId); final int stackSize = mChildren.size(); int minPosition = 0; - int maxPosition = addingNew ? stackSize : stackSize - 1; + int maxPosition = stackSize - 1; if (canShowTask) { minPosition = computeMinPosition(minPosition, stackSize); @@ -615,8 +614,7 @@ public class TaskStack extends WindowContainer<Task> implements // preserve POSITION_BOTTOM/POSITION_TOP positions if they are still valid. if (targetPosition == POSITION_BOTTOM && minPosition == 0) { return POSITION_BOTTOM; - } else if (targetPosition == POSITION_TOP - && maxPosition == (addingNew ? stackSize : stackSize - 1)) { + } else if (targetPosition == POSITION_TOP && maxPosition == (stackSize - 1)) { return POSITION_TOP; } // Reset position based on minimum/maximum possible positions. @@ -669,24 +667,17 @@ public class TaskStack extends WindowContainer<Task> implements */ @Override void removeChild(Task task) { + if (!mChildren.contains(task)) { + // Not really in this stack anymore... + return; + } if (DEBUG_TASK_MOVEMENT) Slog.d(TAG_WM, "removeChild: task=" + task); super.removeChild(task); task.mStack = null; - if (mDisplayContent != null) { - if (mChildren.isEmpty()) { - getParent().positionChildAt(POSITION_BOTTOM, this, false /* includingParents */); - } - mDisplayContent.setLayoutNeeded(); - } - for (int appNdx = mExitingActivities.size() - 1; appNdx >= 0; --appNdx) { - final ActivityRecord activity = mExitingActivities.get(appNdx); - if (activity.getTask() == task) { - activity.mIsExiting = false; - mExitingActivities.remove(appNdx); - } - } + // TODO(task-merge): Remove cast. + mActivityStack.onChildRemoved((TaskRecord) task, mDisplayContent); } @Override @@ -1298,7 +1289,7 @@ public class TaskStack extends WindowContainer<Task> implements super.writeToProto(proto, WINDOW_CONTAINER, logLevel); proto.write(ID, mStackId); for (int taskNdx = mChildren.size() - 1; taskNdx >= 0; taskNdx--) { - mChildren.get(taskNdx).writeToProto(proto, TASKS, logLevel); + mChildren.get(taskNdx).writeToProtoInnerTaskOnly(proto, TASKS, logLevel); } proto.write(FILLS_PARENT, matchParentBounds()); getRawBounds().writeToProto(proto, BOUNDS); diff --git a/services/core/java/com/android/server/wm/WindowContainer.java b/services/core/java/com/android/server/wm/WindowContainer.java index 7ce2b5eb727b..a393ba65fbc9 100644 --- a/services/core/java/com/android/server/wm/WindowContainer.java +++ b/services/core/java/com/android/server/wm/WindowContainer.java @@ -428,7 +428,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< parent.mTreeWeight += child.mTreeWeight; parent = parent.getParent(); } - onChildPositionChanged(); + onChildPositionChanged(child); } /** @@ -454,7 +454,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< parent.mTreeWeight -= child.mTreeWeight; parent = parent.getParent(); } - onChildPositionChanged(); + onChildPositionChanged(child); } /** @@ -583,7 +583,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< if (mChildren.peekLast() != child) { mChildren.remove(child); mChildren.add(child); - onChildPositionChanged(); + onChildPositionChanged(child); } if (includingParents && getParent() != null) { getParent().positionChildAt(POSITION_TOP, this /* child */, @@ -594,7 +594,7 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< if (mChildren.peekFirst() != child) { mChildren.remove(child); mChildren.addFirst(child); - onChildPositionChanged(); + onChildPositionChanged(child); } if (includingParents && getParent() != null) { getParent().positionChildAt(POSITION_BOTTOM, this /* child */, @@ -608,14 +608,14 @@ class WindowContainer<E extends WindowContainer> extends ConfigurationContainer< // doing this adjustment here and remove any adjustments in the callers. mChildren.remove(child); mChildren.add(position, child); - onChildPositionChanged(); + onChildPositionChanged(child); } } /** * Notify that a child's position has changed. Possible changes are adding or removing a child. */ - void onChildPositionChanged() { } + void onChildPositionChanged(WindowContainer child) { } /** * Update override configuration and recalculate full config. diff --git a/services/java/com/android/server/SystemServer.java b/services/java/com/android/server/SystemServer.java index 2009dbdca448..ef9e69df01df 100644 --- a/services/java/com/android/server/SystemServer.java +++ b/services/java/com/android/server/SystemServer.java @@ -439,7 +439,7 @@ public final class SystemServer { // In case the runtime switched since last boot (such as when // the old runtime was removed in an OTA), set the system - // property so that it is in sync. We can | xq oqi't do this in + // property so that it is in sync. We can't do this in // libnativehelper's JniInvocation::Init code where we already // had to fallback to a different runtime because it is // running as root and we need to be the system user to set diff --git a/services/tests/mockingservicestests/src/com/android/server/AlarmManagerServiceTest.java b/services/tests/mockingservicestests/src/com/android/server/AlarmManagerServiceTest.java index 485f436f7f65..556f96ace5d2 100644 --- a/services/tests/mockingservicestests/src/com/android/server/AlarmManagerServiceTest.java +++ b/services/tests/mockingservicestests/src/com/android/server/AlarmManagerServiceTest.java @@ -24,6 +24,7 @@ import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_FREQUENT; import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_RARE; import static android.app.usage.UsageStatsManager.STANDBY_BUCKET_WORKING_SET; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doCallRealMethod; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doNothing; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.doThrow; @@ -35,6 +36,7 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.when; import static com.android.server.AlarmManagerService.ACTIVE_INDEX; import static com.android.server.AlarmManagerService.AlarmHandler.APP_STANDBY_BUCKET_CHANGED; import static com.android.server.AlarmManagerService.AlarmHandler.CHARGING_STATUS_CHANGED; +import static com.android.server.AlarmManagerService.AlarmHandler.REMOVE_FOR_CANCELED; import static com.android.server.AlarmManagerService.Constants.KEY_ALLOW_WHILE_IDLE_LONG_TIME; import static com.android.server.AlarmManagerService.Constants.KEY_ALLOW_WHILE_IDLE_SHORT_TIME; import static com.android.server.AlarmManagerService.Constants.KEY_ALLOW_WHILE_IDLE_WHITELIST_DURATION; @@ -80,9 +82,9 @@ import android.provider.Settings; import android.util.Log; import android.util.SparseArray; -import androidx.test.filters.FlakyTest; import androidx.test.runner.AndroidJUnit4; +import com.android.dx.mockito.inline.extended.MockedVoidMethod; import com.android.internal.annotations.GuardedBy; import com.android.server.usage.AppStandbyInternal; @@ -171,7 +173,6 @@ public class AlarmManagerServiceTest { } public class Injector extends AlarmManagerService.Injector { - boolean mIsAutomotiveOverride; Injector(Context context) { super(context); @@ -257,12 +258,13 @@ public class AlarmManagerServiceTest { .startMocking(); doReturn(mIActivityManager).when(ActivityManager::getService); doReturn(mAppStateTracker).when(() -> LocalServices.getService(AppStateTracker.class)); - doReturn(null) - .when(() -> LocalServices.getService(DeviceIdleInternal.class)); doReturn(mAppStandbyInternal).when( () -> LocalServices.getService(AppStandbyInternal.class)); doReturn(mUsageStatsManagerInternal).when( () -> LocalServices.getService(UsageStatsManagerInternal.class)); + doCallRealMethod().when((MockedVoidMethod) () -> + LocalServices.addService(eq(AlarmManagerInternal.class), any())); + doCallRealMethod().when(() -> LocalServices.getService(AlarmManagerInternal.class)); when(mUsageStatsManagerInternal.getAppStandbyBucket(eq(TEST_CALLING_PACKAGE), eq(UserHandle.getUserId(TEST_CALLING_UID)), anyLong())) .thenReturn(STANDBY_BUCKET_ACTIVE); @@ -455,7 +457,6 @@ public class AlarmManagerServiceTest { assertEquals(expectedTriggerTime, mTestTimer.getElapsed()); } - @FlakyTest(bugId = 130313408) @Test public void testEarliestAlarmSet() { final PendingIntent pi6 = getNewMockPendingIntent(); @@ -600,11 +601,15 @@ public class AlarmManagerServiceTest { anyLong())).thenReturn(bucket); mAppStandbyListener.onAppIdleStateChanged(TEST_CALLING_PACKAGE, UserHandle.getUserId(TEST_CALLING_UID), false, bucket, 0); + assertAndHandleMessageSync(APP_STANDBY_BUCKET_CHANGED); + } + + private void assertAndHandleMessageSync(int what) { final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); verify(mService.mHandler, atLeastOnce()).sendMessage(messageCaptor.capture()); final Message lastMessage = messageCaptor.getValue(); assertEquals("Unexpected message send to handler", lastMessage.what, - APP_STANDBY_BUCKET_CHANGED); + what); mService.mHandler.handleMessage(lastMessage); } @@ -664,12 +669,7 @@ public class AlarmManagerServiceTest { mChargingReceiver.onReceive(mMockContext, new Intent(parole ? BatteryManager.ACTION_CHARGING : BatteryManager.ACTION_DISCHARGING)); - final ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class); - verify(mService.mHandler, atLeastOnce()).sendMessage(messageCaptor.capture()); - final Message lastMessage = messageCaptor.getValue(); - assertEquals("Unexpected message send to handler", lastMessage.what, - CHARGING_STATUS_CHANGED); - mService.mHandler.handleMessage(lastMessage); + assertAndHandleMessageSync(CHARGING_STATUS_CHANGED); } @Test @@ -971,12 +971,13 @@ public class AlarmManagerServiceTest { } @Test - public void alarmCountOnPendingIntentCancel() { + public void alarmCountOnRemoveForCanceled() { + final AlarmManagerInternal ami = LocalServices.getService(AlarmManagerInternal.class); final PendingIntent pi = getNewMockPendingIntent(); - setTestAlarm(ELAPSED_REALTIME_WAKEUP, mNowElapsedTest + 123, pi); - verify(pi).registerCancelListener(mService.mOperationCancelListener); + setTestAlarm(ELAPSED_REALTIME, mNowElapsedTest + 12345, pi); assertEquals(1, mService.mAlarmsPerUid.get(TEST_CALLING_UID)); - mService.mOperationCancelListener.onCancelled(pi); + ami.remove(pi); + assertAndHandleMessageSync(REMOVE_FOR_CANCELED); assertEquals(0, mService.mAlarmsPerUid.get(TEST_CALLING_UID)); } @@ -985,5 +986,6 @@ public class AlarmManagerServiceTest { if (mMockingSession != null) { mMockingSession.finishMocking(); } + LocalServices.removeServiceForTest(AlarmManagerInternal.class); } } diff --git a/services/tests/mockingservicestests/src/com/android/server/am/PendingIntentControllerTest.java b/services/tests/mockingservicestests/src/com/android/server/am/PendingIntentControllerTest.java new file mode 100644 index 000000000000..3975f0baa22a --- /dev/null +++ b/services/tests/mockingservicestests/src/com/android/server/am/PendingIntentControllerTest.java @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2019 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.am; + +import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession; +import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.when; + +import android.app.ActivityManager; +import android.app.ActivityManagerInternal; +import android.app.AppGlobals; +import android.app.PendingIntent; +import android.content.Intent; +import android.content.pm.IPackageManager; +import android.os.Looper; + +import androidx.test.runner.AndroidJUnit4; + +import com.android.server.AlarmManagerInternal; +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.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.MockitoSession; +import org.mockito.quality.Strictness; + +@RunWith(AndroidJUnit4.class) +public class PendingIntentControllerTest { + private static final String TEST_PACKAGE_NAME = "test-package-1"; + private static final int TEST_CALLING_UID = android.os.Process.myUid(); + private static final Intent[] TEST_INTENTS = new Intent[]{new Intent("com.test.intent")}; + + @Mock + private UserController mUserController; + @Mock + private AlarmManagerInternal mAlarmManagerInternal; + @Mock + private ActivityManagerInternal mActivityManagerInternal; + @Mock + private IPackageManager mIPackageManager; + + private MockitoSession mMockingSession; + private PendingIntentController mPendingIntentController; + + @Before + public void setUp() throws Exception { + mMockingSession = mockitoSession() + .initMocks(this) + .mockStatic(LocalServices.class) + .mockStatic(AppGlobals.class) + .strictness(Strictness.LENIENT) // Needed to stub LocalServices.getService twice + .startMocking(); + doReturn(mAlarmManagerInternal).when( + () -> LocalServices.getService(AlarmManagerInternal.class)); + doReturn(mActivityManagerInternal).when( + () -> LocalServices.getService(ActivityManagerInternal.class)); + doReturn(mIPackageManager).when(() -> AppGlobals.getPackageManager()); + when(mIPackageManager.getPackageUid(eq(TEST_PACKAGE_NAME), anyInt(), anyInt())).thenReturn( + TEST_CALLING_UID); + mPendingIntentController = new PendingIntentController(Looper.getMainLooper(), + mUserController); + mPendingIntentController.onActivityManagerInternalAdded(); + } + + private PendingIntentRecord createPendingIntentRecord(int flags) { + return mPendingIntentController.getIntentSender(ActivityManager.INTENT_SENDER_BROADCAST, + TEST_PACKAGE_NAME, TEST_CALLING_UID, 0, null, null, 0, TEST_INTENTS, null, flags, + null); + } + + @Test + public void alarmsRemovedOnCancel() { + final PendingIntentRecord pir = createPendingIntentRecord(0); + mPendingIntentController.cancelIntentSender(pir); + final ArgumentCaptor<PendingIntent> piCaptor = ArgumentCaptor.forClass(PendingIntent.class); + verify(mAlarmManagerInternal).remove(piCaptor.capture()); + assertEquals("Wrong target for pending intent passed to alarm manager", pir, + piCaptor.getValue().getTarget()); + } + + @Test + public void alarmsRemovedOnRecreateWithCancelCurrent() { + final PendingIntentRecord pir = createPendingIntentRecord(0); + createPendingIntentRecord(PendingIntent.FLAG_CANCEL_CURRENT); + final ArgumentCaptor<PendingIntent> piCaptor = ArgumentCaptor.forClass(PendingIntent.class); + verify(mAlarmManagerInternal).remove(piCaptor.capture()); + assertEquals("Wrong target for pending intent passed to alarm manager", pir, + piCaptor.getValue().getTarget()); + } + + @Test + public void alarmsRemovedOnSendingOneShot() { + final PendingIntentRecord pir = createPendingIntentRecord(PendingIntent.FLAG_ONE_SHOT); + pir.send(0, null, null, null, null, null, null); + final ArgumentCaptor<PendingIntent> piCaptor = ArgumentCaptor.forClass(PendingIntent.class); + verify(mAlarmManagerInternal).remove(piCaptor.capture()); + assertEquals("Wrong target for pending intent passed to alarm manager", pir, + piCaptor.getValue().getTarget()); + } + + @After + public void tearDown() { + if (mMockingSession != null) { + mMockingSession.finishMocking(); + } + } +} diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java index 38d6c9c1e4db..2ce37f1be4c5 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityRecordTests.java @@ -53,8 +53,6 @@ import static com.android.server.wm.ActivityStack.ActivityState.RESUMED; import static com.android.server.wm.ActivityStack.ActivityState.STARTED; import static com.android.server.wm.ActivityStack.ActivityState.STOPPED; import static com.android.server.wm.ActivityStack.ActivityState.STOPPING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_MOVING; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_INVISIBLE; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT; @@ -136,13 +134,13 @@ public class ActivityRecordTests extends ActivityTestsBase { @Test public void testStackCleanupOnActivityRemoval() { - mTask.mTask.removeChild(mActivity); + mTask.removeChild(mActivity); verify(mStack, times(1)).onActivityRemovedFromStack(any()); } @Test public void testStackCleanupOnTaskRemoval() { - mStack.removeTask(mTask, null /*reason*/, REMOVE_TASK_MODE_MOVING); + mStack.removeChild(mTask, null /*reason*/); // Stack should be gone on task removal. assertNull(mService.mRootActivityContainer.getStack(mStack.mStackId)); } @@ -325,7 +323,7 @@ public class ActivityRecordTests extends ActivityTestsBase { : ORIENTATION_PORTRAIT; mTask.onRequestedOverrideConfigurationChanged(newConfig); - doReturn(true).when(mTask.mTask).isDragResizing(); + doReturn(true).when(mTask).isDragResizing(); mActivity.mRelaunchReason = ActivityTaskManagerService.RELAUNCH_REASON_NONE; @@ -382,7 +380,7 @@ public class ActivityRecordTests extends ActivityTestsBase { } // Mimic the behavior that display doesn't handle app's requested orientation. - final DisplayContent dc = mTask.mTask.getDisplayContent(); + final DisplayContent dc = mTask.getDisplayContent(); doReturn(false).when(dc).onDescendantOrientationChanged(any(), any()); doReturn(false).when(dc).handlesOrientationChangeFromDescendant(); @@ -1174,7 +1172,7 @@ public class ActivityRecordTests extends ActivityTestsBase { // Empty the home stack. final ActivityStack homeStack = mActivity.getDisplay().getHomeStack(); for (TaskRecord t : homeStack.getAllTasks()) { - homeStack.removeTask(t, "test", REMOVE_TASK_MODE_DESTROYING); + homeStack.removeChild(t, "test"); } mActivity.finishing = true; doReturn(false).when(mRootActivityContainer).resumeFocusedStacksTopActivities(); @@ -1200,7 +1198,7 @@ public class ActivityRecordTests extends ActivityTestsBase { // Empty the home stack. final ActivityStack homeStack = mActivity.getDisplay().getHomeStack(); for (TaskRecord t : homeStack.getAllTasks()) { - homeStack.removeTask(t, "test", REMOVE_TASK_MODE_DESTROYING); + homeStack.removeChild(t, "test"); } mActivity.finishing = true; spyOn(mStack); diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java index fcebb81fd658..cc0cc3f85d50 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStackTests.java @@ -38,7 +38,6 @@ import static com.android.server.wm.ActivityStack.ActivityState.PAUSING; import static com.android.server.wm.ActivityStack.ActivityState.RESUMED; import static com.android.server.wm.ActivityStack.ActivityState.STOPPED; import static com.android.server.wm.ActivityStack.ActivityState.STOPPING; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_INVISIBLE; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE; import static com.android.server.wm.ActivityStack.STACK_VISIBILITY_VISIBLE_BEHIND_TRANSLUCENT; @@ -93,21 +92,6 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testEmptyTaskCleanupOnRemove() { - assertNotNull(mTask.getTask()); - mStack.removeTask(mTask, "testEmptyTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING); - assertNull(mTask.getTask()); - } - - @Test - public void testOccupiedTaskCleanupOnRemove() { - final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); - assertNotNull(mTask.getTask()); - mStack.removeTask(mTask, "testOccupiedTaskCleanupOnRemove", REMOVE_TASK_MODE_DESTROYING); - assertNotNull(mTask.getTask()); - } - - @Test public void testResumedActivity() { final ActivityRecord r = new ActivityBuilder(mService).setTask(mTask).build(); assertNull(mStack.getResumedActivity()); @@ -996,27 +980,6 @@ public class ActivityStackTests extends ActivityTestsBase { } @Test - public void testAdjustFocusedStackToHomeWhenNoActivity() { - final ActivityStack homeStask = mDefaultDisplay.getHomeStack(); - TaskRecord homeTask = homeStask.topTask(); - if (homeTask == null) { - // Create home task if there isn't one. - homeTask = new TaskBuilder(mSupervisor).setStack(homeStask).build(); - } - - final ActivityRecord topActivity = new ActivityBuilder(mService).setTask(mTask).build(); - mStack.moveToFront("testAdjustFocusedStack"); - - // Simulate that home activity has not been started or is force-stopped. - homeStask.removeTask(homeTask, "testAdjustFocusedStack", REMOVE_TASK_MODE_DESTROYING); - - // Finish the only activity. - topActivity.finishIfPossible("testAdjustFocusedStack", false /* oomAdj */); - // Although home stack is empty, it should still be the focused stack. - assertEquals(homeStask, mDefaultDisplay.getFocusedStack()); - } - - @Test public void testWontFinishHomeStackImmediately() { final ActivityStack homeStack = createStackForShouldBeVisibleTest(mDefaultDisplay, WINDOWING_MODE_FULLSCREEN, ACTIVITY_TYPE_HOME, true /* onTop */); 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 ace5d4efa39b..a28bbb60d70c 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityStarterTests.java @@ -715,7 +715,7 @@ public class ActivityStarterTests extends ActivityTestsBase { if (startedActivity != null && startedActivity.getTaskRecord() != null) { // Remove the activity so it doesn't interfere with with subsequent activity launch // tests from this method. - startedActivity.getTaskRecord().mTask.removeChild(startedActivity); + startedActivity.getTaskRecord().removeChild(startedActivity); } } diff --git a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java index 78db6c92772f..1db8f1b1b596 100644 --- a/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/wm/ActivityTestsBase.java @@ -269,7 +269,7 @@ class ActivityTestsBase extends SystemServiceTestsBase { // fullscreen value is normally read from resources in ctor, so for testing we need // to set it somewhere else since we can't mock resources. doReturn(true).when(activity).occludesParent(); - activity.setTask(mTaskRecord); + mTaskRecord.addChild(activity); // Make visible by default... activity.setHidden(false); } @@ -376,15 +376,13 @@ class ActivityTestsBase extends SystemServiceTestsBase { final TaskRecord task = new TaskRecord(mSupervisor.mService, mTaskId, aInfo, intent /*intent*/, mVoiceSession, null /*_voiceInteractor*/, - null /*taskDescription*/); + null /*taskDescription*/, mStack); spyOn(task); task.mUserId = mUserId; if (mStack != null) { mStack.moveToFront("test"); - mStack.addTask(task, true, "creating test task"); - task.createTask(true, true); - spyOn(task.mTask); + mStack.addChild(task, true, true); } return task; diff --git a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java index 1fb6a563aa40..c5301b8a8c6e 100644 --- a/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/AppChangeTransitionTests.java @@ -165,7 +165,7 @@ public class AppChangeTransitionTests extends WindowTestsBase { // setup currently defaults to no snapshot. setUpOnDisplay(mDisplayContent); - mTask.mTaskRecord.setWindowingMode(WINDOWING_MODE_FREEFORM); + mTask.setWindowingMode(WINDOWING_MODE_FREEFORM); assertEquals(1, mDisplayContent.mChangingApps.size()); assertTrue(mActivity.isInChangeTransition()); diff --git a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java index 2f0486d3e81b..d33dbd1dda7c 100644 --- a/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/AppWindowTokenTests.java @@ -48,7 +48,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; +import static org.mockito.Mockito.reset; import static org.mockito.Mockito.verify; import android.content.res.Configuration; @@ -63,7 +63,6 @@ import androidx.test.filters.SmallTest; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; -import org.mockito.Mockito; /** * Tests for the {@link ActivityRecord} class. @@ -209,9 +208,11 @@ public class AppWindowTokenTests extends WindowTestsBase { @Test public void testSizeCompatBounds() { + // TODO(task-merge): Move once Task is merged into TaskRecord + final TaskRecord tr = (TaskRecord) mTask; // Disable the real configuration resolving because we only simulate partial flow. // TODO: Have test use full flow. - doNothing().when(mTask.mTaskRecord).computeConfigResourceOverrides(any(), any()); + doNothing().when(tr).computeConfigResourceOverrides(any(), any()); final Rect fixedBounds = mActivity.getRequestedOverrideConfiguration().windowConfiguration .getBounds(); fixedBounds.set(0, 0, 1200, 1600); @@ -337,11 +338,9 @@ public class AppWindowTokenTests extends WindowTestsBase { mDisplayContent.getDisplayRotation().setFixedToUserRotation( DisplayRotation.FIXED_TO_USER_ROTATION_ENABLED); - - mTask.mTaskRecord = Mockito.mock(TaskRecord.class, RETURNS_DEEP_STUBS); + reset(mTask); mActivity.reportDescendantOrientationChangeIfNeeded(); - - verify(mTask.mTaskRecord).onConfigurationChanged(any(Configuration.class)); + verify(mTask).onConfigurationChanged(any(Configuration.class)); } @Test @@ -451,6 +450,7 @@ public class AppWindowTokenTests extends WindowTestsBase { @Test public void testTransitionAnimationBounds() { + removeGlobalMinSizeRestriction(); final Rect stackBounds = new Rect(0, 0, 1000, 600); final Rect taskBounds = new Rect(100, 400, 600, 800); mStack.setBounds(stackBounds); @@ -458,16 +458,16 @@ public class AppWindowTokenTests extends WindowTestsBase { // Check that anim bounds for freeform window match task bounds mTask.setWindowingMode(WINDOWING_MODE_FREEFORM); - assertEquals(taskBounds, mActivity.getAnimationBounds(STACK_CLIP_NONE)); + assertEquals(mTask.getBounds(), mActivity.getAnimationBounds(STACK_CLIP_NONE)); // STACK_CLIP_AFTER_ANIM should use task bounds since they will be clipped by // bounds animation layer. mTask.setWindowingMode(WINDOWING_MODE_FULLSCREEN); - assertEquals(taskBounds, mActivity.getAnimationBounds(STACK_CLIP_AFTER_ANIM)); + assertEquals(mTask.getBounds(), mActivity.getAnimationBounds(STACK_CLIP_AFTER_ANIM)); // STACK_CLIP_BEFORE_ANIM should use stack bounds since it won't be clipped later. mTask.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_PRIMARY); - assertEquals(stackBounds, mActivity.getAnimationBounds(STACK_CLIP_BEFORE_ANIM)); + assertEquals(mStack.getBounds(), mActivity.getAnimationBounds(STACK_CLIP_BEFORE_ANIM)); } @Test diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java index cc598ffa63bd..69091c61ec90 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RecentTasksTest.java @@ -885,7 +885,7 @@ public class RecentTasksTest extends ActivityTestsBase { final int taskId = task.mTaskId; mRecentTasks.add(task); // Only keep the task in RecentTasks. - task.removeWindowContainer(); + task.removeIfPossible(); mStack.remove(); // The following APIs should not restore task from recents to the active list. diff --git a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java index 839ddb2038ff..ca8f5351c73a 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java +++ b/services/tests/wmtests/src/com/android/server/wm/RecentsAnimationTest.java @@ -196,9 +196,6 @@ public class RecentsAnimationTest extends ActivityTestsBase { doReturn(app).when(mService).getProcessController(eq(recentActivity.processName), anyInt()); ClientLifecycleManager lifecycleManager = mService.getLifecycleManager(); doNothing().when(lifecycleManager).scheduleTransaction(any()); - AppWarnings appWarnings = mService.getAppWarningsLocked(); - spyOn(appWarnings); - doNothing().when(appWarnings).onStartActivity(any()); startRecentsActivity(); diff --git a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java index aa97de72e507..63f70c05f203 100644 --- a/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/RootActivityContainerTests.java @@ -36,7 +36,6 @@ import static com.android.dx.mockito.inline.extended.ExtendedMockito.spyOn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.times; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; import static com.android.server.wm.ActivityDisplay.POSITION_TOP; -import static com.android.server.wm.ActivityStack.REMOVE_TASK_MODE_DESTROYING; import static com.android.server.wm.ActivityStackSupervisor.ON_TOP; import static com.android.server.wm.RootActivityContainer.MATCH_TASK_IN_STACKS_OR_RECENT_TASKS_AND_RESTORE; @@ -272,8 +271,7 @@ public class RootActivityContainerTests extends ActivityTestsBase { assertTrue(pinnedActivity.isFocusable()); // Without the overridding activity, stack should not be focusable. - pinnedStack.removeTask(pinnedActivity.getTaskRecord(), "testFocusability", - REMOVE_TASK_MODE_DESTROYING); + pinnedStack.removeChild(pinnedActivity.getTaskRecord(), "testFocusability"); assertFalse(pinnedStack.isFocusable()); } diff --git a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java index fa1f435a37c0..ad1d1afe7603 100644 --- a/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java +++ b/services/tests/wmtests/src/com/android/server/wm/SystemServicesTestRule.java @@ -437,6 +437,10 @@ public class SystemServicesTestRule implements TestRule { spyOn(getLockTaskController()); spyOn(getTaskChangeNotificationController()); initRootActivityContainerMocks(); + + AppWarnings appWarnings = getAppWarningsLocked(); + spyOn(appWarnings); + doNothing().when(appWarnings).onStartActivity(any()); } void initRootActivityContainerMocks() { diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java index df55b39b0817..012eb5252c50 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositionerTests.java @@ -79,8 +79,9 @@ public class TaskPositionerTests extends WindowTestsBase { // This should be the same calculation as the TaskPositioner uses. mMinVisibleWidth = dipToPixel(MINIMUM_VISIBLE_WIDTH_IN_DP, dm); mMinVisibleHeight = dipToPixel(MINIMUM_VISIBLE_HEIGHT_IN_DP, dm); + removeGlobalMinSizeRestriction(); - mPositioner = new TaskPositioner(mWm, mock(IActivityTaskManager.class)); + mPositioner = new TaskPositioner(mWm, mWm.mAtmService); mPositioner.register(mDisplayContent); mWindow = createWindow(null, TYPE_BASE_APPLICATION, "window"); @@ -493,10 +494,7 @@ public class TaskPositionerTests extends WindowTestsBase { + ") " + Log.getStackTraceString(new Throwable())); } } - assertEquals("left", expected.left, actual.left); - assertEquals("right", expected.right, actual.right); - assertEquals("top", expected.top, actual.top); - assertEquals("bottom", expected.bottom, actual.bottom); + assertEquals(expected, actual); } @FlakyTest(bugId = 129492888) diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java index f8d49ad18664..d2342f081fa1 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskPositioningControllerTests.java @@ -66,7 +66,8 @@ public class TaskPositioningControllerTests extends WindowTestsBase { any(InputChannel.class))).thenReturn(true); mWindow = createWindow(null, TYPE_BASE_APPLICATION, "window"); - mWindow.getTask().setResizeable(RESIZE_MODE_RESIZEABLE); + // TODO(task-merge): Remove cast. + ((TaskRecord) mWindow.getTask()).setResizeMode(RESIZE_MODE_RESIZEABLE); mWindow.mInputChannel = new InputChannel(); mWm.mWindowMap.put(mWindow.mClient.asBinder(), mWindow); doReturn(mock(InputMonitor.class)).when(mDisplayContent).getInputMonitor(); @@ -142,7 +143,8 @@ public class TaskPositioningControllerTests extends WindowTestsBase { doReturn(mWindow.getTask()).when(content).findTaskForResizePoint(anyInt(), anyInt()); assertNotNull(mWindow.getTask().getTopVisibleAppMainWindow()); - mWindow.getTask().setResizeable(RESIZE_MODE_UNRESIZEABLE); + // TODO(task-merge): Remove cast. + ((TaskRecord) mWindow.getTask()).setResizeMode(RESIZE_MODE_UNRESIZEABLE); mTarget.handleTapOutsideTask(content, 0, 0); // Wait until the looper processes finishTaskPositioning. diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java index a4e38f15e0e7..2cafc965e648 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskRecordTests.java @@ -132,7 +132,7 @@ public class TaskRecordTests extends ActivityTestsBase { @Test public void testCopyBaseIntentForTaskInfo() { final TaskRecord task = createTaskRecord(1); - task.mTaskDescription = new ActivityManager.TaskDescription(); + task.setTaskDescription(new ActivityManager.TaskDescription()); final TaskInfo info = task.getTaskInfo(); // The intent of info should be a copy so assert that they are different instances. @@ -348,10 +348,12 @@ public class TaskRecordTests extends ActivityTestsBase { TaskRecord task = stack.getChildAt(0); ActivityRecord root = task.getTopActivity(); - final WindowContainer parentWindowContainer = mock(WindowContainer.class); - Mockito.doReturn(parentWindowContainer).when(task.mTask).getParent(); - Mockito.doReturn(true).when(parentWindowContainer) - .handlesOrientationChangeFromDescendant(); + final WindowContainer parentWindowContainer = + new WindowContainer(mSystemServicesTestRule.getWindowManagerService()); + spyOn(parentWindowContainer); + parentWindowContainer.setBounds(fullScreenBounds); + doReturn(parentWindowContainer).when(task).getParent(); + doReturn(true).when(parentWindowContainer).handlesOrientationChangeFromDescendant(); // Setting app to fixed portrait fits within parent, but TaskRecord shouldn't adjust the // bounds because its parent says it will handle it at a later time. @@ -433,7 +435,7 @@ public class TaskRecordTests extends ActivityTestsBase { info.targetActivity = targetClassName; final TaskRecord task = TaskRecord.create(mService, 1 /* taskId */, info, intent, - null /* taskDescription */); + null /* taskDescription */, null /*stack*/); assertEquals("The alias activity component should be saved in task intent.", aliasClassName, task.intent.getComponent().getClassName()); @@ -834,8 +836,9 @@ public class TaskRecordTests extends ActivityTestsBase { private TaskRecord createTaskRecord(int taskId) { return new TaskRecord(mService, taskId, new Intent(), null, null, null, ActivityBuilder.getDefaultComponent(), null, false, false, false, 0, 10050, null, - new ArrayList<>(), 0, false, null, 0, 0, 0, 0, 0, null, 0, false, false, false, 0, - 0, null /*ActivityInfo*/, null /*_voiceSession*/, null /*_voiceInteractor*/); + 0, false, null, 0, 0, 0, 0, 0, null, 0, false, false, false, 0, + 0, null /*ActivityInfo*/, null /*_voiceSession*/, null /*_voiceInteractor*/, + null /*stack*/); } private static class TestTaskRecordFactory extends TaskRecordFactory { @@ -843,16 +846,16 @@ public class TaskRecordTests extends ActivityTestsBase { @Override TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, - IVoiceInteractionSession voiceSession, IVoiceInteractor voiceInteractor) { + Intent intent, IVoiceInteractionSession voiceSession, + IVoiceInteractor voiceInteractor, ActivityStack stack) { mCreated = true; return null; } @Override TaskRecord create(ActivityTaskManagerService service, int taskId, ActivityInfo info, - Intent intent, - ActivityManager.TaskDescription taskDescription) { + Intent intent, ActivityManager.TaskDescription taskDescription, + ActivityStack stack) { mCreated = true; return null; } @@ -863,14 +866,14 @@ public class TaskRecordTests extends ActivityTestsBase { ComponentName realActivity, ComponentName origActivity, boolean rootWasReset, boolean autoRemoveRecents, boolean askedCompatMode, int userId, int effectiveUid, String lastDescription, - ArrayList<ActivityRecord> activities, long lastTimeMoved, + long lastTimeMoved, boolean neverRelinquishIdentity, ActivityManager.TaskDescription lastTaskDescription, int taskAffiliation, int prevTaskId, int nextTaskId, int taskAffiliationColor, int callingUid, String callingPackage, int resizeMode, boolean supportsPictureInPicture, boolean realActivitySuspended, boolean userSetupComplete, int minWidth, - int minHeight) { + int minHeight, ActivityStack stack) { mCreated = true; return null; } diff --git a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java index 4dfa26644fa9..cb2e1e03a446 100644 --- a/services/tests/wmtests/src/com/android/server/wm/TaskTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/TaskTests.java @@ -16,6 +16,8 @@ package com.android.server.wm; +import static android.app.WindowConfiguration.WINDOWING_MODE_FREEFORM; + import static com.android.dx.mockito.inline.extended.ExtendedMockito.doReturn; import static com.android.dx.mockito.inline.extended.ExtendedMockito.times; import static com.android.dx.mockito.inline.extended.ExtendedMockito.verify; @@ -92,7 +94,7 @@ public class TaskTests extends WindowTestsBase { boolean gotException = false; try { - task.reparent(stackController1, 0, false/* moveParents */); + task.reparent(stackController1, 0, false/* moveParents */, "testReparent"); } catch (IllegalArgumentException e) { gotException = true; } @@ -100,14 +102,14 @@ public class TaskTests extends WindowTestsBase { gotException = false; try { - task.reparent(null, 0, false/* moveParents */); + task.reparent(null, 0, false/* moveParents */, "testReparent"); } catch (IllegalArgumentException e) { gotException = true; } assertTrue("Should not be able to reparent to a stack that doesn't exist", gotException); - task.reparent(stackController2, 0, false/* moveParents */); + task.reparent(stackController2, 0, false/* moveParents */, "testReparent"); assertEquals(stackController2, task.getParent()); assertEquals(0, task.getParent().mChildren.indexOf(task)); assertEquals(1, task2.getParent().mChildren.indexOf(task2)); @@ -125,7 +127,7 @@ public class TaskTests extends WindowTestsBase { final TaskStack stack2 = createTaskStackOnDisplay(dc); final Task task2 = createTaskInStack(stack2, 0 /* userId */); // Reparent and check state - task.reparent(stack2, 0, false /* moveParents */); + task.reparent(stack2, 0, false /* moveParents */, "testReparent_BetweenDisplays"); assertEquals(stack2, task.getParent()); assertEquals(0, task.getParent().mChildren.indexOf(task)); assertEquals(1, task2.getParent().mChildren.indexOf(task2)); @@ -138,6 +140,7 @@ public class TaskTests extends WindowTestsBase { final Task task = createTaskInStack(stack1, 0 /* userId */); // Check that setting bounds also updates surface position + task.setWindowingMode(WINDOWING_MODE_FREEFORM); Rect bounds = new Rect(10, 10, 100, 200); task.setBounds(bounds); assertEquals(new Point(bounds.left, bounds.top), task.getLastSurfacePosition()); diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java index 8cd97cb8a344..428d869fe3cd 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowFrameTests.java @@ -255,6 +255,7 @@ public class WindowFrameTests extends WindowTestsBase { @Test public void testLayoutNonfullscreenTask() { + removeGlobalMinSizeRestriction(); final DisplayInfo displayInfo = mWm.getDefaultDisplayContentLocked().getDisplayInfo(); final int logicalWidth = displayInfo.logicalWidth; final int logicalHeight = displayInfo.logicalHeight; @@ -264,8 +265,8 @@ public class WindowFrameTests extends WindowTestsBase { WindowState w = createWindow(); final Task task = w.getTask(); // Use split-screen because it is non-fullscreen, but also not floating - task.mTaskRecord.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY); - task.mTaskRecord.setBounds(taskBounds); + task.setWindowingMode(WINDOWING_MODE_SPLIT_SCREEN_SECONDARY); + task.setBounds(taskBounds); // The bounds we are requesting might be different from what the system resolved based on // other factors. final Rect resolvedTaskBounds = task.getBounds(); @@ -303,8 +304,8 @@ public class WindowFrameTests extends WindowTestsBase { final int insetTop = logicalHeight / 5; final int insetRight = insetLeft + (resolvedTaskBounds.right - resolvedTaskBounds.left); final int insetBottom = insetTop + (resolvedTaskBounds.bottom - resolvedTaskBounds.top); - task.mTaskRecord.setDisplayedBounds(resolvedTaskBounds); - task.mTaskRecord.setBounds(insetLeft, insetTop, insetRight, insetBottom); + task.setOverrideDisplayedBounds(resolvedTaskBounds); + task.setBounds(insetLeft, insetTop, insetRight, insetBottom); windowFrames.setFrames(pf, pf, pf, cf, cf, pf, cf, mEmptyRect); w.computeFrameLw(); assertEquals(resolvedTaskBounds, w.getFrameLw()); @@ -477,7 +478,7 @@ public class WindowFrameTests extends WindowTestsBase { WindowState w = createWindow(); final Task task = w.getTask(); w.mAttrs.gravity = Gravity.LEFT | Gravity.TOP; - task.mTaskRecord.setWindowingMode(WINDOWING_MODE_FREEFORM); + task.setWindowingMode(WINDOWING_MODE_FREEFORM); DisplayContent dc = mTestDisplayContent; dc.mInputMethodTarget = w; @@ -499,7 +500,7 @@ public class WindowFrameTests extends WindowTestsBase { // First check that it only gets moved up enough to show window. final Rect winRect = new Rect(200, 200, 300, 500); - task.mTaskRecord.setBounds(winRect); + task.setBounds(winRect); w.getWindowFrames().setFrames(pf, df, of, cf, vf, dcf, sf, mEmptyRect); w.computeFrameLw(); @@ -511,7 +512,7 @@ public class WindowFrameTests extends WindowTestsBase { // Now check that it won't get moved beyond the top and then has appropriate insets winRect.bottom = 600; - task.mTaskRecord.setBounds(winRect); + task.setBounds(winRect); w.setBounds(winRect); w.getWindowFrames().setFrames(pf, df, of, cf, vf, dcf, sf, mEmptyRect); w.computeFrameLw(); diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java index 51daf6567a47..3f32e33a76ec 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestUtils.java @@ -42,7 +42,7 @@ class WindowTestUtils { .setUserId(userId) .setStack(stack.mActivityStack) .build(); - return task.mTask; + return task; } } diff --git a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java index 780fed9805cb..c3f59eb75460 100644 --- a/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java +++ b/services/tests/wmtests/src/com/android/server/wm/WindowTestsBase.java @@ -384,7 +384,7 @@ class WindowTestsBase extends SystemServiceTestsBase { } /** Sets the default minimum task size to 1 so that tests can use small task sizes */ - public void removeGlobalMinSizeRestriction() { + void removeGlobalMinSizeRestriction() { mWm.mAtmService.mRootActivityContainer.mDefaultMinSizeOfResizeableTaskDp = 1; } } |