diff options
108 files changed, 2677 insertions, 1569 deletions
diff --git a/Android.bp b/Android.bp index a944bb937778..d04eb17adf15 100644 --- a/Android.bp +++ b/Android.bp @@ -962,6 +962,7 @@ metalava_framework_docs_args = "--manifest $(location core/res/AndroidManifest.x "--hide-package com.android.org.conscrypt --hide-package com.android.server " + "--error UnhiddenSystemApi " + "--hide RequiresPermission " + + "--hide CallbackInterface " + "--hide MissingPermission --hide BroadcastBehavior " + "--hide HiddenSuperclass --hide DeprecationMismatch --hide UnavailableSymbol " + "--hide SdkConstant --hide HiddenTypeParameter --hide Todo --hide Typo " + diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java index eb22d0907525..593e49490e94 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerService.java @@ -59,9 +59,7 @@ import android.os.Looper; import android.os.Message; import android.os.Process; import android.os.RemoteException; -import android.os.ResultReceiver; import android.os.ServiceManager; -import android.os.ShellCallback; import android.os.SystemClock; import android.os.UserHandle; import android.os.UserManagerInternal; @@ -2690,12 +2688,13 @@ public class JobSchedulerService extends com.android.server.SystemService } @Override - public void onShellCommand(FileDescriptor in, FileDescriptor out, FileDescriptor err, - String[] args, ShellCallback callback, ResultReceiver resultReceiver) { - (new JobSchedulerShellCommand(JobSchedulerService.this)).exec( - this, in, out, err, args, callback, resultReceiver); + protected int handleShellCommand(@NonNull FileDescriptor in, @NonNull FileDescriptor out, + @NonNull FileDescriptor err, @NonNull String[] args) { + return (new JobSchedulerShellCommand(JobSchedulerService.this)).exec( + this, in, out, err, args); } + /** * <b>For internal system user only!</b> * Returns a list of all currently-executing jobs. diff --git a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerShellCommand.java b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerShellCommand.java index 01d158ba9452..a5c6c0132fc8 100644 --- a/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerShellCommand.java +++ b/apex/jobscheduler/service/java/com/android/server/job/JobSchedulerShellCommand.java @@ -20,13 +20,13 @@ import android.app.ActivityManager; import android.app.AppGlobals; import android.content.pm.IPackageManager; import android.content.pm.PackageManager; +import android.os.BasicShellCommandHandler; import android.os.Binder; -import android.os.ShellCommand; import android.os.UserHandle; import java.io.PrintWriter; -public final class JobSchedulerShellCommand extends ShellCommand { +public final class JobSchedulerShellCommand extends BasicShellCommandHandler { public static final int CMD_ERR_NO_PACKAGE = -1000; public static final int CMD_ERR_NO_JOB = -1001; public static final int CMD_ERR_CONSTRAINTS = -1002; diff --git a/api/current.txt b/api/current.txt index 55983c86ee4b..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; @@ -50390,34 +50391,34 @@ package android.view { } public class TextureView extends android.view.View { - ctor public TextureView(android.content.Context); - ctor public TextureView(android.content.Context, android.util.AttributeSet); - ctor public TextureView(android.content.Context, android.util.AttributeSet, int); - ctor public TextureView(android.content.Context, android.util.AttributeSet, int, int); + ctor public TextureView(@NonNull android.content.Context); + ctor public TextureView(@NonNull android.content.Context, @Nullable android.util.AttributeSet); + ctor public TextureView(@NonNull android.content.Context, @Nullable android.util.AttributeSet, int); + ctor public TextureView(@NonNull android.content.Context, @Nullable android.util.AttributeSet, int, int); method public final void draw(android.graphics.Canvas); - method public android.graphics.Bitmap getBitmap(); - method public android.graphics.Bitmap getBitmap(int, int); - method public android.graphics.Bitmap getBitmap(android.graphics.Bitmap); - method public android.graphics.SurfaceTexture getSurfaceTexture(); - method public android.view.TextureView.SurfaceTextureListener getSurfaceTextureListener(); - method public android.graphics.Matrix getTransform(android.graphics.Matrix); + method @Nullable public android.graphics.Bitmap getBitmap(); + method @Nullable public android.graphics.Bitmap getBitmap(int, int); + method @NonNull public android.graphics.Bitmap getBitmap(@NonNull android.graphics.Bitmap); + method @Nullable public android.graphics.SurfaceTexture getSurfaceTexture(); + method @Nullable public android.view.TextureView.SurfaceTextureListener getSurfaceTextureListener(); + method @NonNull public android.graphics.Matrix getTransform(@Nullable android.graphics.Matrix); method public boolean isAvailable(); - method public android.graphics.Canvas lockCanvas(); - method public android.graphics.Canvas lockCanvas(android.graphics.Rect); + method @Nullable public android.graphics.Canvas lockCanvas(); + method @Nullable public android.graphics.Canvas lockCanvas(@Nullable android.graphics.Rect); method protected final void onDraw(android.graphics.Canvas); method public void setBackgroundDrawable(android.graphics.drawable.Drawable); method public void setOpaque(boolean); - method public void setSurfaceTexture(android.graphics.SurfaceTexture); - method public void setSurfaceTextureListener(android.view.TextureView.SurfaceTextureListener); - method public void setTransform(android.graphics.Matrix); - method public void unlockCanvasAndPost(android.graphics.Canvas); + method public void setSurfaceTexture(@NonNull android.graphics.SurfaceTexture); + method public void setSurfaceTextureListener(@Nullable android.view.TextureView.SurfaceTextureListener); + method public void setTransform(@Nullable android.graphics.Matrix); + method public void unlockCanvasAndPost(@NonNull android.graphics.Canvas); } public static interface TextureView.SurfaceTextureListener { - method public void onSurfaceTextureAvailable(android.graphics.SurfaceTexture, int, int); - method public boolean onSurfaceTextureDestroyed(android.graphics.SurfaceTexture); - method public void onSurfaceTextureSizeChanged(android.graphics.SurfaceTexture, int, int); - method public void onSurfaceTextureUpdated(android.graphics.SurfaceTexture); + method public void onSurfaceTextureAvailable(@NonNull android.graphics.SurfaceTexture, int, int); + method public boolean onSurfaceTextureDestroyed(@NonNull android.graphics.SurfaceTexture); + method public void onSurfaceTextureSizeChanged(@NonNull android.graphics.SurfaceTexture, int, int); + method public void onSurfaceTextureUpdated(@NonNull android.graphics.SurfaceTexture); } public class TouchDelegate { @@ -50677,7 +50678,7 @@ package android.view { method public final int getScrollY(); method @android.view.ViewDebug.ExportedProperty(category="drawing") @ColorInt public int getSolidColor(); method @LayoutRes public int getSourceLayoutResId(); - method @android.view.ViewDebug.ExportedProperty(category="accessibility") @Nullable public final CharSequence getStateDescription(); + method @android.view.ViewDebug.ExportedProperty(category="accessibility") @Nullable public CharSequence getStateDescription(); method public android.animation.StateListAnimator getStateListAnimator(); method protected int getSuggestedMinimumHeight(); method protected int getSuggestedMinimumWidth(); diff --git a/api/system-current.txt b/api/system-current.txt index 9a241e836b88..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(); @@ -8408,7 +8429,6 @@ package android.telephony { method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean enableDataConnectivity(); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean enableModemForSlot(int, boolean); method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void enableVideoCalling(boolean); - method @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public void factoryReset(int); method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public String getAidForAppType(int); method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public java.util.List<android.service.carrier.CarrierIdentifier> getAllowedCarriers(int); method @Nullable @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public android.telephony.ImsiEncryptionInfo getCarrierInfoForImsiEncryption(int); @@ -8467,6 +8487,7 @@ package android.telephony { method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void requestNumberVerification(@NonNull android.telephony.PhoneNumberRange, long, @NonNull java.util.concurrent.Executor, @NonNull android.telephony.NumberVerificationCallback); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void resetCarrierKeysForImsiEncryption(); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public boolean resetRadioConfig(); + method @RequiresPermission(android.Manifest.permission.CONNECTIVITY_INTERNAL) public void resetSettings(); method @Deprecated @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setAllowedCarriers(int, java.util.List<android.service.carrier.CarrierIdentifier>); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setCarrierDataEnabled(boolean); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public int setCarrierRestrictionRules(@NonNull android.telephony.CarrierRestrictionRules); @@ -9084,20 +9105,20 @@ package android.telephony.ims { public class ImsMmTelManager implements android.telephony.ims.RegistrationManager { method @NonNull public static android.telephony.ims.ImsMmTelManager createForSubscriptionId(int); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getFeatureState(@NonNull java.util.function.Consumer<java.lang.Integer>, @NonNull java.util.concurrent.Executor) throws android.telephony.ims.ImsException; - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationState(@NonNull java.util.function.Consumer<java.lang.Integer>, @NonNull java.util.concurrent.Executor); - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationTransportType(@NonNull java.util.function.Consumer<java.lang.Integer>, @NonNull java.util.concurrent.Executor); + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>); + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationTransportType(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getVoWiFiModeSetting(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public int getVoWiFiRoamingModeSetting(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isAdvancedCallingSettingEnabled(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isAvailable(@android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability int, int); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isCapable(@android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability int, int); - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void isSupported(@android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability int, int, @NonNull java.util.function.Consumer<java.lang.Boolean>, @NonNull java.util.concurrent.Executor) throws android.telephony.ims.ImsException; + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void isSupported(@android.telephony.ims.feature.MmTelFeature.MmTelCapabilities.MmTelCapability int, int, @NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Boolean>) throws android.telephony.ims.ImsException; method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isTtyOverVolteEnabled(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isVoWiFiRoamingSettingEnabled(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isVoWiFiSettingEnabled(); method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public boolean isVtSettingEnabled(); method @Deprecated @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsMmTelManager.RegistrationCallback) throws android.telephony.ims.ImsException; - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull android.telephony.ims.RegistrationManager.RegistrationCallback, @NonNull java.util.concurrent.Executor) throws android.telephony.ims.ImsException; + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.RegistrationManager.RegistrationCallback) throws android.telephony.ims.ImsException; method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerMmTelCapabilityCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.ImsMmTelManager.CapabilityCallback) throws android.telephony.ims.ImsException; method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setAdvancedCallingSettingEnabled(boolean); method @RequiresPermission(android.Manifest.permission.MODIFY_PHONE_STATE) public void setRttCapabilitySetting(boolean); @@ -9557,9 +9578,9 @@ package android.telephony.ims { } public interface RegistrationManager { - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationState(@NonNull java.util.function.Consumer<java.lang.Integer>, @NonNull java.util.concurrent.Executor); - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationTransportType(@NonNull java.util.function.Consumer<java.lang.Integer>, @NonNull java.util.concurrent.Executor); - method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull android.telephony.ims.RegistrationManager.RegistrationCallback, @NonNull java.util.concurrent.Executor) throws android.telephony.ims.ImsException; + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationState(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>); + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void getRegistrationTransportType(@NonNull java.util.concurrent.Executor, @NonNull java.util.function.Consumer<java.lang.Integer>); + method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void registerImsRegistrationCallback(@NonNull java.util.concurrent.Executor, @NonNull android.telephony.ims.RegistrationManager.RegistrationCallback) throws android.telephony.ims.ImsException; method @RequiresPermission(android.Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void unregisterImsRegistrationCallback(@NonNull android.telephony.ims.RegistrationManager.RegistrationCallback); field public static final int REGISTRATION_STATE_NOT_REGISTERED = 0; // 0x0 field public static final int REGISTRATION_STATE_REGISTERED = 2; // 0x2 diff --git a/core/java/android/app/Notification.java b/core/java/android/app/Notification.java index efb9f6bb88f1..47118a81632e 100644 --- a/core/java/android/app/Notification.java +++ b/core/java/android/app/Notification.java @@ -17,7 +17,6 @@ package android.app; import static android.annotation.Dimension.DP; -import static android.graphics.drawable.Icon.TYPE_BITMAP; import static com.android.internal.util.ContrastColorUtil.satisfiesTextContrast; @@ -8741,26 +8740,20 @@ public class Notification implements Parcelable * If your app produces multiple bubbles, the image should be unique for each of them. * </p> * - * <p>The shape of a bubble icon is adaptive and can match the device theme. + * <p>The shape of a bubble icon is adaptive and will match the device theme. * - * If your icon is bitmap-based, you should create it using - * {@link Icon#createWithAdaptiveBitmap(Bitmap)}, otherwise this method will throw. - * - * If your icon is not bitmap-based, you should expect that the icon will be tinted. + * Ideally your icon should be constructed via + * {@link Icon#createWithAdaptiveBitmap(Bitmap)}, otherwise, the icon will be shrunk + * and placed on an adaptive shape. * </p> * - * @throws IllegalArgumentException if icon is null or a non-adaptive bitmap + * @throws IllegalArgumentException if icon is null. */ @NonNull public BubbleMetadata.Builder setIcon(@NonNull Icon icon) { if (icon == null) { throw new IllegalArgumentException("Bubbles require non-null icon"); } - if (icon.getType() == TYPE_BITMAP) { - throw new IllegalArgumentException("When using bitmap based icons, Bubbles " - + "require TYPE_ADAPTIVE_BITMAP, please use" - + " Icon#createWithAdaptiveBitmap instead"); - } mIcon = icon; return this; } diff --git a/core/java/android/os/BasicShellCommandHandler.java b/core/java/android/os/BasicShellCommandHandler.java new file mode 100644 index 000000000000..5bd5d61b6361 --- /dev/null +++ b/core/java/android/os/BasicShellCommandHandler.java @@ -0,0 +1,320 @@ +/* + * 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 android.os; + +import android.util.Log; + +import java.io.BufferedInputStream; +import java.io.FileDescriptor; +import java.io.FileInputStream; +import java.io.FileOutputStream; +import java.io.InputStream; +import java.io.OutputStream; +import java.io.PrintWriter; + +/** + * Helper for implementing {@link Binder#onShellCommand Binder.onShellCommand}. This is meant to + * be copied into mainline modules, so this class must not use any hidden APIs. + * + * @hide + */ +public abstract class BasicShellCommandHandler { + static final String TAG = "ShellCommand"; + static final boolean DEBUG = false; + + private Binder mTarget; + private FileDescriptor mIn; + private FileDescriptor mOut; + private FileDescriptor mErr; + private String[] mArgs; + + private String mCmd; + private int mArgPos; + private String mCurArgData; + + private FileInputStream mFileIn; + private FileOutputStream mFileOut; + private FileOutputStream mFileErr; + + private PrintWriter mOutPrintWriter; + private PrintWriter mErrPrintWriter; + private InputStream mInputStream; + + public void init(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err, + String[] args, int firstArgPos) { + mTarget = target; + mIn = in; + mOut = out; + mErr = err; + mArgs = args; + mCmd = null; + mArgPos = firstArgPos; + mCurArgData = null; + mFileIn = null; + mFileOut = null; + mFileErr = null; + mOutPrintWriter = null; + mErrPrintWriter = null; + mInputStream = null; + } + + public int exec(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err, + String[] args) { + String cmd; + int start; + if (args != null && args.length > 0) { + cmd = args[0]; + start = 1; + } else { + cmd = null; + start = 0; + } + init(target, in, out, err, args, start); + mCmd = cmd; + + if (DEBUG) { + RuntimeException here = new RuntimeException("here"); + here.fillInStackTrace(); + Log.d(TAG, "Starting command " + mCmd + " on " + mTarget, here); + Log.d(TAG, "Calling uid=" + Binder.getCallingUid() + + " pid=" + Binder.getCallingPid()); + } + int res = -1; + try { + res = onCommand(mCmd); + if (DEBUG) Log.d(TAG, "Executed command " + mCmd + " on " + mTarget); + } catch (Throwable e) { + // Unlike usual calls, in this case if an exception gets thrown + // back to us we want to print it back in to the dump data, since + // that is where the caller expects all interesting information to + // go. + PrintWriter eout = getErrPrintWriter(); + eout.println(); + eout.println("Exception occurred while executing: " + e.getMessage()); + e.printStackTrace(eout); + } finally { + if (DEBUG) Log.d(TAG, "Flushing output streams on " + mTarget); + if (mOutPrintWriter != null) { + mOutPrintWriter.flush(); + } + if (mErrPrintWriter != null) { + mErrPrintWriter.flush(); + } + if (DEBUG) Log.d(TAG, "Sending command result on " + mTarget); + } + if (DEBUG) Log.d(TAG, "Finished command " + mCmd + " on " + mTarget); + return res; + } + + /** + * Return the raw FileDescriptor for the output stream. + */ + public FileDescriptor getOutFileDescriptor() { + return mOut; + } + + /** + * Return direct raw access (not buffered) to the command's output data stream. + */ + public OutputStream getRawOutputStream() { + if (mFileOut == null) { + mFileOut = new FileOutputStream(mOut); + } + return mFileOut; + } + + /** + * Return a PrintWriter for formatting output to {@link #getRawOutputStream()}. + */ + public PrintWriter getOutPrintWriter() { + if (mOutPrintWriter == null) { + mOutPrintWriter = new PrintWriter(getRawOutputStream()); + } + return mOutPrintWriter; + } + + /** + * Return the raw FileDescriptor for the error stream. + */ + public FileDescriptor getErrFileDescriptor() { + return mErr; + } + + /** + * Return direct raw access (not buffered) to the command's error output data stream. + */ + public OutputStream getRawErrorStream() { + if (mFileErr == null) { + mFileErr = new FileOutputStream(mErr); + } + return mFileErr; + } + + /** + * Return a PrintWriter for formatting output to {@link #getRawErrorStream()}. + */ + public PrintWriter getErrPrintWriter() { + if (mErr == null) { + return getOutPrintWriter(); + } + if (mErrPrintWriter == null) { + mErrPrintWriter = new PrintWriter(getRawErrorStream()); + } + return mErrPrintWriter; + } + + /** + * Return the raw FileDescriptor for the input stream. + */ + public FileDescriptor getInFileDescriptor() { + return mIn; + } + + /** + * Return direct raw access (not buffered) to the command's input data stream. + */ + public InputStream getRawInputStream() { + if (mFileIn == null) { + mFileIn = new FileInputStream(mIn); + } + return mFileIn; + } + + /** + * Return buffered access to the command's {@link #getRawInputStream()}. + */ + public InputStream getBufferedInputStream() { + if (mInputStream == null) { + mInputStream = new BufferedInputStream(getRawInputStream()); + } + return mInputStream; + } + + /** + * Return the next option on the command line -- that is an argument that + * starts with '-'. If the next argument is not an option, null is returned. + */ + public String getNextOption() { + if (mCurArgData != null) { + String prev = mArgs[mArgPos - 1]; + throw new IllegalArgumentException("No argument expected after \"" + prev + "\""); + } + if (mArgPos >= mArgs.length) { + return null; + } + String arg = mArgs[mArgPos]; + if (!arg.startsWith("-")) { + return null; + } + mArgPos++; + if (arg.equals("--")) { + return null; + } + if (arg.length() > 1 && arg.charAt(1) != '-') { + if (arg.length() > 2) { + mCurArgData = arg.substring(2); + return arg.substring(0, 2); + } else { + mCurArgData = null; + return arg; + } + } + mCurArgData = null; + return arg; + } + + /** + * Return the next argument on the command line, whatever it is; if there are + * no arguments left, return null. + */ + public String getNextArg() { + if (mCurArgData != null) { + String arg = mCurArgData; + mCurArgData = null; + return arg; + } else if (mArgPos < mArgs.length) { + return mArgs[mArgPos++]; + } else { + return null; + } + } + + public String peekNextArg() { + if (mCurArgData != null) { + return mCurArgData; + } else if (mArgPos < mArgs.length) { + return mArgs[mArgPos]; + } else { + return null; + } + } + + /** + * Return the next argument on the command line, whatever it is; if there are + * no arguments left, throws an IllegalArgumentException to report this to the user. + */ + public String getNextArgRequired() { + String arg = getNextArg(); + if (arg == null) { + String prev = mArgs[mArgPos - 1]; + throw new IllegalArgumentException("Argument expected after \"" + prev + "\""); + } + return arg; + } + + public int handleDefaultCommands(String cmd) { + if (cmd == null || "help".equals(cmd) || "-h".equals(cmd)) { + onHelp(); + } else { + getOutPrintWriter().println("Unknown command: " + cmd); + } + return -1; + } + + public Binder getTarget() { + return mTarget; + } + + public String[] getAllArgs() { + return mArgs; + } + + /** + * Implement parsing and execution of a command. If it isn't a command you understand, + * call {@link #handleDefaultCommands(String)} and return its result as a last resort. + * Use {@link #getNextOption()}, {@link #getNextArg()}, and {@link #getNextArgRequired()} + * to process additional command line arguments. Command output can be written to + * {@link #getOutPrintWriter()} and errors to {@link #getErrPrintWriter()}. + * + * <p class="caution">Note that no permission checking has been done before entering this + * function, so you need to be sure to do your own security verification for any commands you + * are executing. The easiest way to do this is to have the ShellCommand contain + * only a reference to your service's aidl interface, and do all of your command + * implementations on top of that -- that way you can rely entirely on your executing security + * code behind that interface.</p> + * + * @param cmd The first command line argument representing the name of the command to execute. + * @return Return the command result; generally 0 or positive indicates success and + * negative values indicate error. + */ + public abstract int onCommand(String cmd); + + /** + * Implement this to print help text about your command to {@link #getOutPrintWriter()}. + */ + public abstract void onHelp(); +} 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/Binder.java b/core/java/android/os/Binder.java index ef3afabfe878..a856975e2501 100644 --- a/core/java/android/os/Binder.java +++ b/core/java/android/os/Binder.java @@ -37,7 +37,9 @@ import libcore.io.IoUtils; import libcore.util.NativeAllocationRegistry; import java.io.FileDescriptor; +import java.io.FileInputStream; import java.io.FileOutputStream; +import java.io.IOException; import java.io.PrintWriter; import java.lang.reflect.Modifier; @@ -905,11 +907,60 @@ public class Binder implements IBinder { @Nullable FileDescriptor err, @NonNull String[] args, @Nullable ShellCallback callback, @NonNull ResultReceiver resultReceiver) throws RemoteException { - FileOutputStream fout = new FileOutputStream(err != null ? err : out); - PrintWriter pw = new FastPrintWriter(fout); + + // First, convert in, out and err to @NonNull, by redirecting any that's null to /dev/null. + try { + if (in == null) { + in = new FileInputStream("/dev/null").getFD(); + } + if (out == null) { + out = new FileOutputStream("/dev/null").getFD(); + } + if (err == null) { + err = out; + } + } catch (IOException e) { + PrintWriter pw = new FastPrintWriter(new FileOutputStream(err != null ? err : out)); + pw.println("Failed to open /dev/null: " + e.getMessage()); + pw.flush(); + resultReceiver.send(-1, null); + return; + } + // Also make args @NonNull. + if (args == null) { + args = new String[0]; + } + + int result = -1; + try { + result = handleShellCommand(in, out, err, args); + } finally { + resultReceiver.send(result, null); + } + } + + /** + * System services can implement this method to implement ADB shell commands. + * + * TODO More Javadoc. + * TODO Add a generic way to define subcommands and their permissions. + * + * @param in standard input. + * @param out standard output. + * @param err standard error. + * @param args arguments passed to the command. Can be empty. The first argument is typically + * a subcommand, such as {@code run} for {@code adb shell cmd jobscheduler run}. + * + * @hide + */ + // @SystemApi TODO Make it a system API. + protected int handleShellCommand(@NonNull FileDescriptor in, @NonNull FileDescriptor out, + @NonNull FileDescriptor err, @NonNull String[] args) { + FileOutputStream ferr = new FileOutputStream(err); + PrintWriter pw = new FastPrintWriter(ferr); pw.println("No shell command implementation."); pw.flush(); - resultReceiver.send(0, null); + return 0; } /** diff --git a/core/java/android/os/ShellCommand.java b/core/java/android/os/ShellCommand.java index 2fe8726a0915..f3a6869687dc 100644 --- a/core/java/android/os/ShellCommand.java +++ b/core/java/android/os/ShellCommand.java @@ -33,105 +33,21 @@ import java.io.PrintWriter; * Helper for implementing {@link Binder#onShellCommand Binder.onShellCommand}. * @hide */ -public abstract class ShellCommand { - static final String TAG = "ShellCommand"; - static final boolean DEBUG = false; - - private Binder mTarget; - private FileDescriptor mIn; - private FileDescriptor mOut; - private FileDescriptor mErr; - private String[] mArgs; +public abstract class ShellCommand extends BasicShellCommandHandler { private ShellCallback mShellCallback; private ResultReceiver mResultReceiver; - private String mCmd; - private int mArgPos; - private String mCurArgData; - - private FileInputStream mFileIn; - private FileOutputStream mFileOut; - private FileOutputStream mFileErr; - - private FastPrintWriter mOutPrintWriter; - private FastPrintWriter mErrPrintWriter; - private InputStream mInputStream; - - public void init(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err, - String[] args, ShellCallback callback, int firstArgPos) { - mTarget = target; - mIn = in; - mOut = out; - mErr = err; - mArgs = args; - mShellCallback = callback; - mResultReceiver = null; - mCmd = null; - mArgPos = firstArgPos; - mCurArgData = null; - mFileIn = null; - mFileOut = null; - mFileErr = null; - mOutPrintWriter = null; - mErrPrintWriter = null; - mInputStream = null; - } - public int exec(Binder target, FileDescriptor in, FileDescriptor out, FileDescriptor err, String[] args, ShellCallback callback, ResultReceiver resultReceiver) { - String cmd; - int start; - if (args != null && args.length > 0) { - cmd = args[0]; - start = 1; - } else { - cmd = null; - start = 0; - } - init(target, in, out, err, args, callback, start); - mCmd = cmd; + mShellCallback = callback; mResultReceiver = resultReceiver; + final int result = super.exec(target, in, out, err, args); - if (DEBUG) { - RuntimeException here = new RuntimeException("here"); - here.fillInStackTrace(); - Slog.d(TAG, "Starting command " + mCmd + " on " + mTarget, here); - Slog.d(TAG, "Calling uid=" + Binder.getCallingUid() - + " pid=" + Binder.getCallingPid() + " ShellCallback=" + getShellCallback()); + if (mResultReceiver != null) { + mResultReceiver.send(result, null); } - int res = -1; - try { - res = onCommand(mCmd); - if (DEBUG) Slog.d(TAG, "Executed command " + mCmd + " on " + mTarget); - } catch (SecurityException e) { - PrintWriter eout = getErrPrintWriter(); - eout.println("Security exception: " + e.getMessage()); - eout.println(); - e.printStackTrace(eout); - } catch (Throwable e) { - // Unlike usual calls, in this case if an exception gets thrown - // back to us we want to print it back in to the dump data, since - // that is where the caller expects all interesting information to - // go. - PrintWriter eout = getErrPrintWriter(); - eout.println(); - eout.println("Exception occurred while executing:"); - e.printStackTrace(eout); - } finally { - if (DEBUG) Slog.d(TAG, "Flushing output streams on " + mTarget); - if (mOutPrintWriter != null) { - mOutPrintWriter.flush(); - } - if (mErrPrintWriter != null) { - mErrPrintWriter.flush(); - } - if (DEBUG) Slog.d(TAG, "Sending command result on " + mTarget); - if (mResultReceiver != null) { - mResultReceiver.send(res, null); - } - } - if (DEBUG) Slog.d(TAG, "Finished command " + mCmd + " on " + mTarget); - return res; + + return result; } /** @@ -146,90 +62,6 @@ public abstract class ShellCommand { } /** - * Return the raw FileDescriptor for the output stream. - */ - public FileDescriptor getOutFileDescriptor() { - return mOut; - } - - /** - * Return direct raw access (not buffered) to the command's output data stream. - */ - public OutputStream getRawOutputStream() { - if (mFileOut == null) { - mFileOut = new FileOutputStream(mOut); - } - return mFileOut; - } - - /** - * Return a PrintWriter for formatting output to {@link #getRawOutputStream()}. - */ - public PrintWriter getOutPrintWriter() { - if (mOutPrintWriter == null) { - mOutPrintWriter = new FastPrintWriter(getRawOutputStream()); - } - return mOutPrintWriter; - } - - /** - * Return the raw FileDescriptor for the error stream. - */ - public FileDescriptor getErrFileDescriptor() { - return mErr; - } - - /** - * Return direct raw access (not buffered) to the command's error output data stream. - */ - public OutputStream getRawErrorStream() { - if (mFileErr == null) { - mFileErr = new FileOutputStream(mErr); - } - return mFileErr; - } - - /** - * Return a PrintWriter for formatting output to {@link #getRawErrorStream()}. - */ - public PrintWriter getErrPrintWriter() { - if (mErr == null) { - return getOutPrintWriter(); - } - if (mErrPrintWriter == null) { - mErrPrintWriter = new FastPrintWriter(getRawErrorStream()); - } - return mErrPrintWriter; - } - - /** - * Return the raw FileDescriptor for the input stream. - */ - public FileDescriptor getInFileDescriptor() { - return mIn; - } - - /** - * Return direct raw access (not buffered) to the command's input data stream. - */ - public InputStream getRawInputStream() { - if (mFileIn == null) { - mFileIn = new FileInputStream(mIn); - } - return mFileIn; - } - - /** - * Return buffered access to the command's {@link #getRawInputStream()}. - */ - public InputStream getBufferedInputStream() { - if (mInputStream == null) { - mInputStream = new BufferedInputStream(getRawInputStream()); - } - return mInputStream; - } - - /** * Helper for just system services to ask the shell to open an output file. * @hide */ @@ -256,77 +88,19 @@ public abstract class ShellCommand { return null; } - /** - * Return the next option on the command line -- that is an argument that - * starts with '-'. If the next argument is not an option, null is returned. - */ - public String getNextOption() { - if (mCurArgData != null) { - String prev = mArgs[mArgPos - 1]; - throw new IllegalArgumentException("No argument expected after \"" + prev + "\""); - } - if (mArgPos >= mArgs.length) { - return null; - } - String arg = mArgs[mArgPos]; - if (!arg.startsWith("-")) { - return null; - } - mArgPos++; - if (arg.equals("--")) { - return null; - } - if (arg.length() > 1 && arg.charAt(1) != '-') { - if (arg.length() > 2) { - mCurArgData = arg.substring(2); - return arg.substring(0, 2); - } else { - mCurArgData = null; - return arg; - } - } - mCurArgData = null; - return arg; - } - - /** - * Return the next argument on the command line, whatever it is; if there are - * no arguments left, return null. - */ - public String getNextArg() { - if (mCurArgData != null) { - String arg = mCurArgData; - mCurArgData = null; - return arg; - } else if (mArgPos < mArgs.length) { - return mArgs[mArgPos++]; - } else { - return null; + public int handleDefaultCommands(String cmd) { + if ("dump".equals(cmd)) { + String[] newArgs = new String[getAllArgs().length-1]; + System.arraycopy(getAllArgs(), 1, newArgs, 0, getAllArgs().length-1); + getTarget().doDump(getOutFileDescriptor(), getOutPrintWriter(), newArgs); + return 0; } + return super.handleDefaultCommands(cmd); } @UnsupportedAppUsage public String peekNextArg() { - if (mCurArgData != null) { - return mCurArgData; - } else if (mArgPos < mArgs.length) { - return mArgs[mArgPos]; - } else { - return null; - } - } - - /** - * Return the next argument on the command line, whatever it is; if there are - * no arguments left, throws an IllegalArgumentException to report this to the user. - */ - public String getNextArgRequired() { - String arg = getNextArg(); - if (arg == null) { - String prev = mArgs[mArgPos - 1]; - throw new IllegalArgumentException("Argument expected after \"" + prev + "\""); - } - return arg; + return super.peekNextArg(); } /** @@ -335,43 +109,4 @@ public abstract class ShellCommand { public ShellCallback getShellCallback() { return mShellCallback; } - - public int handleDefaultCommands(String cmd) { - if ("dump".equals(cmd)) { - String[] newArgs = new String[mArgs.length-1]; - System.arraycopy(mArgs, 1, newArgs, 0, mArgs.length-1); - mTarget.doDump(mOut, getOutPrintWriter(), newArgs); - return 0; - } else if (cmd == null || "help".equals(cmd) || "-h".equals(cmd)) { - onHelp(); - } else { - getOutPrintWriter().println("Unknown command: " + cmd); - } - return -1; - } - - /** - * Implement parsing and execution of a command. If it isn't a command you understand, - * call {@link #handleDefaultCommands(String)} and return its result as a last resort. - * Use {@link #getNextOption()}, {@link #getNextArg()}, and {@link #getNextArgRequired()} - * to process additional command line arguments. Command output can be written to - * {@link #getOutPrintWriter()} and errors to {@link #getErrPrintWriter()}. - * - * <p class="caution">Note that no permission checking has been done before entering this function, - * so you need to be sure to do your own security verification for any commands you - * are executing. The easiest way to do this is to have the ShellCommand contain - * only a reference to your service's aidl interface, and do all of your command - * implementations on top of that -- that way you can rely entirely on your executing security - * code behind that interface.</p> - * - * @param cmd The first command line argument representing the name of the command to execute. - * @return Return the command result; generally 0 or positive indicates success and - * negative values indicate error. - */ - public abstract int onCommand(String cmd); - - /** - * Implement this to print help text about your command to {@link #getOutPrintWriter()}. - */ - public abstract void onHelp(); } 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/android/view/TextureView.java b/core/java/android/view/TextureView.java index 0175ba201dd1..5876b03476ce 100644 --- a/core/java/android/view/TextureView.java +++ b/core/java/android/view/TextureView.java @@ -16,6 +16,7 @@ package android.view; +import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.UnsupportedAppUsage; import android.content.Context; @@ -139,7 +140,7 @@ public class TextureView extends View { * * @param context The context to associate this view with. */ - public TextureView(Context context) { + public TextureView(@NonNull Context context) { super(context); } @@ -149,7 +150,7 @@ public class TextureView extends View { * @param context The context to associate this view with. * @param attrs The attributes of the XML tag that is inflating the view. */ - public TextureView(Context context, AttributeSet attrs) { + public TextureView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } @@ -162,7 +163,7 @@ public class TextureView extends View { * reference to a style resource that supplies default values for * the view. Can be 0 to not look for defaults. */ - public TextureView(Context context, AttributeSet attrs, int defStyleAttr) { + public TextureView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } @@ -179,7 +180,8 @@ public class TextureView extends View { * defStyleAttr is 0 or can not be found in the theme. Can be 0 * to not look for defaults. */ - public TextureView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { + public TextureView(@NonNull Context context, @Nullable AttributeSet attrs, + int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @@ -484,13 +486,13 @@ public class TextureView extends View { * situations, make sure this texture view is not marked opaque.</p> * * @param transform The transform to apply to the content of - * this view. + * this view. If null the transform will be set to identity. * * @see #getTransform(android.graphics.Matrix) * @see #isOpaque() * @see #setOpaque(boolean) */ - public void setTransform(Matrix transform) { + public void setTransform(@Nullable Matrix transform) { mMatrix.set(transform); mMatrixChanged = true; invalidateParentIfNeeded(); @@ -507,7 +509,7 @@ public class TextureView extends View { * * @see #setTransform(android.graphics.Matrix) */ - public Matrix getTransform(Matrix transform) { + public @NonNull Matrix getTransform(@Nullable Matrix transform) { if (transform == null) { transform = new Matrix(); } @@ -544,7 +546,7 @@ public class TextureView extends View { * @see #getBitmap(android.graphics.Bitmap) * @see #getBitmap(int, int) */ - public Bitmap getBitmap() { + public @Nullable Bitmap getBitmap() { return getBitmap(getWidth(), getHeight()); } @@ -571,7 +573,7 @@ public class TextureView extends View { * @see #getBitmap(android.graphics.Bitmap) * @see #getBitmap() */ - public Bitmap getBitmap(int width, int height) { + public @Nullable Bitmap getBitmap(int width, int height) { if (isAvailable() && width > 0 && height > 0) { return getBitmap(Bitmap.createBitmap(getResources().getDisplayMetrics(), width, height, Bitmap.Config.ARGB_8888)); @@ -602,7 +604,7 @@ public class TextureView extends View { * @throws IllegalStateException if the hardware rendering context cannot be * acquired to capture the bitmap */ - public Bitmap getBitmap(Bitmap bitmap) { + public @NonNull Bitmap getBitmap(@NonNull Bitmap bitmap) { if (bitmap != null && isAvailable()) { applyUpdate(); applyTransformMatrix(); @@ -649,12 +651,13 @@ public class TextureView extends View { * owned by another producer. For instance, if the TextureView is being used * to render the camera's preview you cannot invoke this method.</p> * - * @return A Canvas used to draw into the surface. + * @return A Canvas used to draw into the surface, or null if the surface cannot be locked for + * drawing (see {@link #isAvailable()}). * * @see #lockCanvas(android.graphics.Rect) * @see #unlockCanvasAndPost(android.graphics.Canvas) */ - public Canvas lockCanvas() { + public @Nullable Canvas lockCanvas() { return lockCanvas(null); } @@ -669,15 +672,17 @@ public class TextureView extends View { * already connected to an image producer (for instance: the camera, * OpenGL, a media player, etc.) * - * @param dirty Area of the surface that will be modified. + * @param dirty Area of the surface that will be modified. If null the area of the entire + * surface is used. - * @return A Canvas used to draw into the surface. + * @return A Canvas used to draw into the surface, or null if the surface cannot be locked for + * drawing (see {@link #isAvailable()}). * * @see #lockCanvas() * @see #unlockCanvasAndPost(android.graphics.Canvas) * @see #isAvailable() */ - public Canvas lockCanvas(Rect dirty) { + public @Nullable Canvas lockCanvas(@Nullable Rect dirty) { if (!isAvailable()) return null; if (mCanvas == null) { @@ -705,7 +710,7 @@ public class TextureView extends View { * @see #lockCanvas() * @see #lockCanvas(android.graphics.Rect) */ - public void unlockCanvasAndPost(Canvas canvas) { + public void unlockCanvasAndPost(@NonNull Canvas canvas) { if (mCanvas != null && canvas == mCanvas) { canvas.restoreToCount(mSaveCount); mSaveCount = 0; @@ -723,7 +728,7 @@ public class TextureView extends View { * * @see #isAvailable() */ - public SurfaceTexture getSurfaceTexture() { + public @Nullable SurfaceTexture getSurfaceTexture() { return mSurface; } @@ -742,7 +747,7 @@ public class TextureView extends View { * @param surfaceTexture The {@link SurfaceTexture} that the view should use. * @see SurfaceTexture#detachFromGLContext() */ - public void setSurfaceTexture(SurfaceTexture surfaceTexture) { + public void setSurfaceTexture(@NonNull SurfaceTexture surfaceTexture) { if (surfaceTexture == null) { throw new NullPointerException("surfaceTexture must not be null"); } @@ -781,7 +786,7 @@ public class TextureView extends View { * @see #setSurfaceTextureListener(android.view.TextureView.SurfaceTextureListener) * @see SurfaceTextureListener */ - public SurfaceTextureListener getSurfaceTextureListener() { + public @Nullable SurfaceTextureListener getSurfaceTextureListener() { return mListener; } @@ -792,25 +797,22 @@ public class TextureView extends View { * @see #getSurfaceTextureListener() * @see SurfaceTextureListener */ - public void setSurfaceTextureListener(SurfaceTextureListener listener) { + public void setSurfaceTextureListener(@Nullable SurfaceTextureListener listener) { mListener = listener; } @UnsupportedAppUsage private final SurfaceTexture.OnFrameAvailableListener mUpdateListener = - new SurfaceTexture.OnFrameAvailableListener() { - @Override - public void onFrameAvailable(SurfaceTexture surfaceTexture) { - updateLayer(); - invalidate(); - } - }; + surfaceTexture -> { + updateLayer(); + invalidate(); + }; /** * This listener can be used to be notified when the surface texture * associated with this texture view is available. */ - public static interface SurfaceTextureListener { + public interface SurfaceTextureListener { /** * Invoked when a {@link TextureView}'s SurfaceTexture is ready for use. * @@ -819,7 +821,7 @@ public class TextureView extends View { * @param width The width of the surface * @param height The height of the surface */ - public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height); + void onSurfaceTextureAvailable(@NonNull SurfaceTexture surface, int width, int height); /** * Invoked when the {@link SurfaceTexture}'s buffers size changed. @@ -829,7 +831,7 @@ public class TextureView extends View { * @param width The new width of the surface * @param height The new height of the surface */ - public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height); + void onSurfaceTextureSizeChanged(@NonNull SurfaceTexture surface, int width, int height); /** * Invoked when the specified {@link SurfaceTexture} is about to be destroyed. @@ -839,7 +841,7 @@ public class TextureView extends View { * * @param surface The surface about to be destroyed */ - public boolean onSurfaceTextureDestroyed(SurfaceTexture surface); + boolean onSurfaceTextureDestroyed(@NonNull SurfaceTexture surface); /** * Invoked when the specified {@link SurfaceTexture} is updated through @@ -847,7 +849,7 @@ public class TextureView extends View { * * @param surface The surface just updated */ - public void onSurfaceTextureUpdated(SurfaceTexture surface); + void onSurfaceTextureUpdated(@NonNull SurfaceTexture surface); } @UnsupportedAppUsage diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 1599afb358e0..b90ce876aeb3 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -8727,7 +8727,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, structure.setContextClickable(true); } structure.setClassName(getAccessibilityClassName().toString()); - structure.setContentDescription(getContentDescription()); + structure.setContentDescription(mContentDescription); } /** @@ -9934,8 +9934,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback, info.setImportantForAccessibility(isImportantForAccessibility()); info.setPackageName(mContext.getPackageName()); info.setClassName(getAccessibilityClassName()); - info.setStateDescription(getStateDescription()); - info.setContentDescription(getContentDescription()); + info.setStateDescription(mStateDescription); + info.setContentDescription(mContentDescription); info.setEnabled(isEnabled()); info.setClickable(isClickable()); @@ -10318,7 +10318,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, * @see #setStateDescription(CharSequence) */ @ViewDebug.ExportedProperty(category = "accessibility") - public final @Nullable CharSequence getStateDescription() { + public @Nullable CharSequence getStateDescription() { return mStateDescription; } @@ -13724,7 +13724,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, */ @UnsupportedAppUsage public CharSequence getIterableTextForAccessibility() { - return getContentDescription(); + return mContentDescription; } /** @@ -29514,9 +29514,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback, stream.addProperty("text:textAlignment", getTextAlignment()); // accessibility - CharSequence contentDescription = getContentDescription(); stream.addProperty("accessibility:contentDescription", - contentDescription == null ? "" : contentDescription.toString()); + mContentDescription == null ? "" : mContentDescription.toString()); + stream.addProperty("accessibility:stateDescription", + mStateDescription == null ? "" : mStateDescription.toString()); stream.addProperty("accessibility:labelFor", getLabelFor()); stream.addProperty("accessibility:importantForAccessibility", getImportantForAccessibility()); } diff --git a/core/java/android/view/WindowlessWindowManager.java b/core/java/android/view/WindowlessWindowManager.java index f4f7d0b33fd1..6c6046f1876f 100644 --- a/core/java/android/view/WindowlessWindowManager.java +++ b/core/java/android/view/WindowlessWindowManager.java @@ -93,8 +93,9 @@ class WindowlessWindowManager implements IWindowSession { DisplayCutout.ParcelableWrapper outDisplayCutout, InputChannel outInputChannel, InsetsState outInsetsState) { final SurfaceControl.Builder b = new SurfaceControl.Builder(mSurfaceSession) - .setParent(mRootSurface) - .setName(attrs.getTitle().toString()); + .setParent(mRootSurface) + .setFormat(attrs.format) + .setName(attrs.getTitle().toString()); final SurfaceControl sc = b.build(); synchronized (this) { mStateForWindow.put(window.asBinder(), new State(sc, attrs)); diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java index 7ee53f26b1f8..e81db16f0743 100644 --- a/core/java/android/view/inputmethod/InputMethodManager.java +++ b/core/java/android/view/inputmethod/InputMethodManager.java @@ -92,7 +92,10 @@ import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; /** @@ -422,6 +425,13 @@ public final class InputMethodManager { int mCursorCandEnd; /** + * Initial startInput with {@link StartInputReason.WINDOW_FOCUS_GAIN} is executed + * in a background thread. Later, if there is an actual startInput it will wait on + * main thread till the background thread completes. + */ + private CompletableFuture<Void> mWindowFocusGainFuture; + + /** * The instance that has previously been sent to the input method. */ private CursorAnchorInfo mCursorAnchorInfo = null; @@ -1598,6 +1608,18 @@ public final class InputMethodManager { boolean startInputInner(@StartInputReason int startInputReason, @Nullable IBinder windowGainingFocus, @StartInputFlags int startInputFlags, @SoftInputModeFlags int softInputMode, int windowFlags) { + if (startInputReason != StartInputReason.WINDOW_FOCUS_GAIN + && mWindowFocusGainFuture != null) { + try { + mWindowFocusGainFuture.get(); + } catch (ExecutionException | InterruptedException e) { + // do nothing + } catch (CancellationException e) { + // window no longer has focus. + return true; + } + } + final View view; synchronized (mH) { view = mServedView; @@ -1947,31 +1969,38 @@ public final class InputMethodManager { } } - if (checkFocusNoStartInput(forceNewFocus)) { - // We need to restart input on the current focus view. This - // should be done in conjunction with telling the system service - // about the window gaining focus, to help make the transition - // smooth. - if (startInputInner(StartInputReason.WINDOW_FOCUS_GAIN, rootView.getWindowToken(), - startInputFlags, softInputMode, windowFlags)) { - return; - } + final boolean forceNewFocus1 = forceNewFocus; + final int startInputFlags1 = startInputFlags; + if (mWindowFocusGainFuture != null) { + mWindowFocusGainFuture.cancel(false/* mayInterruptIfRunning */); } + mWindowFocusGainFuture = CompletableFuture.runAsync(() -> { + if (checkFocusNoStartInput(forceNewFocus1)) { + // We need to restart input on the current focus view. This + // should be done in conjunction with telling the system service + // about the window gaining focus, to help make the transition + // smooth. + if (startInputInner(StartInputReason.WINDOW_FOCUS_GAIN, rootView.getWindowToken(), + startInputFlags1, softInputMode, windowFlags)) { + return; + } + } - // For some reason we didn't do a startInput + windowFocusGain, so - // we'll just do a window focus gain and call it a day. - synchronized (mH) { - try { - if (DEBUG) Log.v(TAG, "Reporting focus gain, without startInput"); - mService.startInputOrWindowGainedFocus( - StartInputReason.WINDOW_FOCUS_GAIN_REPORT_ONLY, mClient, - rootView.getWindowToken(), startInputFlags, softInputMode, windowFlags, - null, null, 0 /* missingMethodFlags */, - rootView.getContext().getApplicationInfo().targetSdkVersion); - } catch (RemoteException e) { - throw e.rethrowFromSystemServer(); + // For some reason we didn't do a startInput + windowFocusGain, so + // we'll just do a window focus gain and call it a day. + synchronized (mH) { + try { + if (DEBUG) Log.v(TAG, "Reporting focus gain, without startInput"); + mService.startInputOrWindowGainedFocus( + StartInputReason.WINDOW_FOCUS_GAIN_REPORT_ONLY, mClient, + rootView.getWindowToken(), startInputFlags1, softInputMode, windowFlags, + null, null, 0 /* missingMethodFlags */, + rootView.getContext().getApplicationInfo().targetSdkVersion); + } catch (RemoteException e) { + throw e.rethrowFromSystemServer(); + } } - } + }); } /** @hide */ @@ -1986,6 +2015,10 @@ public final class InputMethodManager { // If the mCurRootView is losing window focus, release the strong reference to it // so as not to prevent it from being garbage-collected. mCurRootView = null; + if (mWindowFocusGainFuture != null) { + mWindowFocusGainFuture.cancel(false /* mayInterruptIfRunning */); + mWindowFocusGainFuture = null; + } } else { if (DEBUG) { Log.v(TAG, "Ignoring onPreWindowFocus()." diff --git a/core/java/android/webkit/WebSettings.java b/core/java/android/webkit/WebSettings.java index 7282008f7e3a..2895621f962a 100644 --- a/core/java/android/webkit/WebSettings.java +++ b/core/java/android/webkit/WebSettings.java @@ -328,6 +328,9 @@ public abstract class WebSettings { * <p> * The built-in mechanisms are the only currently supported zoom * mechanisms, so it is recommended that this setting is always enabled. + * However, on-screen zoom controls are deprecated in Android (see + * {@link android.widget.ZoomButtonsController}) so it's recommended to + * disable {@link #setDisplayZoomControls}. * * @param enabled whether the WebView should use its built-in zoom mechanisms */ @@ -347,7 +350,9 @@ public abstract class WebSettings { /** * Sets whether the WebView should display on-screen zoom controls when * using the built-in zoom mechanisms. See {@link #setBuiltInZoomControls}. - * The default is {@code true}. + * The default is {@code true}. However, on-screen zoom controls are deprecated + * in Android (see {@link android.widget.ZoomButtonsController}) so it's + * recommended to set this to {@code false}. * * @param enabled whether the WebView should display on-screen zoom controls */ diff --git a/core/java/com/android/internal/os/BaseCommand.java b/core/java/com/android/internal/os/BaseCommand.java index 278f40660ee9..e1b8e6c2d7d1 100644 --- a/core/java/com/android/internal/os/BaseCommand.java +++ b/core/java/com/android/internal/os/BaseCommand.java @@ -18,14 +18,14 @@ package com.android.internal.os; import android.annotation.UnsupportedAppUsage; -import android.os.ShellCommand; +import android.os.BasicShellCommandHandler; import java.io.PrintStream; public abstract class BaseCommand { @UnsupportedAppUsage - final protected ShellCommand mArgs = new ShellCommand() { + final protected BasicShellCommandHandler mArgs = new BasicShellCommandHandler() { @Override public int onCommand(String cmd) { return 0; } @@ -50,7 +50,7 @@ public abstract class BaseCommand { } mRawArgs = args; - mArgs.init(null, null, null, null, args, null, 0); + mArgs.init(null, null, null, null, args, 0); try { onRun(); 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/java/com/android/server/SystemConfig.java b/core/java/com/android/server/SystemConfig.java index db91dc5a8bc3..ed7f5de83fd1 100644 --- a/core/java/com/android/server/SystemConfig.java +++ b/core/java/com/android/server/SystemConfig.java @@ -540,6 +540,7 @@ public class SystemConfig { Slog.w(TAG, "Couldn't find or open permissions file " + permFile); return; } + Slog.i(TAG, "Reading permissions from " + permFile); final boolean lowRam = ActivityManager.isLowRamDeviceStatic(); diff --git a/core/res/res/values/config.xml b/core/res/res/values/config.xml index eaf93eb9e216..9ca98c570c89 100644 --- a/core/res/res/values/config.xml +++ b/core/res/res/values/config.xml @@ -3705,7 +3705,7 @@ name is separated by comma. Example: "com.android.phone,com.android.stk,com.android.providers.telephony" --> - <string name="config_telephonyPackages" translatable="false">"com.android.phone,com.android.stk,com.android.providers.telephony,com.android.ons"</string> + <string name="config_telephonyPackages" translatable="false">"com.android.phone,com.android.stk,com.android.providers.telephony,com.android.ons,com.android.cellbroadcastservice"</string> <!-- The package name for the default system wifi app. This package must be trusted, as it has the permissions to control wifi diff --git a/data/keyboards/Vendor_1532_Product_0900.kl b/data/keyboards/Vendor_1532_Product_0900.kl index c2fc1b4f9365..4c6c4dda02b0 100644 --- a/data/keyboards/Vendor_1532_Product_0900.kl +++ b/data/keyboards/Vendor_1532_Product_0900.kl @@ -20,13 +20,19 @@ key 307 BUTTON_X key 308 BUTTON_Y key 310 BUTTON_L1 key 311 BUTTON_R1 -key 316 BUTTON_MODE key 317 BUTTON_THUMBL key 318 BUTTON_THUMBR key 158 BACK key 172 HOME +# Left arrow to the left of the "power" key +key 0x13a BUTTON_SELECT +# Right arrow to the right of the "power" key +key 0x13b BUTTON_START +# Power key +key 0x13c BUTTON_MODE + axis 0x00 X axis 0x01 Y axis 0x02 Z diff --git a/libs/hwui/renderthread/CanvasContext.cpp b/libs/hwui/renderthread/CanvasContext.cpp index 4ca26c273c95..15e0c8d0a266 100644 --- a/libs/hwui/renderthread/CanvasContext.cpp +++ b/libs/hwui/renderthread/CanvasContext.cpp @@ -479,7 +479,8 @@ void CanvasContext::draw() { if (didDraw) { swap.damage = windowDirty; } else { - swap.damage = SkRect::MakeWH(INT_MAX, INT_MAX); + float max = static_cast<float>(INT_MAX); + swap.damage = SkRect::MakeWH(max, max); } swap.swapCompletedTime = systemTime(SYSTEM_TIME_MONOTONIC); swap.vsyncTime = mRenderThread.timeLord().latestVsync(); 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_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/mime/java-res/android.mime.types b/mime/java-res/android.mime.types index 7a5299ff1b69..ce022a8b0f19 100644 --- a/mime/java-res/android.mime.types +++ b/mime/java-res/android.mime.types @@ -48,6 +48,9 @@ ?application/epub+zip epub ?application/pkix-cert cer ?application/rss+xml rss +?application/sdp sdp +?application/smil+xml smil +?application/ttml+xml ttml dfxp ?application/vnd.android.ota ota ?application/vnd.apple.mpegurl m3u8 ?application/vnd.ms-pki.stl stl @@ -67,12 +70,13 @@ ?application/x-x509-server-cert crt ?application/x-x509-user-cert crt -?audio/3gpp 3gpp +?audio/3gpp 3gpp 3ga ?audio/aac-adts aac +?audio/ac3 ac3 a52 ?audio/imelody imy ?audio/midi rtttl xmf ?audio/mobile-xmf mxmf -?audio/mp4 m4a +?audio/mp4 m4a m4b m4p f4a f4b f4p ?audio/mpegurl m3u ?audio/sp-midi smf ?audio/x-matroska mka @@ -101,10 +105,11 @@ ?text/xml xml ?text/x-vcard vcf -?video/3gpp2 3gpp2 3g2 +?video/3gpp2 3gpp2 3gp2 3g2 ?video/3gpp 3gpp ?video/avi avi ?video/m4v m4v +?video/mp4 m4v f4v mp4v mpeg4 ?video/mp2p mpeg ?video/mp2t m2ts mts ?video/mp2ts ts @@ -129,11 +134,11 @@ application/pgp-signature pgp application/x-x509-ca-cert crt -audio/aac aac +audio/aac aac adts adt audio/basic snd audio/flac flac audio/midi rtx -audio/mpeg mp3 m4a m4r +audio/mpeg mp3 mp2 mp1 mpa m4a m4r audio/x-mpegurl m3u m3u8 image/jpeg jpg image/x-ms-bmp bmp @@ -141,6 +146,6 @@ text/plain txt text/x-c++hdr hpp text/x-c++src cpp video/3gpp 3gpp -video/mpeg mpeg +video/mpeg mpeg mpeg2 mpv2 mp2v m2v m2t mpeg1 mpv1 mp1v m1v video/quicktime mov video/x-matroska mkv diff --git a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java index 706727bf050e..d3d9b286ded6 100644 --- a/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java +++ b/packages/CarSystemUI/src/com/android/systemui/CarSystemUIBinder.java @@ -16,100 +16,30 @@ package com.android.systemui; -import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME; - -import android.content.Context; -import android.os.PowerManager; -import android.util.DisplayMetrics; - -import com.android.internal.logging.MetricsLogger; -import com.android.keyguard.KeyguardUpdateMonitor; -import com.android.systemui.appops.AppOpsController; -import com.android.systemui.assist.AssistManager; import com.android.systemui.biometrics.AuthController; -import com.android.systemui.broadcast.BroadcastDispatcher; -import com.android.systemui.bubbles.BubbleController; -import com.android.systemui.colorextraction.SysuiColorExtractor; -import com.android.systemui.doze.DozeLog; import com.android.systemui.globalactions.GlobalActionsComponent; import com.android.systemui.keyguard.KeyguardViewMediator; -import com.android.systemui.keyguard.ScreenLifecycle; -import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.navigationbar.car.CarNavigationBar; -import com.android.systemui.navigationbar.car.CarNavigationBarController; import com.android.systemui.pip.PipUI; -import com.android.systemui.plugins.FalsingManager; import com.android.systemui.power.PowerUI; import com.android.systemui.recents.Recents; import com.android.systemui.recents.RecentsModule; -import com.android.systemui.shared.plugins.PluginManager; -import com.android.systemui.statusbar.CommandQueue; -import com.android.systemui.statusbar.FeatureFlags; -import com.android.systemui.statusbar.NavigationBarController; -import com.android.systemui.statusbar.NotificationListener; -import com.android.systemui.statusbar.NotificationLockscreenUserManager; -import com.android.systemui.statusbar.NotificationMediaManager; -import com.android.systemui.statusbar.NotificationRemoteInputManager; -import com.android.systemui.statusbar.NotificationViewHierarchyManager; -import com.android.systemui.statusbar.PulseExpansionHandler; -import com.android.systemui.statusbar.SysuiStatusBarStateController; -import com.android.systemui.statusbar.VibratorHelper; import com.android.systemui.statusbar.car.CarStatusBar; -import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; -import com.android.systemui.statusbar.notification.DynamicPrivacyController; +import com.android.systemui.statusbar.car.CarStatusBarModule; import com.android.systemui.statusbar.notification.InstantAppNotifier; -import com.android.systemui.statusbar.notification.NewNotifPipeline; -import com.android.systemui.statusbar.notification.NotificationAlertingManager; -import com.android.systemui.statusbar.notification.NotificationEntryManager; -import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider; -import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator; -import com.android.systemui.statusbar.notification.VisualStabilityManager; -import com.android.systemui.statusbar.notification.logging.NotifLog; -import com.android.systemui.statusbar.notification.logging.NotificationLogger; -import com.android.systemui.statusbar.notification.row.NotificationGutsManager; -import com.android.systemui.statusbar.phone.AutoHideController; -import com.android.systemui.statusbar.phone.BiometricUnlockController; -import com.android.systemui.statusbar.phone.DozeParameters; -import com.android.systemui.statusbar.phone.DozeScrimController; -import com.android.systemui.statusbar.phone.DozeServiceHost; -import com.android.systemui.statusbar.phone.HeadsUpManagerPhone; -import com.android.systemui.statusbar.phone.KeyguardBypassController; -import com.android.systemui.statusbar.phone.LightBarController; -import com.android.systemui.statusbar.phone.LockscreenWallpaper; -import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper; -import com.android.systemui.statusbar.phone.NotificationGroupManager; -import com.android.systemui.statusbar.phone.ScrimController; import com.android.systemui.statusbar.phone.StatusBar; -import com.android.systemui.statusbar.phone.StatusBarIconController; -import com.android.systemui.statusbar.phone.StatusBarWindowController; -import com.android.systemui.statusbar.phone.StatusBarWindowViewController; -import com.android.systemui.statusbar.policy.BatteryController; -import com.android.systemui.statusbar.policy.ConfigurationController; -import com.android.systemui.statusbar.policy.DeviceProvisionedController; -import com.android.systemui.statusbar.policy.KeyguardStateController; -import com.android.systemui.statusbar.policy.NetworkController; -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.statusbar.tv.TvStatusBar; import com.android.systemui.theme.ThemeOverlayController; -import com.android.systemui.util.InjectionInflationController; import com.android.systemui.util.leak.GarbageMonitor; import com.android.systemui.volume.VolumeUI; -import javax.inject.Named; -import javax.inject.Singleton; - import dagger.Binds; -import dagger.Lazy; import dagger.Module; -import dagger.Provides; import dagger.multibindings.ClassKey; import dagger.multibindings.IntoMap; /** Binder for car specific {@link SystemUI} modules. */ -@Module(includes = {RecentsModule.class}) +@Module(includes = {RecentsModule.class, CarStatusBarModule.class}) public abstract class CarSystemUIBinder { /** Inject into AuthController. */ @Binds @@ -219,147 +149,4 @@ public abstract class CarSystemUIBinder { @IntoMap @ClassKey(VolumeUI.class) public abstract SystemUI bindVolumeUI(VolumeUI sysui); - - /** - * Provides our instance of StatusBar which is considered optional. - */ - @Provides - @Singleton - static CarStatusBar provideStatusBar( - Context context, - FeatureFlags featureFlags, - LightBarController lightBarController, - AutoHideController autoHideController, - KeyguardUpdateMonitor keyguardUpdateMonitor, - StatusBarIconController statusBarIconController, - DozeLog dozeLog, - InjectionInflationController injectionInflationController, - PulseExpansionHandler pulseExpansionHandler, - NotificationWakeUpCoordinator notificationWakeUpCoordinator, - KeyguardBypassController keyguardBypassController, - KeyguardStateController keyguardStateController, - HeadsUpManagerPhone headsUpManagerPhone, - DynamicPrivacyController dynamicPrivacyController, - BypassHeadsUpNotifier bypassHeadsUpNotifier, - @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress, - Lazy<NewNotifPipeline> newNotifPipeline, - FalsingManager falsingManager, - BroadcastDispatcher broadcastDispatcher, - RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler, - NotificationGutsManager notificationGutsManager, - NotificationLogger notificationLogger, - NotificationEntryManager notificationEntryManager, - NotificationInterruptionStateProvider notificationInterruptionStateProvider, - NotificationViewHierarchyManager notificationViewHierarchyManager, - ForegroundServiceController foregroundServiceController, - AppOpsController appOpsController, - KeyguardViewMediator keyguardViewMediator, - ZenModeController zenModeController, - NotificationAlertingManager notificationAlertingManager, - DisplayMetrics displayMetrics, - MetricsLogger metricsLogger, - UiOffloadThread uiOffloadThread, - NotificationMediaManager notificationMediaManager, - NotificationLockscreenUserManager lockScreenUserManager, - NotificationRemoteInputManager remoteInputManager, - UserSwitcherController userSwitcherController, - NetworkController networkController, - BatteryController batteryController, - SysuiColorExtractor colorExtractor, - ScreenLifecycle screenLifecycle, - WakefulnessLifecycle wakefulnessLifecycle, - SysuiStatusBarStateController statusBarStateController, - VibratorHelper vibratorHelper, - BubbleController bubbleController, - NotificationGroupManager groupManager, - NotificationGroupAlertTransferHelper groupAlertTransferHelper, - VisualStabilityManager visualStabilityManager, - DeviceProvisionedController deviceProvisionedController, - NavigationBarController navigationBarController, - AssistManager assistManager, - NotificationListener notificationListener, - ConfigurationController configurationController, - StatusBarWindowController statusBarWindowController, - StatusBarWindowViewController.Builder statusBarWindowViewControllerBuilder, - NotifLog notifLog, - DozeParameters dozeParameters, - ScrimController scrimController, - Lazy<LockscreenWallpaper> lockscreenWallpaperLazy, - Lazy<BiometricUnlockController> biometricUnlockControllerLazy, - DozeServiceHost dozeServiceHost, - PowerManager powerManager, - DozeScrimController dozeScrimController, - CommandQueue commandQueue, - PluginManager pluginManager, - CarNavigationBarController carNavigationBarController, - RemoteInputUriController remoteInputUriController) { - return new CarStatusBar( - context, - featureFlags, - lightBarController, - autoHideController, - keyguardUpdateMonitor, - statusBarIconController, - dozeLog, - injectionInflationController, - pulseExpansionHandler, - notificationWakeUpCoordinator, - keyguardBypassController, - keyguardStateController, - headsUpManagerPhone, - dynamicPrivacyController, - bypassHeadsUpNotifier, - allowNotificationLongPress, - newNotifPipeline, - falsingManager, - broadcastDispatcher, - remoteInputQuickSettingsDisabler, - notificationGutsManager, - notificationLogger, - notificationEntryManager, - notificationInterruptionStateProvider, - notificationViewHierarchyManager, - foregroundServiceController, - appOpsController, - keyguardViewMediator, - zenModeController, - notificationAlertingManager, - displayMetrics, - metricsLogger, - uiOffloadThread, - notificationMediaManager, - lockScreenUserManager, - remoteInputManager, - userSwitcherController, - networkController, - batteryController, - colorExtractor, - screenLifecycle, - wakefulnessLifecycle, - statusBarStateController, - vibratorHelper, - bubbleController, - groupManager, - groupAlertTransferHelper, - visualStabilityManager, - deviceProvisionedController, - navigationBarController, - assistManager, - notificationListener, - configurationController, - statusBarWindowController, - statusBarWindowViewControllerBuilder, - notifLog, - dozeParameters, - scrimController, - lockscreenWallpaperLazy, - biometricUnlockControllerLazy, - dozeServiceHost, - powerManager, - dozeScrimController, - commandQueue, - pluginManager, - remoteInputUriController, - carNavigationBarController); - } } diff --git a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java index 98b91ebd8038..af92767efc49 100644 --- a/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java +++ b/packages/CarSystemUI/src/com/android/systemui/navigationbar/car/CarNavigationBar.java @@ -53,13 +53,13 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks private final CarNavigationBarController mCarNavigationBarController; private final WindowManager mWindowManager; private final DeviceProvisionedController mDeviceProvisionedController; + private final CommandQueue mCommandQueue; private final Lazy<FacetButtonTaskStackListener> mFacetButtonTaskStackListener; private final Handler mMainHandler; private final Lazy<KeyguardStateController> mKeyguardStateController; private final Lazy<NavigationBarController> mNavigationBarController; private IStatusBarService mBarService; - private CommandQueue mCommandQueue; private ActivityManagerWrapper mActivityManagerWrapper; // If the nav bar should be hidden when the soft keyboard is visible. @@ -83,6 +83,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks CarNavigationBarController carNavigationBarController, WindowManager windowManager, DeviceProvisionedController deviceProvisionedController, + CommandQueue commandQueue, Lazy<FacetButtonTaskStackListener> facetButtonTaskStackListener, @MainHandler Handler mainHandler, Lazy<KeyguardStateController> keyguardStateController, @@ -91,6 +92,7 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks mCarNavigationBarController = carNavigationBarController; mWindowManager = windowManager; mDeviceProvisionedController = deviceProvisionedController; + mCommandQueue = commandQueue; mFacetButtonTaskStackListener = facetButtonTaskStackListener; mMainHandler = mainHandler; mKeyguardStateController = keyguardStateController; @@ -109,7 +111,6 @@ public class CarNavigationBar extends SystemUI implements CommandQueue.Callbacks ServiceManager.getService(Context.STATUS_BAR_SERVICE)); // Connect into the status bar manager service - mCommandQueue = getComponent(CommandQueue.class); mCommandQueue.addCallback(this); RegisterStatusBarResult result = null; 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 new file mode 100644 index 000000000000..b19fae891a58 --- /dev/null +++ b/packages/CarSystemUI/src/com/android/systemui/statusbar/car/CarStatusBarModule.java @@ -0,0 +1,244 @@ +/* + * 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.car; + +import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME; + +import android.content.Context; +import android.os.PowerManager; +import android.util.DisplayMetrics; + +import com.android.internal.logging.MetricsLogger; +import com.android.keyguard.KeyguardUpdateMonitor; +import com.android.systemui.ForegroundServiceController; +import com.android.systemui.UiOffloadThread; +import com.android.systemui.appops.AppOpsController; +import com.android.systemui.assist.AssistManager; +import com.android.systemui.broadcast.BroadcastDispatcher; +import com.android.systemui.bubbles.BubbleController; +import com.android.systemui.colorextraction.SysuiColorExtractor; +import com.android.systemui.doze.DozeLog; +import com.android.systemui.keyguard.KeyguardViewMediator; +import com.android.systemui.keyguard.ScreenLifecycle; +import com.android.systemui.keyguard.WakefulnessLifecycle; +import com.android.systemui.navigationbar.car.CarNavigationBarController; +import com.android.systemui.plugins.FalsingManager; +import com.android.systemui.shared.plugins.PluginManager; +import com.android.systemui.statusbar.CommandQueue; +import com.android.systemui.statusbar.FeatureFlags; +import com.android.systemui.statusbar.NavigationBarController; +import com.android.systemui.statusbar.NotificationListener; +import com.android.systemui.statusbar.NotificationLockscreenUserManager; +import com.android.systemui.statusbar.NotificationMediaManager; +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; +import com.android.systemui.statusbar.notification.DynamicPrivacyController; +import com.android.systemui.statusbar.notification.NewNotifPipeline; +import com.android.systemui.statusbar.notification.NotificationAlertingManager; +import com.android.systemui.statusbar.notification.NotificationEntryManager; +import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider; +import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator; +import com.android.systemui.statusbar.notification.VisualStabilityManager; +import com.android.systemui.statusbar.notification.logging.NotifLog; +import com.android.systemui.statusbar.notification.logging.NotificationLogger; +import com.android.systemui.statusbar.notification.row.NotificationGutsManager; +import com.android.systemui.statusbar.phone.AutoHideController; +import com.android.systemui.statusbar.phone.BiometricUnlockController; +import com.android.systemui.statusbar.phone.DozeParameters; +import com.android.systemui.statusbar.phone.DozeScrimController; +import com.android.systemui.statusbar.phone.DozeServiceHost; +import com.android.systemui.statusbar.phone.HeadsUpManagerPhone; +import com.android.systemui.statusbar.phone.KeyguardBypassController; +import com.android.systemui.statusbar.phone.LightBarController; +import com.android.systemui.statusbar.phone.LockscreenWallpaper; +import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper; +import com.android.systemui.statusbar.phone.NotificationGroupManager; +import com.android.systemui.statusbar.phone.ScrimController; +import com.android.systemui.statusbar.phone.StatusBarIconController; +import com.android.systemui.statusbar.phone.StatusBarWindowController; +import com.android.systemui.statusbar.phone.StatusBarWindowViewController; +import com.android.systemui.statusbar.policy.BatteryController; +import com.android.systemui.statusbar.policy.ConfigurationController; +import com.android.systemui.statusbar.policy.DeviceProvisionedController; +import com.android.systemui.statusbar.policy.KeyguardStateController; +import com.android.systemui.statusbar.policy.NetworkController; +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 javax.inject.Named; +import javax.inject.Singleton; + +import dagger.Lazy; +import dagger.Module; +import dagger.Provides; + +/** + * Dagger Module providing {@link CarStatusBar}. + */ +@Module(includes = {StatusBarDependenciesModule.class}) +public class CarStatusBarModule { + /** + * Provides our instance of StatusBar which is considered optional. + */ + @Provides + @Singleton + static CarStatusBar provideStatusBar( + Context context, + FeatureFlags featureFlags, + LightBarController lightBarController, + AutoHideController autoHideController, + KeyguardUpdateMonitor keyguardUpdateMonitor, + StatusBarIconController statusBarIconController, + DozeLog dozeLog, + PulseExpansionHandler pulseExpansionHandler, + NotificationWakeUpCoordinator notificationWakeUpCoordinator, + KeyguardBypassController keyguardBypassController, + KeyguardStateController keyguardStateController, + HeadsUpManagerPhone headsUpManagerPhone, + DynamicPrivacyController dynamicPrivacyController, + BypassHeadsUpNotifier bypassHeadsUpNotifier, + @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress, + Lazy<NewNotifPipeline> newNotifPipeline, + FalsingManager falsingManager, + BroadcastDispatcher broadcastDispatcher, + RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler, + NotificationGutsManager notificationGutsManager, + NotificationLogger notificationLogger, + NotificationEntryManager notificationEntryManager, + NotificationInterruptionStateProvider notificationInterruptionStateProvider, + NotificationViewHierarchyManager notificationViewHierarchyManager, + ForegroundServiceController foregroundServiceController, + AppOpsController appOpsController, + KeyguardViewMediator keyguardViewMediator, + ZenModeController zenModeController, + NotificationAlertingManager notificationAlertingManager, + DisplayMetrics displayMetrics, + MetricsLogger metricsLogger, + UiOffloadThread uiOffloadThread, + NotificationMediaManager notificationMediaManager, + NotificationLockscreenUserManager lockScreenUserManager, + NotificationRemoteInputManager remoteInputManager, + UserSwitcherController userSwitcherController, + NetworkController networkController, + BatteryController batteryController, + SysuiColorExtractor colorExtractor, + ScreenLifecycle screenLifecycle, + WakefulnessLifecycle wakefulnessLifecycle, + SysuiStatusBarStateController statusBarStateController, + VibratorHelper vibratorHelper, + BubbleController bubbleController, + NotificationGroupManager groupManager, + NotificationGroupAlertTransferHelper groupAlertTransferHelper, + VisualStabilityManager visualStabilityManager, + DeviceProvisionedController deviceProvisionedController, + NavigationBarController navigationBarController, + AssistManager assistManager, + NotificationListener notificationListener, + ConfigurationController configurationController, + StatusBarWindowController statusBarWindowController, + StatusBarWindowViewController.Builder statusBarWindowViewControllerBuilder, + NotifLog notifLog, + DozeParameters dozeParameters, + ScrimController scrimController, + Lazy<LockscreenWallpaper> lockscreenWallpaperLazy, + Lazy<BiometricUnlockController> biometricUnlockControllerLazy, + DozeServiceHost dozeServiceHost, + PowerManager powerManager, + DozeScrimController dozeScrimController, + CommandQueue commandQueue, + PluginManager pluginManager, + RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory, + CarNavigationBarController carNavigationBarController) { + return new CarStatusBar( + context, + featureFlags, + lightBarController, + autoHideController, + keyguardUpdateMonitor, + statusBarIconController, + dozeLog, + pulseExpansionHandler, + notificationWakeUpCoordinator, + keyguardBypassController, + keyguardStateController, + headsUpManagerPhone, + dynamicPrivacyController, + bypassHeadsUpNotifier, + allowNotificationLongPress, + newNotifPipeline, + falsingManager, + broadcastDispatcher, + remoteInputQuickSettingsDisabler, + notificationGutsManager, + notificationLogger, + notificationEntryManager, + notificationInterruptionStateProvider, + notificationViewHierarchyManager, + foregroundServiceController, + appOpsController, + keyguardViewMediator, + zenModeController, + notificationAlertingManager, + displayMetrics, + metricsLogger, + uiOffloadThread, + notificationMediaManager, + lockScreenUserManager, + remoteInputManager, + userSwitcherController, + networkController, + batteryController, + colorExtractor, + screenLifecycle, + wakefulnessLifecycle, + statusBarStateController, + vibratorHelper, + bubbleController, + groupManager, + groupAlertTransferHelper, + visualStabilityManager, + deviceProvisionedController, + navigationBarController, + assistManager, + notificationListener, + configurationController, + statusBarWindowController, + statusBarWindowViewControllerBuilder, + notifLog, + dozeParameters, + scrimController, + lockscreenWallpaperLazy, + biometricUnlockControllerLazy, + dozeServiceHost, + powerManager, + dozeScrimController, + 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/res/values/dimens.xml b/packages/SystemUI/res/values/dimens.xml index 14371fe4b41b..64b2892efc9a 100644 --- a/packages/SystemUI/res/values/dimens.xml +++ b/packages/SystemUI/res/values/dimens.xml @@ -1120,8 +1120,6 @@ <dimen name="bubble_touch_padding">12dp</dimen> <!-- Size of the circle around the bubbles when they're in the dismiss target. --> <dimen name="bubble_dismiss_encircle_size">52dp</dimen> - <!-- How much to inset the icon in the circle --> - <dimen name="bubble_icon_inset">16dp</dimen> <!-- Padding around the view displayed when the bubble is expanded --> <dimen name="bubble_expanded_view_padding">4dp</dimen> <!-- This should be at least the size of bubble_expanded_view_padding; it is used to include diff --git a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java index 074ef53aa57c..acce41cc942e 100644 --- a/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java +++ b/packages/SystemUI/shared/src/com/android/systemui/shared/system/TaskStackChangeListeners.java @@ -56,7 +56,9 @@ public class TaskStackChangeListeners extends TaskStackListener { } public void addListener(IActivityManager am, TaskStackChangeListener listener) { - mTaskStackListeners.add(listener); + synchronized (mTaskStackListeners) { + mTaskStackListeners.add(listener); + } if (!mRegistered) { // Register mTaskStackListener to IActivityManager only once if needed. try { @@ -69,8 +71,12 @@ public class TaskStackChangeListeners extends TaskStackListener { } public void removeListener(TaskStackChangeListener listener) { - mTaskStackListeners.remove(listener); - if (mTaskStackListeners.isEmpty() && mRegistered) { + boolean isEmpty; + synchronized (mTaskStackListeners) { + mTaskStackListeners.remove(listener); + isEmpty = mTaskStackListeners.isEmpty(); + } + if (isEmpty && mRegistered) { // Unregister mTaskStackListener once we have no more listeners try { ActivityTaskManager.getService().unregisterTaskStackListener(this); @@ -83,14 +89,17 @@ public class TaskStackChangeListeners extends TaskStackListener { @Override public void onTaskStackChanged() throws RemoteException { - // Call the task changed callback for the non-ui thread listeners first + // Call the task changed callback for the non-ui thread listeners first. Copy to a set of + // temp listeners so that we don't lock on mTaskStackListeners while calling all the + // callbacks. This call is always on the same binder thread, so we can just synchronize + // on the copying of the listener list. synchronized (mTaskStackListeners) { - mTmpListeners.clear(); mTmpListeners.addAll(mTaskStackListeners); } for (int i = mTmpListeners.size() - 1; i >= 0; i--) { mTmpListeners.get(i).onTaskStackChangedBackground(); } + mTmpListeners.clear(); mHandler.removeMessages(H.ON_TASK_STACK_CHANGED); mHandler.sendEmptyMessage(H.ON_TASK_STACK_CHANGED); diff --git a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java index 46b4c6b7d44c..21b52c1e5b57 100644 --- a/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java +++ b/packages/SystemUI/src/com/android/keyguard/CarrierTextController.java @@ -169,12 +169,15 @@ public class CarrierTextController { mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); mSeparator = separator; mWakefulnessLifecycle = Dependency.get(WakefulnessLifecycle.class); - mSimSlotsNumber = ((TelephonyManager) context.getSystemService( - Context.TELEPHONY_SERVICE)).getSupportedModemCount(); + mSimSlotsNumber = getTelephonyManager().getSupportedModemCount(); mSimErrorState = new boolean[mSimSlotsNumber]; mMainHandler = Dependency.get(Dependency.MAIN_HANDLER); } + private TelephonyManager getTelephonyManager() { + return (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); + } + /** * Checks if there are faulty cards. Adds the text depending on the slot of the card * @@ -190,7 +193,7 @@ public class CarrierTextController { CharSequence carrierTextForSimIOError = getCarrierTextForSimState( IccCardConstants.State.CARD_IO_ERROR, carrier); // mSimErrorState has the state of each sim indexed by slotID. - for (int index = 0; index < mSimErrorState.length; index++) { + for (int index = 0; index < getTelephonyManager().getActiveModemCount(); index++) { if (!mSimErrorState[index]) { continue; } @@ -223,8 +226,7 @@ public class CarrierTextController { * @param callback Callback to provide text updates */ public void setListening(CarrierTextCallback callback) { - TelephonyManager telephonyManager = ((TelephonyManager) mContext - .getSystemService(Context.TELEPHONY_SERVICE)); + TelephonyManager telephonyManager = getTelephonyManager(); if (callback != null) { mCarrierTextCallback = callback; // TODO(b/140034799) diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinView.java index 9c0a71c1f81d..b1502b9a0d63 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinView.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPinView.java @@ -104,7 +104,12 @@ public class KeyguardSimPinView extends KeyguardPinBasedInputView { private void setLockedSimMessage() { boolean isEsimLocked = KeyguardEsimArea.isEsimLocked(mContext, mSubId); - int count = TelephonyManager.getDefault().getSimCount(); + int count = 1; + TelephonyManager telephonyManager = + (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); + if (telephonyManager != null) { + count = telephonyManager.getActiveModemCount(); + } Resources rez = getResources(); String msg; TypedArray array = mContext.obtainStyledAttributes(new int[] { R.attr.wallpaperTextColor }); diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukView.java b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukView.java index fc888e11d3f5..70237a053e1e 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukView.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardSimPukView.java @@ -164,7 +164,12 @@ public class KeyguardSimPukView extends KeyguardPinBasedInputView { } boolean isEsimLocked = KeyguardEsimArea.isEsimLocked(mContext, mSubId); - int count = TelephonyManager.getDefault().getSimCount(); + int count = 1; + TelephonyManager telephonyManager = + (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); + if (telephonyManager != null) { + count = telephonyManager.getActiveModemCount(); + } Resources rez = getResources(); String msg; TypedArray array = mContext.obtainStyledAttributes(new int[] { R.attr.wallpaperTextColor }); diff --git a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java index 6685db130d4a..0b0922a7766f 100644 --- a/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java +++ b/packages/SystemUI/src/com/android/keyguard/KeyguardUpdateMonitor.java @@ -2649,8 +2649,10 @@ public class KeyguardUpdateMonitor implements TrustManager.TrustListener, Dumpab // that don't return the complete set of values and have different types. In Keyguard we // need IccCardConstants, but TelephonyManager would only give us // TelephonyManager.SIM_STATE*, so we retrieve it manually. - final TelephonyManager tele = TelephonyManager.from(mContext); - int simState = tele.getSimState(slotId); + final TelephonyManager tele = + (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); + int simState = (tele != null) ? + tele.getSimState(slotId) : TelephonyManager.SIM_STATE_UNKNOWN; State state; try { state = State.intToState(simState); diff --git a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java index a94952c5bc19..8e472f9c98a3 100644 --- a/packages/SystemUI/src/com/android/systemui/CornerHandleView.java +++ b/packages/SystemUI/src/com/android/systemui/CornerHandleView.java @@ -47,6 +47,7 @@ public class CornerHandleView extends View { private int mLightColor; private int mDarkColor; private Path mPath; + private boolean mRequiresInvalidate; public CornerHandleView(Context context, AttributeSet attrs) { super(context, attrs); @@ -67,6 +68,15 @@ public class CornerHandleView extends View { updatePath(); } + @Override + public void setAlpha(float alpha) { + super.setAlpha(alpha); + if (alpha > 0f && mRequiresInvalidate) { + mRequiresInvalidate = false; + invalidate(); + } + } + private void updatePath() { mPath = new Path(); @@ -104,11 +114,16 @@ public class CornerHandleView extends View { * appropriately. Intention is to match the home handle color. */ public void updateDarkness(float darkIntensity) { - mPaint.setColor((int) ArgbEvaluator.getInstance().evaluate(darkIntensity, - mLightColor, - mDarkColor)); - if (getVisibility() == VISIBLE) { - invalidate(); + int color = (int) ArgbEvaluator.getInstance().evaluate(darkIntensity, + mLightColor, mDarkColor); + if (mPaint.getColor() != color) { + mPaint.setColor(color); + if (getVisibility() == VISIBLE && getAlpha() > 0) { + invalidate(); + } else { + // If we are currently invisible, then invalidate when we are next made visible + mRequiresInvalidate = true; + } } } diff --git a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleReminderExpBehavior.java b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleReminderExpBehavior.java index 9a277e8fa77c..46ae84a95fad 100644 --- a/packages/SystemUI/src/com/android/systemui/assist/AssistHandleReminderExpBehavior.java +++ b/packages/SystemUI/src/com/android/systemui/assist/AssistHandleReminderExpBehavior.java @@ -249,7 +249,7 @@ final class AssistHandleReminderExpBehavior implements BehaviorController { public void onModeDeactivated() { mAssistHandleCallbacks = null; if (mContext != null) { - mContext.unregisterReceiver(mDefaultHomeBroadcastReceiver); + mBroadcastDispatcher.get().unregisterReceiver(mDefaultHomeBroadcastReceiver); Settings.Secure.putLong(mContext.getContentResolver(), LEARNING_TIME_ELAPSED_KEY, 0); Settings.Secure.putInt(mContext.getContentResolver(), LEARNING_EVENT_COUNT_KEY, 0); Settings.Secure.putLong(mContext.getContentResolver(), LEARNED_HINT_LAST_SHOWN_KEY, 0); diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java b/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java index baa3a4a938c1..c641943278d4 100644 --- a/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java +++ b/packages/SystemUI/src/com/android/systemui/assist/ui/EdgeLight.java @@ -67,8 +67,10 @@ public final class EdgeLight { } /** Sets the edge light color. */ - public void setColor(@ColorInt int color) { + public boolean setColor(@ColorInt int color) { + boolean changed = mColor != color; mColor = color; + return changed; } /** Returns the edge light length, in units of the total device perimeter. */ diff --git a/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java b/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java index 570b911cd400..e5121a8ea35c 100644 --- a/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java +++ b/packages/SystemUI/src/com/android/systemui/assist/ui/InvocationLightsView.java @@ -259,10 +259,13 @@ public class InvocationLightsView extends View if (mUseNavBarColor) { @ColorInt int invocationColor = (int) ArgbEvaluator.getInstance().evaluate( darkIntensity, mLightColor, mDarkColor); + boolean changed = true; for (EdgeLight light : mAssistInvocationLights) { - light.setColor(invocationColor); + changed &= light.setColor(invocationColor); + } + if (changed) { + invalidate(); } - invalidate(); } } 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/bubbles/Bubble.java b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java index 7600b2f3ed7a..f8e45d4c8b63 100644 --- a/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java +++ b/packages/SystemUI/src/com/android/systemui/bubbles/Bubble.java @@ -134,6 +134,10 @@ class Bubble { return mAppName; } + public Drawable getUserBadgedAppIcon() { + return mUserBadgedAppIcon; + } + boolean isInflated() { return mInflated; } @@ -165,7 +169,6 @@ class Bubble { mIconView = (BubbleView) inflater.inflate( R.layout.bubble_view, stackView, false /* attachToRoot */); mIconView.setBubble(this); - mIconView.setAppIcon(mUserBadgedAppIcon); mExpandedView = (BubbleExpandedView) inflater.inflate( R.layout.bubble_expanded_view, stackView, false /* attachToRoot */); diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java index e5af3897dff2..4a1bbe48efb0 100644 --- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java +++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleStackView.java @@ -1459,7 +1459,7 @@ public class BubbleStackView extends FrameLayout { mFlyout.setupFlyoutStartingAsDot( updateMessage, mStackAnimationController.getStackPosition(), getWidth(), mStackAnimationController.isStackOnLeftSide(), - bubble.getIconView().getBadgeColor() /* dotColor */, + bubble.getIconView().getDotColor() /* dotColor */, expandFlyoutAfterDelay /* onLayoutComplete */, mFlyoutOnHide, bubble.getIconView().getDotCenter()); diff --git a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java index fe4fa90a272d..35657d38df0c 100644 --- a/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java +++ b/packages/SystemUI/src/com/android/systemui/bubbles/BubbleView.java @@ -24,17 +24,16 @@ import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.graphics.Path; -import android.graphics.drawable.AdaptiveIconDrawable; import android.graphics.drawable.BitmapDrawable; -import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.graphics.drawable.Icon; -import android.graphics.drawable.InsetDrawable; import android.util.AttributeSet; import android.util.PathParser; import android.widget.FrameLayout; import com.android.internal.graphics.ColorUtils; +import com.android.launcher3.icons.BitmapInfo; +import com.android.launcher3.icons.ColorExtractor; import com.android.launcher3.icons.ShadowGenerator; import com.android.systemui.Interpolators; import com.android.systemui.R; @@ -45,17 +44,13 @@ import com.android.systemui.statusbar.notification.collection.NotificationEntry; */ public class BubbleView extends FrameLayout { - private static final int DARK_ICON_ALPHA = 180; - private static final double ICON_MIN_CONTRAST = 4.1; - private static final int DEFAULT_BACKGROUND_COLOR = Color.LTGRAY; // Same value as Launcher3 badge code private static final float WHITE_SCRIM_ALPHA = 0.54f; private Context mContext; private BadgedImageView mBadgedImageView; - private int mBadgeColor; - private int mIconInset; - private Drawable mUserBadgedAppIcon; + private int mDotColor; + private ColorExtractor mColorExtractor; // mBubbleIconFactory cannot be static because it depends on Context. private BubbleIconFactory mBubbleIconFactory; @@ -79,13 +74,13 @@ public class BubbleView extends FrameLayout { public BubbleView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); mContext = context; - mIconInset = getResources().getDimensionPixelSize(R.dimen.bubble_icon_inset); } @Override protected void onFinishInflate() { super.onFinishInflate(); mBadgedImageView = findViewById(R.id.bubble_image); + mColorExtractor = new ColorExtractor(); } @Override @@ -106,6 +101,13 @@ public class BubbleView extends FrameLayout { } /** + * @param factory Factory for creating normalized bubble icons. + */ + public void setBubbleIconFactory(BubbleIconFactory factory) { + mBubbleIconFactory = factory; + } + + /** * The {@link NotificationEntry} associated with this view, if one exists. */ @Nullable @@ -129,17 +131,6 @@ public class BubbleView extends FrameLayout { updateViews(); } - /** - * @param factory Factory for creating normalized bubble icons. - */ - public void setBubbleIconFactory(BubbleIconFactory factory) { - mBubbleIconFactory = factory; - } - - public void setAppIcon(Drawable appIcon) { - mUserBadgedAppIcon = appIcon; - } - /** Changes the dot's visibility to match the bubble view's state. */ void updateDotVisibility(boolean animate) { updateDotVisibility(animate, null /* after */); @@ -154,9 +145,17 @@ public class BubbleView extends FrameLayout { updateDotVisibility(animate); } + boolean isDotShowing() { + return mBubble.showBubbleDot() && !mSuppressDot; + } + + int getDotColor() { + return mDotColor; + } + /** Sets the position of the 'new' dot, animating it out and back in if requested. */ void setDotPosition(boolean onLeft, boolean animate) { - if (animate && onLeft != mBadgedImageView.getDotOnLeft() && shouldShowDot()) { + if (animate && onLeft != mBadgedImageView.getDotOnLeft() && isDotShowing()) { animateDot(false /* showDot */, () -> { mBadgedImageView.setDotOnLeft(onLeft); animateDot(true /* showDot */, null); @@ -180,7 +179,7 @@ public class BubbleView extends FrameLayout { * after animation if requested. */ private void updateDotVisibility(boolean animate, Runnable after) { - final boolean showDot = shouldShowDot(); + final boolean showDot = isDotShowing(); if (animate) { animateDot(showDot, after); } else { @@ -218,42 +217,21 @@ public class BubbleView extends FrameLayout { if (mBubble == null || mBubbleIconFactory == null) { return; } - // Update icon. - Notification.BubbleMetadata metadata = mBubble.getEntry().getBubbleMetadata(); - Notification n = mBubble.getEntry().getSbn().getNotification(); - Icon ic = metadata.getIcon(); - boolean needsTint = ic.getType() != Icon.TYPE_ADAPTIVE_BITMAP; - - Drawable iconDrawable = ic.loadDrawable(mContext); - if (needsTint) { - iconDrawable = buildIconWithTint(iconDrawable, n.color); - } - Bitmap bubbleIcon = mBubbleIconFactory.createBadgedIconBitmap(iconDrawable, - null /* user */, - true /* shrinkNonAdaptiveIcons */).icon; - - // Give it a shadow - Bitmap userBadgedBitmap = mBubbleIconFactory.createIconBitmap(mUserBadgedAppIcon, - 1f, mBubbleIconFactory.getBadgeSize()); - Canvas c = new Canvas(); - ShadowGenerator shadowGenerator = new ShadowGenerator(mBubbleIconFactory.getBadgeSize()); - c.setBitmap(userBadgedBitmap); - shadowGenerator.recreateIcon(Bitmap.createBitmap(userBadgedBitmap), c); - mBubbleIconFactory.badgeWithDrawable(bubbleIcon, - new BitmapDrawable(mContext.getResources(), userBadgedBitmap)); - mBadgedImageView.setImageBitmap(bubbleIcon); + Drawable bubbleDrawable = getBubbleDrawable(mContext); + BitmapInfo badgeBitmapInfo = getBadgedBitmap(); + BitmapInfo bubbleBitmapInfo = getBubbleBitmap(bubbleDrawable, badgeBitmapInfo); + mBadgedImageView.setImageBitmap(bubbleBitmapInfo.icon); // Update badge. - int badgeColor = determineDominateColor(iconDrawable, n.color); - mBadgeColor = badgeColor; - mBadgedImageView.setDotColor(badgeColor); + mDotColor = ColorUtils.blendARGB(badgeBitmapInfo.color, Color.WHITE, WHITE_SCRIM_ALPHA); + mBadgedImageView.setDotColor(mDotColor); // Update dot. Path iconPath = PathParser.createPathFromPathData( getResources().getString(com.android.internal.R.string.config_icon_mask)); Matrix matrix = new Matrix(); - float scale = mBubbleIconFactory.getNormalizer().getScale(iconDrawable, + float scale = mBubbleIconFactory.getNormalizer().getScale(bubbleDrawable, null /* outBounds */, null /* path */, null /* outMaskShape */); float radius = BadgedImageView.DEFAULT_PATH_SIZE / 2f; matrix.setScale(scale /* x scale */, scale /* y scale */, radius /* pivot x */, @@ -261,41 +239,34 @@ public class BubbleView extends FrameLayout { iconPath.transform(matrix); mBadgedImageView.drawDot(iconPath); - animateDot(shouldShowDot(), null /* after */); + animateDot(isDotShowing(), null /* after */); } - boolean shouldShowDot() { - return mBubble.showBubbleDot() && !mSuppressDot; + Drawable getBubbleDrawable(Context context) { + Notification.BubbleMetadata metadata = getEntry().getBubbleMetadata(); + Icon ic = metadata.getIcon(); + return ic.loadDrawable(context); } - int getBadgeColor() { - return mBadgeColor; - } + BitmapInfo getBadgedBitmap() { + Bitmap userBadgedBitmap = mBubbleIconFactory.createIconBitmap( + mBubble.getUserBadgedAppIcon(), 1f, mBubbleIconFactory.getBadgeSize()); - private AdaptiveIconDrawable buildIconWithTint(Drawable iconDrawable, int backgroundColor) { - iconDrawable = checkTint(iconDrawable, backgroundColor); - InsetDrawable foreground = new InsetDrawable(iconDrawable, mIconInset); - ColorDrawable background = new ColorDrawable(backgroundColor); - return new AdaptiveIconDrawable(background, foreground); + Canvas c = new Canvas(); + ShadowGenerator shadowGenerator = new ShadowGenerator(mBubbleIconFactory.getBadgeSize()); + c.setBitmap(userBadgedBitmap); + shadowGenerator.recreateIcon(Bitmap.createBitmap(userBadgedBitmap), c); + BitmapInfo bitmapInfo = mBubbleIconFactory.createIconBitmap(userBadgedBitmap); + return bitmapInfo; } - private Drawable checkTint(Drawable iconDrawable, int backgroundColor) { - backgroundColor = ColorUtils.setAlphaComponent(backgroundColor, 255 /* alpha */); - if (backgroundColor == Color.TRANSPARENT) { - // ColorUtils throws exception when background is translucent. - backgroundColor = DEFAULT_BACKGROUND_COLOR; - } - iconDrawable.setTint(Color.WHITE); - double contrastRatio = ColorUtils.calculateContrast(Color.WHITE, backgroundColor); - if (contrastRatio < ICON_MIN_CONTRAST) { - int dark = ColorUtils.setAlphaComponent(Color.BLACK, DARK_ICON_ALPHA); - iconDrawable.setTint(dark); - } - return iconDrawable; - } + BitmapInfo getBubbleBitmap(Drawable bubble, BitmapInfo badge) { + BitmapInfo bubbleIconInfo = mBubbleIconFactory.createBadgedIconBitmap(bubble, + null /* user */, + true /* shrinkNonAdaptiveIcons */); - private int determineDominateColor(Drawable d, int defaultTint) { - // XXX: should we pull from the drawable, app icon, notif tint? - return ColorUtils.blendARGB(defaultTint, Color.WHITE, WHITE_SCRIM_ALPHA); + mBubbleIconFactory.badgeWithDrawable(bubbleIconInfo.icon, + new BitmapDrawable(mContext.getResources(), badge.icon)); + return bubbleIconInfo; } } diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java index 3b0c9aebfe08..9f5493720bef 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIBinder.java @@ -16,109 +16,35 @@ package com.android.systemui.dagger; -import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME; - -import android.content.Context; -import android.os.PowerManager; -import android.util.DisplayMetrics; - -import androidx.annotation.Nullable; - -import com.android.internal.logging.MetricsLogger; -import com.android.keyguard.KeyguardUpdateMonitor; -import com.android.systemui.ForegroundServiceController; import com.android.systemui.LatencyTester; import com.android.systemui.ScreenDecorations; import com.android.systemui.SizeCompatModeActivityController; import com.android.systemui.SliceBroadcastRelayHandler; import com.android.systemui.SystemUI; -import com.android.systemui.UiOffloadThread; -import com.android.systemui.appops.AppOpsController; -import com.android.systemui.assist.AssistManager; import com.android.systemui.biometrics.AuthController; -import com.android.systemui.broadcast.BroadcastDispatcher; -import com.android.systemui.bubbles.BubbleController; -import com.android.systemui.colorextraction.SysuiColorExtractor; -import com.android.systemui.doze.DozeLog; import com.android.systemui.globalactions.GlobalActionsComponent; import com.android.systemui.keyguard.KeyguardViewMediator; -import com.android.systemui.keyguard.ScreenLifecycle; -import com.android.systemui.keyguard.WakefulnessLifecycle; import com.android.systemui.pip.PipUI; -import com.android.systemui.plugins.FalsingManager; import com.android.systemui.power.PowerUI; import com.android.systemui.recents.Recents; import com.android.systemui.recents.RecentsModule; -import com.android.systemui.shared.plugins.PluginManager; -import com.android.systemui.statusbar.CommandQueue; -import com.android.systemui.statusbar.FeatureFlags; -import com.android.systemui.statusbar.NavigationBarController; -import com.android.systemui.statusbar.NotificationListener; -import com.android.systemui.statusbar.NotificationLockscreenUserManager; -import com.android.systemui.statusbar.NotificationMediaManager; -import com.android.systemui.statusbar.NotificationRemoteInputManager; -import com.android.systemui.statusbar.NotificationViewHierarchyManager; -import com.android.systemui.statusbar.PulseExpansionHandler; -import com.android.systemui.statusbar.SysuiStatusBarStateController; -import com.android.systemui.statusbar.VibratorHelper; -import com.android.systemui.statusbar.notification.BypassHeadsUpNotifier; -import com.android.systemui.statusbar.notification.DynamicPrivacyController; import com.android.systemui.statusbar.notification.InstantAppNotifier; -import com.android.systemui.statusbar.notification.NewNotifPipeline; -import com.android.systemui.statusbar.notification.NotificationAlertingManager; -import com.android.systemui.statusbar.notification.NotificationEntryManager; -import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider; -import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator; -import com.android.systemui.statusbar.notification.VisualStabilityManager; -import com.android.systemui.statusbar.notification.logging.NotifLog; -import com.android.systemui.statusbar.notification.logging.NotificationLogger; -import com.android.systemui.statusbar.notification.row.NotificationGutsManager; -import com.android.systemui.statusbar.phone.AutoHideController; -import com.android.systemui.statusbar.phone.BiometricUnlockController; -import com.android.systemui.statusbar.phone.DozeParameters; -import com.android.systemui.statusbar.phone.DozeScrimController; -import com.android.systemui.statusbar.phone.DozeServiceHost; -import com.android.systemui.statusbar.phone.HeadsUpManagerPhone; -import com.android.systemui.statusbar.phone.KeyguardBypassController; -import com.android.systemui.statusbar.phone.KeyguardLiftController; -import com.android.systemui.statusbar.phone.LightBarController; -import com.android.systemui.statusbar.phone.LockscreenWallpaper; -import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper; -import com.android.systemui.statusbar.phone.NotificationGroupManager; -import com.android.systemui.statusbar.phone.ScrimController; import com.android.systemui.statusbar.phone.StatusBar; -import com.android.systemui.statusbar.phone.StatusBarIconController; -import com.android.systemui.statusbar.phone.StatusBarWindowController; -import com.android.systemui.statusbar.phone.StatusBarWindowViewController; -import com.android.systemui.statusbar.policy.BatteryController; -import com.android.systemui.statusbar.policy.ConfigurationController; -import com.android.systemui.statusbar.policy.DeviceProvisionedController; -import com.android.systemui.statusbar.policy.KeyguardStateController; -import com.android.systemui.statusbar.policy.NetworkController; -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.statusbar.phone.StatusBarModule; import com.android.systemui.statusbar.tv.TvStatusBar; import com.android.systemui.theme.ThemeOverlayController; -import com.android.systemui.util.InjectionInflationController; import com.android.systemui.util.leak.GarbageMonitor; import com.android.systemui.volume.VolumeUI; -import javax.inject.Named; -import javax.inject.Singleton; - import dagger.Binds; -import dagger.Lazy; import dagger.Module; -import dagger.Provides; import dagger.multibindings.ClassKey; import dagger.multibindings.IntoMap; /** * SystemUI objects that are injectable should go here. */ -@Module(includes = {RecentsModule.class}) +@Module(includes = {RecentsModule.class, StatusBarModule.class}) public abstract class SystemUIBinder { /** Inject into AuthController. */ @Binds @@ -216,148 +142,4 @@ public abstract class SystemUIBinder { @IntoMap @ClassKey(VolumeUI.class) public abstract SystemUI bindVolumeUI(VolumeUI sysui); - - /** - * Provides our instance of StatusBar which is considered optional. - */ - @Provides - @Singleton - static StatusBar provideStatusBar( - Context context, - FeatureFlags featureFlags, - LightBarController lightBarController, - AutoHideController autoHideController, - KeyguardUpdateMonitor keyguardUpdateMonitor, - StatusBarIconController statusBarIconController, - DozeLog dozeLog, - InjectionInflationController injectionInflationController, - PulseExpansionHandler pulseExpansionHandler, - NotificationWakeUpCoordinator notificationWakeUpCoordinator, - KeyguardBypassController keyguardBypassController, - KeyguardStateController keyguardStateController, - HeadsUpManagerPhone headsUpManagerPhone, - DynamicPrivacyController dynamicPrivacyController, - BypassHeadsUpNotifier bypassHeadsUpNotifier, - @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress, - Lazy<NewNotifPipeline> newNotifPipeline, - FalsingManager falsingManager, - BroadcastDispatcher broadcastDispatcher, - RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler, - NotificationGutsManager notificationGutsManager, - NotificationLogger notificationLogger, - NotificationEntryManager notificationEntryManager, - NotificationInterruptionStateProvider notificationInterruptionStateProvider, - NotificationViewHierarchyManager notificationViewHierarchyManager, - ForegroundServiceController foregroundServiceController, - AppOpsController appOpsController, - KeyguardViewMediator keyguardViewMediator, - ZenModeController zenModeController, - NotificationAlertingManager notificationAlertingManager, - DisplayMetrics displayMetrics, - MetricsLogger metricsLogger, - UiOffloadThread uiOffloadThread, - NotificationMediaManager notificationMediaManager, - NotificationLockscreenUserManager lockScreenUserManager, - NotificationRemoteInputManager remoteInputManager, - UserSwitcherController userSwitcherController, - NetworkController networkController, - BatteryController batteryController, - SysuiColorExtractor colorExtractor, - ScreenLifecycle screenLifecycle, - WakefulnessLifecycle wakefulnessLifecycle, - SysuiStatusBarStateController statusBarStateController, - VibratorHelper vibratorHelper, - BubbleController bubbleController, - NotificationGroupManager groupManager, - NotificationGroupAlertTransferHelper groupAlertTransferHelper, - VisualStabilityManager visualStabilityManager, - DeviceProvisionedController deviceProvisionedController, - NavigationBarController navigationBarController, - AssistManager assistManager, - NotificationListener notificationListener, - ConfigurationController configurationController, - StatusBarWindowController statusBarWindowController, - StatusBarWindowViewController.Builder statusBarWindowViewControllerBuilder, - NotifLog notifLog, - DozeParameters dozeParameters, - ScrimController scrimController, - @Nullable KeyguardLiftController keyguardLiftController, - Lazy<LockscreenWallpaper> lockscreenWallpaperLazy, - Lazy<BiometricUnlockController> biometricUnlockControllerLazy, - DozeServiceHost dozeServiceHost, - PowerManager powerManager, - DozeScrimController dozeScrimController, - CommandQueue commandQueue, - PluginManager pluginManager, - RemoteInputUriController remoteInputUriController) { - return new StatusBar( - context, - featureFlags, - lightBarController, - autoHideController, - keyguardUpdateMonitor, - statusBarIconController, - dozeLog, - injectionInflationController, - pulseExpansionHandler, - notificationWakeUpCoordinator, - keyguardBypassController, - keyguardStateController, - headsUpManagerPhone, - dynamicPrivacyController, - bypassHeadsUpNotifier, - allowNotificationLongPress, - newNotifPipeline, - falsingManager, - broadcastDispatcher, - remoteInputQuickSettingsDisabler, - notificationGutsManager, - notificationLogger, - notificationEntryManager, - notificationInterruptionStateProvider, - notificationViewHierarchyManager, - foregroundServiceController, - appOpsController, - keyguardViewMediator, - zenModeController, - notificationAlertingManager, - displayMetrics, - metricsLogger, - uiOffloadThread, - notificationMediaManager, - lockScreenUserManager, - remoteInputManager, - userSwitcherController, - networkController, - batteryController, - colorExtractor, - screenLifecycle, - wakefulnessLifecycle, - statusBarStateController, - vibratorHelper, - bubbleController, - groupManager, - groupAlertTransferHelper, - visualStabilityManager, - deviceProvisionedController, - navigationBarController, - assistManager, - notificationListener, - configurationController, - statusBarWindowController, - statusBarWindowViewControllerBuilder, - notifLog, - dozeParameters, - scrimController, - keyguardLiftController, - lockscreenWallpaperLazy, - biometricUnlockControllerLazy, - dozeServiceHost, - powerManager, - dozeScrimController, - commandQueue, - pluginManager, - remoteInputUriController); - } - } diff --git a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java index 9e7f6c683bbe..b3a5181d1ca5 100644 --- a/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java +++ b/packages/SystemUI/src/com/android/systemui/dagger/SystemUIModule.java @@ -25,6 +25,7 @@ import com.android.systemui.DumpController; import com.android.systemui.assist.AssistModule; import com.android.systemui.model.SysUiState; import com.android.systemui.plugins.statusbar.StatusBarStateController; +import com.android.systemui.statusbar.CommandQueue; import com.android.systemui.statusbar.notification.people.PeopleHubModule; import com.android.systemui.statusbar.phone.KeyguardLiftController; import com.android.systemui.statusbar.phone.StatusBar; @@ -71,5 +72,8 @@ public abstract class SystemUIModule { } @BindsOptionalOf + abstract CommandQueue optionalCommandQueue(); + + @BindsOptionalOf abstract StatusBar optionalStatusBar(); } diff --git a/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivity.java b/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivity.java index 86c532cdb773..b1df578c62df 100644 --- a/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivity.java +++ b/packages/SystemUI/src/com/android/systemui/keyguard/WorkLockActivity.java @@ -117,9 +117,14 @@ public class WorkLockActivity extends Activity { } } + @VisibleForTesting + protected void unregisterBroadcastReceiver() { + mBroadcastDispatcher.unregisterReceiver(mLockEventReceiver); + } + @Override public void onDestroy() { - unregisterReceiver(mLockEventReceiver); + unregisterBroadcastReceiver(); super.onDestroy(); } 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/CommandQueue.java b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java index eb6ea13a6690..b723b752548b 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/CommandQueue.java @@ -50,8 +50,6 @@ import android.view.InsetsState.InternalInsetType; import android.view.View; import android.view.WindowInsetsController.Appearance; -import androidx.annotation.VisibleForTesting; - import com.android.internal.os.SomeArgs; import com.android.internal.statusbar.IStatusBar; import com.android.internal.statusbar.StatusBarIcon; @@ -61,9 +59,6 @@ import com.android.systemui.statusbar.policy.CallbackController; import java.util.ArrayList; -import javax.inject.Inject; -import javax.inject.Singleton; - /** * This class takes the functions from IStatusBar that come in on * binder pool threads and posts messages to get them onto the main @@ -71,7 +66,6 @@ import javax.inject.Singleton; * coalescing these calls so they don't stack up. For the calls * are coalesced, note that they are all idempotent. */ -@Singleton public class CommandQueue extends IStatusBar.Stub implements CallbackController<Callbacks>, DisplayManager.DisplayListener { private static final int INDEX_MASK = 0xffff; @@ -307,8 +301,6 @@ public class CommandQueue extends IStatusBar.Stub implements CallbackController< } } - @VisibleForTesting - @Inject public CommandQueue(Context context) { context.getSystemService(DisplayManager.class).registerDisplayListener(this, mHandler); // We always have default display. diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarDependenciesModule.java b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarDependenciesModule.java new file mode 100644 index 000000000000..48f02cc147db --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/StatusBarDependenciesModule.java @@ -0,0 +1,37 @@ +/* + * 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 dagger.Module; +import dagger.Provides; + +/** + * Dagger Module providing common dependencies of StatusBar. + */ +@Module +public class StatusBarDependenciesModule { + /** + * Provides our instance of CommandQueue which is considered optional. + */ + @Provides + public CommandQueue provideCommandQueue(Context context) { + return new CommandQueue(context); + } + +} 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/notification/collection/NotificationData.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java index 9981c93431e7..a0229d16d6eb 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationData.java @@ -68,7 +68,6 @@ public class NotificationData { private final ArrayMap<String, NotificationEntry> mEntries = new ArrayMap<>(); private final ArrayList<NotificationEntry> mSortedAndFiltered = new ArrayList<>(); - private final ArrayList<NotificationEntry> mFilteredForUser = new ArrayList<>(); private final NotificationGroupManager mGroupManager = Dependency.get(NotificationGroupManager.class); @@ -166,20 +165,20 @@ public class NotificationData { } public ArrayList<NotificationEntry> getNotificationsForCurrentUser() { - mFilteredForUser.clear(); - synchronized (mEntries) { final int len = mEntries.size(); + ArrayList<NotificationEntry> filteredForUser = new ArrayList<>(len); + for (int i = 0; i < len; i++) { NotificationEntry entry = mEntries.valueAt(i); final StatusBarNotification sbn = entry.getSbn(); if (!getEnvironment().isNotificationForCurrentProfiles(sbn)) { continue; } - mFilteredForUser.add(entry); + filteredForUser.add(entry); } + return filteredForUser; } - return mFilteredForUser; } public NotificationEntry get(String key) { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java index 396c5fefd8b7..0ef75165f54f 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/collection/NotificationRowBinderImpl.java @@ -142,6 +142,7 @@ public class NotificationRowBinderImpl implements NotificationRowBinder { entry.updateIcons(mContext, sbn); entry.reset(); updateNotification(entry, pmUser, sbn, entry.getRow()); + entry.getRow().setOnDismissRunnable(onDismissRunnable); } else { entry.createIcons(mContext, sbn); new RowInflaterTask().inflate(mContext, parent, entry, diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java index a817f54e77ca..50a20374fee5 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ActivatableNotificationView.java @@ -159,6 +159,8 @@ public abstract class ActivatableNotificationView extends ExpandableOutlineView private int mHeadsUpAddStartLocation; private float mHeadsUpLocation; private boolean mIsAppearing; + private boolean mDismissed; + private boolean mRefocusOnDismiss; public ActivatableNotificationView(Context context, AttributeSet attrs) { super(context, attrs); @@ -1048,6 +1050,27 @@ public abstract class ActivatableNotificationView extends ExpandableOutlineView return getHeight(); } + /** Mark that this view has been dismissed. */ + public void dismiss(boolean refocusOnDismiss) { + mDismissed = true; + mRefocusOnDismiss = refocusOnDismiss; + } + + /** Mark that this view is no longer dismissed. */ + public void unDismiss() { + mDismissed = false; + } + + /** Is this view marked as dismissed? */ + public boolean isDismissed() { + return mDismissed; + } + + /** Should a re-focus occur upon dismissing this view? */ + public boolean shouldRefocusOnDismiss() { + return mRefocusOnDismiss || isAccessibilityFocused(); + } + public interface OnActivatedListener { void onActivated(ActivatableNotificationView view); void onActivationReset(ActivatableNotificationView view); diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java index 536db67a8795..f0d07a7ed0bd 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRow.java @@ -95,6 +95,7 @@ import com.android.systemui.statusbar.notification.stack.AnimationProperties; import com.android.systemui.statusbar.notification.stack.ExpandableViewState; import com.android.systemui.statusbar.notification.stack.NotificationChildrenContainer; import com.android.systemui.statusbar.notification.stack.NotificationStackScrollLayout; +import com.android.systemui.statusbar.notification.stack.SwipeableView; import com.android.systemui.statusbar.phone.KeyguardBypassController; import com.android.systemui.statusbar.phone.NotificationGroupManager; import com.android.systemui.statusbar.phone.StatusBar; @@ -114,7 +115,7 @@ import java.util.function.Consumer; * the group summary (which contains 1 or more child notifications). */ public class ExpandableNotificationRow extends ActivatableNotificationView - implements PluginListener<NotificationMenuRowPlugin> { + implements PluginListener<NotificationMenuRowPlugin>, SwipeableView { private static final boolean DEBUG = false; private static final int DEFAULT_DIVIDER_ALPHA = 0x29; @@ -288,7 +289,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView } }; private boolean mForceUnlocked; - private boolean mDismissed; private boolean mKeepInParent; private boolean mRemoved; private static final Property<ExpandableNotificationRow, Float> TRANSLATE_CONTENT = @@ -307,7 +307,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView private boolean mHeadsupDisappearRunning; private View mChildAfterViewWhenDismissed; private View mGroupParentWhenDismissed; - private boolean mRefocusOnDismiss; private float mContentTransformationAmount; private boolean mIconsVisible = true; private boolean mAboveShelf; @@ -1164,6 +1163,11 @@ public class ExpandableNotificationRow extends ActivatableNotificationView } } + @Override + public boolean hasFinishedInitialization() { + return getEntry().hasFinishedInitialization(); + } + /** * Get a handle to a NotificationMenuRowPlugin whose menu view has been added to our hierarchy, * or null if there is no menu row @@ -1323,11 +1327,11 @@ public class ExpandableNotificationRow extends ActivatableNotificationView } } - public void setDismissed(boolean fromAccessibility) { + @Override + public void dismiss(boolean refocusOnDismiss) { + super.dismiss(refocusOnDismiss); setLongPressListener(null); - mDismissed = true; mGroupParentWhenDismissed = mNotificationParent; - mRefocusOnDismiss = fromAccessibility; mChildAfterViewWhenDismissed = null; mEntry.icon.setDismissed(); if (isChildInGroup()) { @@ -1340,10 +1344,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView } } - public boolean isDismissed() { - return mDismissed; - } - public boolean keepInParent() { return mKeepInParent; } @@ -1445,7 +1445,7 @@ public class ExpandableNotificationRow extends ActivatableNotificationView groupSummary.getRow().performDismiss(fromAccessibility); } } - setDismissed(fromAccessibility); + dismiss(fromAccessibility); if (mEntry.isClearable()) { // TODO: beverlyt, log dismissal // TODO: track dismiss sentiment @@ -3021,10 +3021,6 @@ public class ExpandableNotificationRow extends ActivatableNotificationView return false; } - public boolean shouldRefocusOnDismiss() { - return mRefocusOnDismiss || isAccessibilityFocused(); - } - public interface OnExpandClickListener { void onExpandClicked(NotificationEntry clickedEntry, boolean nowExpanded); } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java index 54d406615ae0..fdd51e9e7790 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSectionsManager.java @@ -23,7 +23,6 @@ import static java.lang.annotation.RetentionPolicy.SOURCE; import android.annotation.IntDef; import android.annotation.NonNull; import android.annotation.Nullable; -import android.app.PendingIntent; import android.content.Intent; import android.provider.Settings; import android.view.LayoutInflater; @@ -310,6 +309,8 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section mParent.removeView(mPeopleHubView); } } else { + mPeopleHubView.unDismiss(); + mPeopleHubView.resetTranslation(); if (!currentlyVisible) { if (mPeopleHubView.getTransientContainer() != null) { mPeopleHubView.getTransientContainer().removeTransientView(mPeopleHubView); @@ -419,8 +420,9 @@ public class NotificationSectionsManager implements StackScrollAlgorithm.Section } } - private void handlePeopleHubClick(PendingIntent pendingIntent) { - mActivityStarter.startPendingIntentDismissingKeyguard(pendingIntent, null, mPeopleHubView); + void hidePeopleRow() { + mPeopleHubVisible = false; + updateSectionBoundaries(); } /** diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java index 6dca7ee9e872..2b9912ce055d 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationStackScrollLayout.java @@ -4920,7 +4920,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd } else { child.setMinClipTopAmount(0); } - previousChildWillBeDismissed = StackScrollAlgorithm.canChildBeDismissed(child); + previousChildWillBeDismissed = canChildBeDismissed(child); } } @@ -5523,7 +5523,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd performDismissAllAnimations(viewsToHide, closeShade, () -> { for (ExpandableNotificationRow rowToRemove : viewsToRemove) { - if (StackScrollAlgorithm.canChildBeDismissed(rowToRemove)) { + if (canChildBeDismissed(rowToRemove)) { if (selection == ROWS_ALL) { // TODO: This is a listener method; we shouldn't be calling it. Can we just // call performRemoveNotification as below? @@ -5552,7 +5552,7 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd private boolean includeChildInDismissAll( ExpandableNotificationRow row, @SelectedRows int selection) { - return StackScrollAlgorithm.canChildBeDismissed(row) && matchesSelection(row, selection); + return canChildBeDismissed(row) && matchesSelection(row, selection); } /** @@ -6223,7 +6223,10 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd */ @Override public void onChildDismissed(View view) { - ExpandableNotificationRow row = (ExpandableNotificationRow) view; + if (!(view instanceof ActivatableNotificationView)) { + return; + } + ActivatableNotificationView row = (ActivatableNotificationView) view; if (!row.isDismissed()) { handleChildViewDismissed(view); } @@ -6261,6 +6264,12 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd row.performDismissWithBlockingHelper(false /* fromAccessibility */); } + if (view instanceof PeopleHubView) { + PeopleHubView row = (PeopleHubView) view; + row.dismiss(false); + mSectionsManager.hidePeopleRow(); + } + if (!isBlockingHelperShown) { mSwipedOutViews.add(view); } @@ -6349,9 +6358,9 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd return 0; } - @Override + @Override public boolean canChildBeDismissed(View v) { - return StackScrollAlgorithm.canChildBeDismissed(v); + return NotificationStackScrollLayout.canChildBeDismissed(v); } @Override @@ -6361,6 +6370,23 @@ public class NotificationStackScrollLayout extends ViewGroup implements ScrollAd } }; + private static boolean canChildBeDismissed(View v) { + if (v instanceof ExpandableNotificationRow) { + ExpandableNotificationRow row = (ExpandableNotificationRow) v; + if (row.isBlockingHelperShowingAndTranslationFinished()) { + return true; + } + if (row.areGutsExposed() || !row.getEntry().hasFinishedInitialization()) { + return false; + } + return row.canViewBeDismissed(); + } + if (v instanceof PeopleHubView) { + return true; + } + return false; + } + // ---------------------- DragDownHelper.OnDragDownListener ------------------------------------ @ShadeViewRefactor(RefactorComponent.INPUT) diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelper.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelper.java index 0968674d31cc..6d0fcc386281 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelper.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/NotificationSwipeHelper.java @@ -31,11 +31,10 @@ import com.android.systemui.SwipeHelper; import com.android.systemui.plugins.FalsingManager; import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin; import com.android.systemui.plugins.statusbar.NotificationSwipeActionHelper; -import com.android.systemui.statusbar.notification.row.ExpandableNotificationRow; import com.android.systemui.statusbar.notification.row.ExpandableView; -class NotificationSwipeHelper extends SwipeHelper - implements NotificationSwipeActionHelper { +class NotificationSwipeHelper extends SwipeHelper implements NotificationSwipeActionHelper { + @VisibleForTesting protected static final long COVER_MENU_DELAY = 4000; private static final String TAG = "NotificationSwipeHelper"; @@ -58,12 +57,7 @@ class NotificationSwipeHelper extends SwipeHelper super(swipeDirection, callback, context, falsingManager); mMenuListener = menuListener; mCallback = callback; - mFalsingCheck = new Runnable() { - @Override - public void run() { - resetExposedMenuView(true /* animate */, true /* force */); - } - }; + mFalsingCheck = () -> resetExposedMenuView(true /* animate */, true /* force */); } public View getTranslatingParentView() { @@ -126,14 +120,14 @@ class NotificationSwipeHelper extends SwipeHelper // Slide back any notifications that might be showing a menu resetExposedMenuView(true /* animate */, false /* force */); - if (currView instanceof ExpandableNotificationRow) { - initializeRow((ExpandableNotificationRow) currView); + if (currView instanceof SwipeableView) { + initializeRow((SwipeableView) currView); } } @VisibleForTesting - protected void initializeRow(ExpandableNotificationRow row) { - if (row.getEntry().hasFinishedInitialization()) { + protected void initializeRow(SwipeableView row) { + if (row.hasFinishedInitialization()) { mCurrMenuRow = row.createMenu(); if (mCurrMenuRow != null) { mCurrMenuRow.setMenuClickListener(mMenuListener); @@ -304,8 +298,8 @@ class NotificationSwipeHelper extends SwipeHelper @Override public Animator getViewTranslationAnimator(View v, float target, ValueAnimator.AnimatorUpdateListener listener) { - if (v instanceof ExpandableNotificationRow) { - return ((ExpandableNotificationRow) v).getTranslateViewAnimator(target, listener); + if (v instanceof SwipeableView) { + return ((SwipeableView) v).getTranslateViewAnimator(target, listener); } else { return superGetViewTranslationAnimator(v, target, listener); } @@ -313,15 +307,15 @@ class NotificationSwipeHelper extends SwipeHelper @Override public void setTranslation(View v, float translate) { - if (v instanceof ExpandableNotificationRow) { - ((ExpandableNotificationRow) v).setTranslation(translate); + if (v instanceof SwipeableView) { + ((SwipeableView) v).setTranslation(translate); } } @Override public float getTranslation(View v) { - if (v instanceof ExpandableNotificationRow) { - return ((ExpandableNotificationRow) v).getTranslation(); + if (v instanceof SwipeableView) { + return ((SwipeableView) v).getTranslation(); } else { return 0f; @@ -410,8 +404,8 @@ class NotificationSwipeHelper extends SwipeHelper if (anim != null) { anim.start(); } - } else if (prevMenuExposedView instanceof ExpandableNotificationRow) { - ExpandableNotificationRow row = (ExpandableNotificationRow) prevMenuExposedView; + } else if (prevMenuExposedView instanceof SwipeableView) { + SwipeableView row = (SwipeableView) prevMenuExposedView; if (!row.isRemoved()) { row.resetTranslation(); } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/PeopleHubView.kt b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/PeopleHubView.kt index e31ee024fa36..a0796060e9d8 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/PeopleHubView.kt +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/PeopleHubView.kt @@ -16,23 +16,39 @@ package com.android.systemui.statusbar.notification.stack +import android.animation.Animator +import android.animation.AnimatorListenerAdapter +import android.animation.ObjectAnimator +import android.animation.ValueAnimator import android.content.Context import android.util.AttributeSet +import android.util.FloatProperty import android.view.View import android.view.ViewGroup import android.widget.ImageView import android.widget.LinearLayout import android.widget.TextView import com.android.systemui.R -import com.android.systemui.statusbar.notification.people.PersonViewModel +import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin import com.android.systemui.statusbar.notification.people.DataListener +import com.android.systemui.statusbar.notification.people.PersonViewModel import com.android.systemui.statusbar.notification.row.ActivatableNotificationView +private val TRANSLATE_CONTENT = object : FloatProperty<PeopleHubView>("translate") { + override fun setValue(view: PeopleHubView, value: Float) { + view.translation = value + } + + override fun get(view: PeopleHubView) = view.translation +} + class PeopleHubView(context: Context, attrs: AttributeSet) : - ActivatableNotificationView(context, attrs) { + ActivatableNotificationView(context, attrs), SwipeableView { private lateinit var contents: ViewGroup private lateinit var personControllers: List<PersonDataListenerImpl> + private var translateAnim: ObjectAnimator? = null + val personViewAdapters: Sequence<DataListener<PersonViewModel?>> get() = personControllers.asSequence() @@ -49,6 +65,34 @@ class PeopleHubView(context: Context, attrs: AttributeSet) : override fun getContentView(): View = contents + override fun hasFinishedInitialization(): Boolean = true + + override fun createMenu(): NotificationMenuRowPlugin? = null + + override fun getTranslateViewAnimator( + leftTarget: Float, + listener: ValueAnimator.AnimatorUpdateListener? + ): Animator = + ObjectAnimator + .ofFloat(this, TRANSLATE_CONTENT, leftTarget) + .apply { + listener?.let { addUpdateListener(listener) } + addListener(object : AnimatorListenerAdapter() { + override fun onAnimationEnd(anim: Animator) { + translateAnim = null + } + }) + } + .also { + translateAnim?.cancel() + translateAnim = it + } + + override fun resetTranslation() { + translateAnim?.cancel() + translationX = 0f + } + private inner class PersonDataListenerImpl(val viewGroup: ViewGroup) : DataListener<PersonViewModel?> { diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java index 4b61064f4a54..9646c01c8c41 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/StackScrollAlgorithm.java @@ -195,20 +195,6 @@ public class StackScrollAlgorithm { } } - public static boolean canChildBeDismissed(View v) { - if (!(v instanceof ExpandableNotificationRow)) { - return false; - } - ExpandableNotificationRow row = (ExpandableNotificationRow) v; - if (row.isBlockingHelperShowingAndTranslationFinished()) { - return true; - } - if (row.areGutsExposed() || !row.getEntry().hasFinishedInitialization()) { - return false; - } - return row.canViewBeDismissed(); - } - /** * Updates the dimmed, activated and hiding sensitive states of the children. */ diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/SwipeableView.java b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/SwipeableView.java new file mode 100644 index 000000000000..6c6ef61cfdaf --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/notification/stack/SwipeableView.java @@ -0,0 +1,50 @@ +/* + * 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.notification.stack; + +import android.animation.Animator; +import android.animation.ValueAnimator; + +import androidx.annotation.Nullable; + +import com.android.systemui.plugins.statusbar.NotificationMenuRowPlugin; + +/** A View that is swipeable inside of the notification shade. */ +public interface SwipeableView { + + /** Has this view finished initializing? */ + boolean hasFinishedInitialization(); + + /** Optionally creates a menu for this view. */ + @Nullable NotificationMenuRowPlugin createMenu(); + + /** Animator for translating the view, simulating a swipe. */ + Animator getTranslateViewAnimator( + float leftTarget, ValueAnimator.AnimatorUpdateListener listener); + + /** Sets the translation amount for an in-progress swipe. */ + void setTranslation(float translate); + + /** Gets the current translation amount. */ + float getTranslation(); + + /** Has this view been removed? */ + boolean isRemoved(); + + /** Resets the swipe translation back to zero state. */ + void resetTranslation(); +} diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ButtonDispatcher.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ButtonDispatcher.java index fce1dcc998fe..c2731089132c 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/ButtonDispatcher.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/ButtonDispatcher.java @@ -203,10 +203,16 @@ public class ButtonDispatcher { mFadeAnimator.addUpdateListener(mAlphaListener); mFadeAnimator.start(); } else { - mAlpha = alpha; - final int N = mViews.size(); - for (int i = 0; i < N; i++) { - mViews.get(i).setAlpha(alpha); + // Discretize the alpha updates to prevent too frequent updates when there is a long + // alpha animation + int prevAlpha = (int) (getAlpha() * 255); + int nextAlpha = (int) (alpha * 255); + if (prevAlpha != nextAlpha) { + mAlpha = nextAlpha / 255f; + final int N = mViews.size(); + for (int i = 0; i < N; i++) { + mViews.get(i).setAlpha(mAlpha); + } } } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationHandle.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationHandle.java index 4f7af58094ec..abceb11b36e9 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationHandle.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NavigationHandle.java @@ -31,13 +31,13 @@ import com.android.settingslib.Utils; import com.android.systemui.R; public class NavigationHandle extends View implements ButtonInterface { - private float mDarkIntensity = -1; private final Paint mPaint = new Paint(); private @ColorInt final int mLightColor; private @ColorInt final int mDarkColor; private final int mRadius; private final int mBottom; + private boolean mRequiresInvalidate; public NavigationHandle(Context context) { this(context, null); @@ -60,6 +60,15 @@ public class NavigationHandle extends View implements ButtonInterface { } @Override + public void setAlpha(float alpha) { + super.setAlpha(alpha); + if (alpha > 0f && mRequiresInvalidate) { + mRequiresInvalidate = false; + invalidate(); + } + } + + @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); @@ -85,11 +94,15 @@ public class NavigationHandle extends View implements ButtonInterface { @Override public void setDarkIntensity(float intensity) { - if (mDarkIntensity != intensity) { - mPaint.setColor((int) ArgbEvaluator.getInstance().evaluate(intensity, mLightColor, - mDarkColor)); - mDarkIntensity = intensity; - invalidate(); + int color = (int) ArgbEvaluator.getInstance().evaluate(intensity, mLightColor, mDarkColor); + if (mPaint.getColor() != color) { + mPaint.setColor(color); + if (getVisibility() == VISIBLE && getAlpha() > 0) { + invalidate(); + } else { + // If we are currently invisible, then invalidate when we are next made visible + mRequiresInvalidate = true; + } } } 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 4148a73e579c..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; @@ -157,7 +155,6 @@ import com.android.systemui.bubbles.BubbleController; import com.android.systemui.charging.WirelessChargingAnimation; import com.android.systemui.classifier.FalsingLog; import com.android.systemui.colorextraction.SysuiColorExtractor; -import com.android.systemui.dagger.SystemUIBinder; import com.android.systemui.doze.DozeHost; import com.android.systemui.doze.DozeLog; import com.android.systemui.fragments.ExtensionFragmentListener; @@ -202,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; @@ -243,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; @@ -364,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; @@ -384,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; @@ -403,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 @@ -637,7 +632,7 @@ public class StatusBar extends SystemUI implements DemoMode, * Public constructor for StatusBar. * * StatusBar is considered optional, and therefore can not be marked as @Inject directly. - * Instead, an @Provide method is included in {@link SystemUIBinder}. + * Instead, an @Provide method is included. */ public StatusBar( Context context, @@ -647,7 +642,6 @@ public class StatusBar extends SystemUI implements DemoMode, KeyguardUpdateMonitor keyguardUpdateMonitor, StatusBarIconController statusBarIconController, DozeLog dozeLog, - InjectionInflationController injectionInflationController, PulseExpansionHandler pulseExpansionHandler, NotificationWakeUpCoordinator notificationWakeUpCoordinator, KeyguardBypassController keyguardBypassController, @@ -706,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; @@ -714,7 +709,6 @@ public class StatusBar extends SystemUI implements DemoMode, mKeyguardUpdateMonitor = keyguardUpdateMonitor; mIconController = statusBarIconController; mDozeLog = dozeLog; - mInjectionInflater = injectionInflationController; mPulseExpansionHandler = pulseExpansionHandler; mWakeUpCoordinator = notificationWakeUpCoordinator; mKeyguardBypassController = keyguardBypassController; @@ -774,6 +768,8 @@ public class StatusBar extends SystemUI implements DemoMode, mCommandQueue = commandQueue; mPluginManager = pluginManager; mRemoteInputUriController = remoteInputUriController; + mSuperStatusBarViewFactory = superStatusBarViewFactory; + mBubbleExpandListener = (isExpanding, key) -> { mEntryManager.updateNotifications("onBubbleExpandChanged"); @@ -1368,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); } @@ -1429,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(); } @@ -1470,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) { @@ -2649,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 @@ -2927,7 +2913,7 @@ public class StatusBar extends SystemUI implements DemoMode, mQSPanel.updateResources(); } - loadDimens(); + mStatusBarWindowController.refreshStatusBarHeight(); if (mStatusBarView != null) { mStatusBarView.updateResources(); @@ -2940,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 new file mode 100644 index 000000000000..67f6a0ca6b72 --- /dev/null +++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/StatusBarModule.java @@ -0,0 +1,230 @@ +/* + * 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.phone; + +import static com.android.systemui.Dependency.ALLOW_NOTIFICATION_LONG_PRESS_NAME; + +import android.content.Context; +import android.os.PowerManager; +import android.util.DisplayMetrics; + +import androidx.annotation.Nullable; + +import com.android.internal.logging.MetricsLogger; +import com.android.keyguard.KeyguardUpdateMonitor; +import com.android.systemui.ForegroundServiceController; +import com.android.systemui.UiOffloadThread; +import com.android.systemui.appops.AppOpsController; +import com.android.systemui.assist.AssistManager; +import com.android.systemui.broadcast.BroadcastDispatcher; +import com.android.systemui.bubbles.BubbleController; +import com.android.systemui.colorextraction.SysuiColorExtractor; +import com.android.systemui.doze.DozeLog; +import com.android.systemui.keyguard.KeyguardViewMediator; +import com.android.systemui.keyguard.ScreenLifecycle; +import com.android.systemui.keyguard.WakefulnessLifecycle; +import com.android.systemui.plugins.FalsingManager; +import com.android.systemui.shared.plugins.PluginManager; +import com.android.systemui.statusbar.CommandQueue; +import com.android.systemui.statusbar.FeatureFlags; +import com.android.systemui.statusbar.NavigationBarController; +import com.android.systemui.statusbar.NotificationListener; +import com.android.systemui.statusbar.NotificationLockscreenUserManager; +import com.android.systemui.statusbar.NotificationMediaManager; +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; +import com.android.systemui.statusbar.notification.DynamicPrivacyController; +import com.android.systemui.statusbar.notification.NewNotifPipeline; +import com.android.systemui.statusbar.notification.NotificationAlertingManager; +import com.android.systemui.statusbar.notification.NotificationEntryManager; +import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider; +import com.android.systemui.statusbar.notification.NotificationWakeUpCoordinator; +import com.android.systemui.statusbar.notification.VisualStabilityManager; +import com.android.systemui.statusbar.notification.logging.NotifLog; +import com.android.systemui.statusbar.notification.logging.NotificationLogger; +import com.android.systemui.statusbar.notification.row.NotificationGutsManager; +import com.android.systemui.statusbar.policy.BatteryController; +import com.android.systemui.statusbar.policy.ConfigurationController; +import com.android.systemui.statusbar.policy.DeviceProvisionedController; +import com.android.systemui.statusbar.policy.KeyguardStateController; +import com.android.systemui.statusbar.policy.NetworkController; +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 javax.inject.Named; +import javax.inject.Singleton; + +import dagger.Lazy; +import dagger.Module; +import dagger.Provides; + +/** + * Dagger Module providing {@link StatusBar}. + */ +@Module(includes = {StatusBarDependenciesModule.class}) +public class StatusBarModule { + /** + * Provides our instance of StatusBar which is considered optional. + */ + @Provides + @Singleton + static StatusBar provideStatusBar( + Context context, + FeatureFlags featureFlags, + LightBarController lightBarController, + AutoHideController autoHideController, + KeyguardUpdateMonitor keyguardUpdateMonitor, + StatusBarIconController statusBarIconController, + DozeLog dozeLog, + PulseExpansionHandler pulseExpansionHandler, + NotificationWakeUpCoordinator notificationWakeUpCoordinator, + KeyguardBypassController keyguardBypassController, + KeyguardStateController keyguardStateController, + HeadsUpManagerPhone headsUpManagerPhone, + DynamicPrivacyController dynamicPrivacyController, + BypassHeadsUpNotifier bypassHeadsUpNotifier, + @Named(ALLOW_NOTIFICATION_LONG_PRESS_NAME) boolean allowNotificationLongPress, + Lazy<NewNotifPipeline> newNotifPipeline, + FalsingManager falsingManager, + BroadcastDispatcher broadcastDispatcher, + RemoteInputQuickSettingsDisabler remoteInputQuickSettingsDisabler, + NotificationGutsManager notificationGutsManager, + NotificationLogger notificationLogger, + NotificationEntryManager notificationEntryManager, + NotificationInterruptionStateProvider notificationInterruptionStateProvider, + NotificationViewHierarchyManager notificationViewHierarchyManager, + ForegroundServiceController foregroundServiceController, + AppOpsController appOpsController, + KeyguardViewMediator keyguardViewMediator, + ZenModeController zenModeController, + NotificationAlertingManager notificationAlertingManager, + DisplayMetrics displayMetrics, + MetricsLogger metricsLogger, + UiOffloadThread uiOffloadThread, + NotificationMediaManager notificationMediaManager, + NotificationLockscreenUserManager lockScreenUserManager, + NotificationRemoteInputManager remoteInputManager, + UserSwitcherController userSwitcherController, + NetworkController networkController, + BatteryController batteryController, + SysuiColorExtractor colorExtractor, + ScreenLifecycle screenLifecycle, + WakefulnessLifecycle wakefulnessLifecycle, + SysuiStatusBarStateController statusBarStateController, + VibratorHelper vibratorHelper, + BubbleController bubbleController, + NotificationGroupManager groupManager, + NotificationGroupAlertTransferHelper groupAlertTransferHelper, + VisualStabilityManager visualStabilityManager, + DeviceProvisionedController deviceProvisionedController, + NavigationBarController navigationBarController, + AssistManager assistManager, + NotificationListener notificationListener, + ConfigurationController configurationController, + StatusBarWindowController statusBarWindowController, + StatusBarWindowViewController.Builder statusBarWindowViewControllerBuilder, + NotifLog notifLog, + DozeParameters dozeParameters, + ScrimController scrimController, + @Nullable KeyguardLiftController keyguardLiftController, + Lazy<LockscreenWallpaper> lockscreenWallpaperLazy, + Lazy<BiometricUnlockController> biometricUnlockControllerLazy, + DozeServiceHost dozeServiceHost, + PowerManager powerManager, + DozeScrimController dozeScrimController, + CommandQueue commandQueue, + PluginManager pluginManager, + RemoteInputUriController remoteInputUriController, + SuperStatusBarViewFactory superStatusBarViewFactory) { + return new StatusBar( + context, + featureFlags, + lightBarController, + autoHideController, + keyguardUpdateMonitor, + statusBarIconController, + dozeLog, + pulseExpansionHandler, + notificationWakeUpCoordinator, + keyguardBypassController, + keyguardStateController, + headsUpManagerPhone, + dynamicPrivacyController, + bypassHeadsUpNotifier, + allowNotificationLongPress, + newNotifPipeline, + falsingManager, + broadcastDispatcher, + remoteInputQuickSettingsDisabler, + notificationGutsManager, + notificationLogger, + notificationEntryManager, + notificationInterruptionStateProvider, + notificationViewHierarchyManager, + foregroundServiceController, + appOpsController, + keyguardViewMediator, + zenModeController, + notificationAlertingManager, + displayMetrics, + metricsLogger, + uiOffloadThread, + notificationMediaManager, + lockScreenUserManager, + remoteInputManager, + userSwitcherController, + networkController, + batteryController, + colorExtractor, + screenLifecycle, + wakefulnessLifecycle, + statusBarStateController, + vibratorHelper, + bubbleController, + groupManager, + groupAlertTransferHelper, + visualStabilityManager, + deviceProvisionedController, + navigationBarController, + assistManager, + notificationListener, + configurationController, + statusBarWindowController, + statusBarWindowViewControllerBuilder, + notifLog, + dozeParameters, + scrimController, + keyguardLiftController, + lockscreenWallpaperLazy, + biometricUnlockControllerLazy, + dozeServiceHost, + powerManager, + dozeScrimController, + commandQueue, + pluginManager, + 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/src/com/android/systemui/statusbar/policy/MobileSignalController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java index 5da726749580..bae51b6ebd9e 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/MobileSignalController.java @@ -48,6 +48,7 @@ import com.android.systemui.statusbar.policy.NetworkControllerImpl.SubscriptionD import java.io.PrintWriter; import java.util.BitSet; +import java.util.concurrent.Executor; import java.util.Objects; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -103,7 +104,7 @@ public class MobileSignalController extends SignalController< mPhone = phone; mDefaults = defaults; mSubscriptionInfo = info; - mPhoneStateListener = new MobilePhoneStateListener(receiverLooper); + mPhoneStateListener = new MobilePhoneStateListener((new Handler(receiverLooper))::post); mNetworkNameSeparator = getStringIfExists(R.string.status_bar_network_name_separator); mNetworkNameDefault = getStringIfExists( com.android.internal.R.string.lockscreen_carrier_default); @@ -665,8 +666,8 @@ public class MobileSignalController extends SignalController< } class MobilePhoneStateListener extends PhoneStateListener { - public MobilePhoneStateListener(Looper looper) { - super(looper); + public MobilePhoneStateListener(Executor executor) { + super(executor); } @Override diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java index e5898eded11e..12d357731560 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/NetworkControllerImpl.java @@ -282,7 +282,7 @@ public class NetworkControllerImpl extends BroadcastReceiver // exclusively for status bar icons. mConnectivityManager.registerDefaultNetworkCallback(callback, mReceiverHandler); // Register the listener on our bg looper - mPhoneStateListener = new PhoneStateListener(bgLooper) { + mPhoneStateListener = new PhoneStateListener(mReceiverHandler::post) { @Override public void onActiveDataSubscriptionIdChanged(int subId) { mActiveMobileDataSubscription = subId; @@ -649,7 +649,7 @@ public class NetworkControllerImpl extends BroadcastReceiver } private boolean hasAnySim() { - int simCount = mPhone.getSimCount(); + int simCount = mPhone.getActiveModemCount(); for (int i = 0; i < simCount; i++) { int state = mPhone.getSimState(i); if (state != TelephonyManager.SIM_STATE_ABSENT diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java index 65bb28ffbe39..949ac4df88ba 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/SmartReplyView.java @@ -22,6 +22,7 @@ import android.text.TextPaint; import android.text.method.TransformationMethod; import android.util.AttributeSet; import android.util.Log; +import android.view.ContextThemeWrapper; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; @@ -238,13 +239,15 @@ public class SmartReplyView extends ViewGroup { public List<Button> inflateSmartActions(Context packageContext, @NonNull SmartActions smartActions, SmartReplyController smartReplyController, NotificationEntry entry, HeadsUpManager headsUpManager, boolean delayOnClickListener) { + Context themedPackageContext = new ContextThemeWrapper(packageContext, mContext.getTheme()); List<Button> buttons = new ArrayList<>(); int numSmartActions = smartActions.actions.size(); for (int n = 0; n < numSmartActions; n++) { Notification.Action action = smartActions.actions.get(n); if (action.actionIntent != null) { buttons.add(inflateActionButton( - this, getContext(), packageContext, n, smartActions, smartReplyController, + this, getContext(), themedPackageContext, n, smartActions, + smartReplyController, entry, headsUpManager, delayOnClickListener)); } } diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java index 075c6d40ca31..13c0db938ca0 100644 --- a/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java +++ b/packages/SystemUI/src/com/android/systemui/statusbar/policy/UserSwitcherController.java @@ -463,8 +463,11 @@ public class UserSwitcherController implements Dumpable { } private void listenForCallState() { - TelephonyManager.from(mContext).listen(mPhoneStateListener, - PhoneStateListener.LISTEN_CALL_STATE); + final TelephonyManager tele = + (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE); + if (tele != null) { + tele.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE); + } } private final PhoneStateListener mPhoneStateListener = new PhoneStateListener() { diff --git a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java index 1dd48634615b..d8eaaa182722 100644 --- a/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java +++ b/packages/SystemUI/tests/src/com/android/keyguard/CarrierTextControllerTest.java @@ -145,6 +145,7 @@ public class CarrierTextControllerTest extends SysuiTestCase { mCarrierTextCallbackInfo = new CarrierTextController.CarrierTextCallbackInfo("", new CharSequence[]{}, false, new int[]{}); when(mTelephonyManager.getSupportedModemCount()).thenReturn(3); + when(mTelephonyManager.getActiveModemCount()).thenReturn(3); mCarrierTextController = new CarrierTextController(mContext, SEPARATOR, true, true); // This should not start listening on any of the real dependencies but will test that @@ -216,6 +217,15 @@ public class CarrierTextControllerTest extends SysuiTestCase { // There's only one subscription in the list assertEquals(1, captor.getValue().listOfCarriers.length); assertEquals(TEST_CARRIER, captor.getValue().listOfCarriers[0]); + + // Now it becomes single SIM active mode. + reset(mCarrierTextCallback); + when(mTelephonyManager.getActiveModemCount()).thenReturn(1); + // Update carrier text. It should ignore error state of subId 3 in inactive slotId. + mCarrierTextController.updateCarrierText(); + mTestableLooper.processAllMessages(); + verify(mCarrierTextCallback).updateCarrierInfo(captor.capture()); + assertEquals("TEST_CARRIER", captor.getValue().carrierText); } @Test 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/keyguard/WorkLockActivityTest.java b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java index 187c72a065a7..e4c387a26fd5 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/keyguard/WorkLockActivityTest.java @@ -19,7 +19,10 @@ package com.android.systemui.keyguard; import static android.app.ActivityManager.TaskDescription; import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import android.annotation.ColorInt; @@ -36,7 +39,6 @@ import androidx.test.runner.AndroidJUnit4; import com.android.systemui.SysuiTestCase; import com.android.systemui.broadcast.BroadcastDispatcher; -import com.android.systemui.keyguard.WorkLockActivity; import org.junit.Before; import org.junit.Test; @@ -112,4 +114,11 @@ public class WorkLockActivityTest extends SysuiTestCase { .putExtra(Intent.EXTRA_USER_ID, USER_ID)); assertEquals(orgColor, mActivity.getPrimaryColor()); } + + @Test + public void testUnregisteredFromDispatcher() { + mActivity.unregisterBroadcastReceiver(); + verify(mBroadcastDispatcher).unregisterReceiver(any()); + verify(mContext, never()).unregisterReceiver(any()); + } } diff --git a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java index 5e6c96313d36..d17c573515f5 100644 --- a/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java +++ b/packages/SystemUI/tests/src/com/android/systemui/statusbar/notification/row/ExpandableNotificationRowTest.java @@ -226,7 +226,7 @@ public class ExpandableNotificationRowTest extends SysuiTestCase { any(NotificationMenuRowPlugin.MenuItem.class)); reset(listener); - mGroupRow.setDismissed(true); + mGroupRow.dismiss(true); mGroupRow.doLongClickCallback(0,0); verify(listener, times(0)).onLongPress(eq(mGroupRow), eq(0), eq(0), any(NotificationMenuRowPlugin.MenuItem.class)); 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/packages/Tethering/Android.bp b/packages/Tethering/Android.bp index 998572fc5679..61bfb92363bd 100644 --- a/packages/Tethering/Android.bp +++ b/packages/Tethering/Android.bp @@ -27,6 +27,7 @@ java_defaults { "androidx.annotation_annotation", "netd_aidl_interface-java", "networkstack-aidl-interfaces-java", + "android.hardware.tetheroffload.control-V1.0-java", "tethering-client", ], manifest: "AndroidManifestBase.xml", @@ -38,11 +39,39 @@ android_library { defaults: ["TetheringAndroidLibraryDefaults"], } +cc_library_shared { + name: "libtetheroffloadjni", + srcs: [ + "jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp", + ], + shared_libs: [ + "libnativehelper", + "libcutils", + "android.hardware.tetheroffload.config@1.0", + ], + static_libs: [ + "liblog", + "libbase", + "libhidlbase", + "libutils", + ], + + cflags: [ + "-Wall", + "-Werror", + "-Wno-unused-parameter", + "-Wthread-safety", + ], +} + // Common defaults for compiling the actual APK. java_defaults { name: "TetheringAppDefaults", platform_apis: true, privileged: true, + jni_libs: [ + "libtetheroffloadjni", + ], resource_dirs: [ "res", ], @@ -71,6 +100,8 @@ filegroup { name: "tethering-servicescore-srcs", srcs: [ "src/com/android/server/connectivity/tethering/EntitlementManager.java", + "src/com/android/server/connectivity/tethering/OffloadController.java", + "src/com/android/server/connectivity/tethering/OffloadHardwareInterface.java", "src/com/android/server/connectivity/tethering/TetheringConfiguration.java", "src/com/android/server/connectivity/tethering/UpstreamNetworkMonitor.java", ], @@ -88,3 +119,11 @@ filegroup { "src/android/net/util/PrefixUtils.java", ], } + +// This group would be removed when tethering migration is done. +filegroup { + name: "tethering-jni-srcs", + srcs: [ + "jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp", + ], +} diff --git a/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp b/packages/Tethering/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp index 3eaf48845a2f..3eaf48845a2f 100644 --- a/services/core/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp +++ b/packages/Tethering/jni/com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp diff --git a/services/core/java/com/android/server/connectivity/tethering/OffloadController.java b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java index a3c299814a7a..16734d83e3aa 100644 --- a/services/core/java/com/android/server/connectivity/tethering/OffloadController.java +++ b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadController.java @@ -36,8 +36,8 @@ import android.net.netlink.NetlinkSocket; import android.net.util.IpUtils; import android.net.util.SharedLog; import android.os.Handler; -import android.os.Looper; import android.os.INetworkManagementService; +import android.os.Looper; import android.os.RemoteException; import android.os.SystemClock; import android.provider.Settings; @@ -60,7 +60,6 @@ import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.TimeUnit; /** * A class to encapsulate the business logic of programming the tethering @@ -74,7 +73,7 @@ public class OffloadController { private static final String ANYIP = "0.0.0.0"; private static final ForwardedStats EMPTY_STATS = new ForwardedStats(); - private static enum UpdateType { IF_NEEDED, FORCE }; + private enum UpdateType { IF_NEEDED, FORCE }; private final Handler mHandler; private final OffloadHardwareInterface mHwInterface; @@ -128,6 +127,7 @@ public class OffloadController { } } + /** Start hardware offload. */ public boolean start() { if (started()) return true; @@ -235,6 +235,7 @@ public class OffloadController { return isStarted; } + /** Stop hardware offload. */ public void stop() { // Completely stops tethering offload. After this method is called, it is no longer safe to // call any HAL method, no callbacks from the hardware will be delivered, and any in-flight @@ -258,7 +259,9 @@ public class OffloadController { // getTetherStats() is the only function in OffloadController that can be called from // a different thread. Do not attempt to update stats by querying the offload HAL // synchronously from a different thread than our Handler thread. http://b/64771555. - Runnable updateStats = () -> { updateStatsForCurrentUpstream(); }; + Runnable updateStats = () -> { + updateStatsForCurrentUpstream(); + }; if (Looper.myLooper() == mHandler.getLooper()) { updateStats.run(); } else { @@ -358,6 +361,7 @@ public class OffloadController { } } + /** Set current tethering upstream LinkProperties. */ public void setUpstreamLinkProperties(LinkProperties lp) { if (!started() || Objects.equals(mUpstreamLinkProperties, lp)) return; @@ -376,6 +380,7 @@ public class OffloadController { pushUpstreamParameters(prevUpstream); } + /** Set local prefixes. */ public void setLocalPrefixes(Set<IpPrefix> localPrefixes) { mExemptPrefixes = localPrefixes; @@ -383,6 +388,7 @@ public class OffloadController { computeAndPushLocalPrefixes(UpdateType.IF_NEEDED); } + /** Update current downstream LinkProperties. */ public void notifyDownstreamLinkProperties(LinkProperties lp) { final String ifname = lp.getInterfaceName(); final LinkProperties oldLp = mDownstreams.put(ifname, new LinkProperties(lp)); @@ -421,6 +427,7 @@ public class OffloadController { } } + /** Remove downstream interface from offload hardware. */ public void removeDownstreamInterface(String ifname) { final LinkProperties lp = mDownstreams.remove(ifname); if (lp == null) return; @@ -481,7 +488,7 @@ public class OffloadController { iface, v4addr, v4gateway, (v6gateways.isEmpty() ? null : v6gateways)); if (!success) { - return success; + return success; } // Update stats after we've told the hardware to change routing so we don't miss packets. @@ -545,6 +552,7 @@ public class OffloadController { return false; } + /** Dump information. */ public void dump(IndentingPrintWriter pw) { if (isOffloadDisabled()) { pw.println("Offload disabled"); @@ -630,7 +638,7 @@ public class OffloadController { if (ip instanceof Inet4Address) { return (Inet4Address) ip; } - } catch (IllegalArgumentException iae) {} + } catch (IllegalArgumentException iae) { } return null; } diff --git a/services/core/java/com/android/server/connectivity/tethering/OffloadHardwareInterface.java b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadHardwareInterface.java index 207f86762b95..01339a4a2c33 100644 --- a/services/core/java/com/android/server/connectivity/tethering/OffloadHardwareInterface.java +++ b/packages/Tethering/src/com/android/server/connectivity/tethering/OffloadHardwareInterface.java @@ -23,9 +23,9 @@ import android.hardware.tetheroffload.control.V1_0.ITetheringOffloadCallback; import android.hardware.tetheroffload.control.V1_0.NatTimeoutUpdate; import android.hardware.tetheroffload.control.V1_0.NetworkProtocol; import android.hardware.tetheroffload.control.V1_0.OffloadCallbackEvent; +import android.net.util.SharedLog; import android.os.Handler; import android.os.RemoteException; -import android.net.util.SharedLog; import android.system.OsConstants; import java.util.ArrayList; @@ -55,18 +55,34 @@ public class OffloadHardwareInterface { private TetheringOffloadCallback mTetheringOffloadCallback; private ControlCallback mControlCallback; + /** The callback to notify status of offload management process. */ public static class ControlCallback { + /** Offload started. */ public void onStarted() {} + /** + * Offload stopped because an error has occurred in lower layer. + */ public void onStoppedError() {} + /** + * Offload stopped because the device has moved to a bearer on which hardware offload is + * not supported. Subsequent calls to setUpstreamParameters and add/removeDownstream will + * likely fail and cannot be presumed to be saved inside of the hardware management process. + * Upon receiving #onSupportAvailable(), the caller should reprogram the hardware to begin + * offload again. + */ public void onStoppedUnsupported() {} + /** Indicate that offload is able to proivde support for this time. */ public void onSupportAvailable() {} + /** Offload stopped because of usage limit reached. */ public void onStoppedLimitReached() {} + /** Indicate to update NAT timeout. */ public void onNatTimeoutUpdate(int proto, String srcAddr, int srcPort, String dstAddr, int dstPort) {} } + /** The object which records Tx/Rx forwarded bytes. */ public static class ForwardedStats { public long rxBytes; public long txBytes; @@ -76,11 +92,13 @@ public class OffloadHardwareInterface { txBytes = 0; } + /** Add Tx/Rx bytes. */ public void add(ForwardedStats other) { rxBytes += other.rxBytes; txBytes += other.txBytes; } + /** Returns the string representation of this object. */ public String toString() { return String.format("rx:%s tx:%s", rxBytes, txBytes); } @@ -91,14 +109,17 @@ public class OffloadHardwareInterface { mLog = log.forSubComponent(TAG); } + /** Get default value indicating whether offload is supported. */ public int getDefaultTetherOffloadDisabled() { return DEFAULT_TETHER_OFFLOAD_DISABLED; } + /** Configure offload management process. */ public boolean initOffloadConfig() { return configOffload(); } + /** Initialize the tethering offload HAL. */ public boolean initOffloadControl(ControlCallback controlCb) { mControlCallback = controlCb; @@ -125,8 +146,8 @@ public class OffloadHardwareInterface { mOffloadControl.initOffload( mTetheringOffloadCallback, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -134,9 +155,10 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } + /** Stop IOffloadControl. */ public void stopOffloadControl() { if (mOffloadControl != null) { try { @@ -154,6 +176,7 @@ public class OffloadHardwareInterface { mLog.log("stopOffloadControl()"); } + /** Get Tx/Rx usage from last query. */ public ForwardedStats getForwardedStats(String upstream) { final String logmsg = String.format("getForwardedStats(%s)", upstream); @@ -174,6 +197,7 @@ public class OffloadHardwareInterface { return stats; } + /** Set local prefixes to offload management process. */ public boolean setLocalPrefixes(ArrayList<String> localPrefixes) { final String logmsg = String.format("setLocalPrefixes([%s])", String.join(",", localPrefixes)); @@ -182,8 +206,8 @@ public class OffloadHardwareInterface { try { mOffloadControl.setLocalPrefixes(localPrefixes, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -191,9 +215,10 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } + /** Set data limit value to offload management process. */ public boolean setDataLimit(String iface, long limit) { final String logmsg = String.format("setDataLimit(%s, %d)", iface, limit); @@ -203,8 +228,8 @@ public class OffloadHardwareInterface { mOffloadControl.setDataLimit( iface, limit, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -212,9 +237,10 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } + /** Set upstream parameters to offload management process. */ public boolean setUpstreamParameters( String iface, String v4addr, String v4gateway, ArrayList<String> v6gws) { iface = (iface != null) ? iface : NO_INTERFACE_NAME; @@ -230,8 +256,8 @@ public class OffloadHardwareInterface { mOffloadControl.setUpstreamParameters( iface, v4addr, v4gateway, v6gws, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -239,9 +265,10 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } + /** Add downstream prefix to offload management process. */ public boolean addDownstreamPrefix(String ifname, String prefix) { final String logmsg = String.format("addDownstreamPrefix(%s, %s)", ifname, prefix); @@ -249,8 +276,8 @@ public class OffloadHardwareInterface { try { mOffloadControl.addDownstream(ifname, prefix, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -258,9 +285,10 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } + /** Remove downstream prefix from offload management process. */ public boolean removeDownstreamPrefix(String ifname, String prefix) { final String logmsg = String.format("removeDownstreamPrefix(%s, %s)", ifname, prefix); @@ -268,8 +296,8 @@ public class OffloadHardwareInterface { try { mOffloadControl.removeDownstream(ifname, prefix, (boolean success, String errMsg) -> { - results.success = success; - results.errMsg = errMsg; + results.mSuccess = success; + results.mErrMsg = errMsg; }); } catch (RemoteException e) { record(logmsg, e); @@ -277,7 +305,7 @@ public class OffloadHardwareInterface { } record(logmsg, results); - return results.success; + return results.mSuccess; } private void record(String msg, Throwable t) { @@ -286,7 +314,7 @@ public class OffloadHardwareInterface { private void record(String msg, CbResults results) { final String logmsg = msg + YIELDS + results; - if (!results.success) { + if (!results.mSuccess) { mLog.e(logmsg); } else { mLog.log(logmsg); @@ -298,7 +326,7 @@ public class OffloadHardwareInterface { public final ControlCallback controlCb; public final SharedLog log; - public TetheringOffloadCallback(Handler h, ControlCallback cb, SharedLog sharedLog) { + TetheringOffloadCallback(Handler h, ControlCallback cb, SharedLog sharedLog) { handler = h; controlCb = cb; log = sharedLog; @@ -332,7 +360,7 @@ public class OffloadHardwareInterface { @Override public void updateTimeout(NatTimeoutUpdate params) { handler.post(() -> { - controlCb.onNatTimeoutUpdate( + controlCb.onNatTimeoutUpdate( networkProtocolToOsConstant(params.proto), params.src.addr, uint16(params.src.port), params.dst.addr, uint16(params.dst.port)); @@ -352,15 +380,15 @@ public class OffloadHardwareInterface { } private static class CbResults { - boolean success; - String errMsg; + boolean mSuccess; + String mErrMsg; @Override public String toString() { - if (success) { + if (mSuccess) { return "ok"; } else { - return "fail: " + errMsg; + return "fail: " + mErrMsg; } } } diff --git a/packages/Tethering/tests/unit/Android.bp b/packages/Tethering/tests/unit/Android.bp index 7c06e5f0d7ce..363be18a73bc 100644 --- a/packages/Tethering/tests/unit/Android.bp +++ b/packages/Tethering/tests/unit/Android.bp @@ -25,6 +25,7 @@ android_test { static_libs: [ "androidx.test.rules", "frameworks-base-testutils", + "net-tests-utils", "mockito-target-extended-minus-junit4", "TetheringApiCurrentLib", "testables", @@ -46,6 +47,7 @@ filegroup { name: "tethering-tests-src", srcs: [ "src/com/android/server/connectivity/tethering/EntitlementManagerTest.java", + "src/com/android/server/connectivity/tethering/OffloadControllerTest.java", "src/com/android/server/connectivity/tethering/TetheringConfigurationTest.java", "src/com/android/server/connectivity/tethering/UpstreamNetworkMonitorTest.java", "src/android/net/dhcp/DhcpServingParamsParcelExtTest.java", diff --git a/tests/net/java/com/android/server/connectivity/tethering/OffloadControllerTest.java b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/OffloadControllerTest.java index 9931aec01487..8574f5401496 100644 --- a/tests/net/java/com/android/server/connectivity/tethering/OffloadControllerTest.java +++ b/packages/Tethering/tests/unit/src/com/android/server/connectivity/tethering/OffloadControllerTest.java @@ -26,10 +26,10 @@ import static android.provider.Settings.Global.TETHER_OFFLOAD_DISABLED; import static com.android.server.connectivity.tethering.OffloadHardwareInterface.ForwardedStats; import static com.android.testutils.MiscAssertsKt.assertContainsAll; +import static com.android.testutils.MiscAssertsKt.assertThrows; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; -import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyLong; import static org.mockito.Matchers.anyObject; @@ -148,10 +148,8 @@ public class OffloadControllerTest { public void testNoSettingsValueDefaultDisabledDoesNotStart() throws Exception { setupFunctioningHardwareInterface(); when(mHardware.getDefaultTetherOffloadDisabled()).thenReturn(1); - try { - Settings.Global.getInt(mContentResolver, TETHER_OFFLOAD_DISABLED); - fail(); - } catch (SettingNotFoundException expected) {} + assertThrows(SettingNotFoundException.class, () -> + Settings.Global.getInt(mContentResolver, TETHER_OFFLOAD_DISABLED)); final OffloadController offload = makeOffloadController(); offload.start(); @@ -168,10 +166,8 @@ public class OffloadControllerTest { public void testNoSettingsValueDefaultEnabledDoesStart() throws Exception { setupFunctioningHardwareInterface(); when(mHardware.getDefaultTetherOffloadDisabled()).thenReturn(0); - try { - Settings.Global.getInt(mContentResolver, TETHER_OFFLOAD_DISABLED); - fail(); - } catch (SettingNotFoundException expected) {} + assertThrows(SettingNotFoundException.class, () -> + Settings.Global.getInt(mContentResolver, TETHER_OFFLOAD_DISABLED)); final OffloadController offload = makeOffloadController(); offload.start(); diff --git a/services/core/java/com/android/server/am/ProcessList.java b/services/core/java/com/android/server/am/ProcessList.java index f2f1e0286a58..8be31a6e07c2 100644 --- a/services/core/java/com/android/server/am/ProcessList.java +++ b/services/core/java/com/android/server/am/ProcessList.java @@ -1323,7 +1323,7 @@ public final class ProcessList { final int procCount = procs.size(); for (int i = 0; i < procCount; i++) { final int procUid = procs.keyAt(i); - if (UserHandle.isApp(procUid) || !UserHandle.isSameUser(procUid, uid)) { + if (!UserHandle.isCore(procUid) || !UserHandle.isSameUser(procUid, uid)) { // Don't use an app process or different user process for system component. continue; } diff --git a/services/core/java/com/android/server/attention/AttentionManagerService.java b/services/core/java/com/android/server/attention/AttentionManagerService.java index 67d358910de1..232bc08e5b5c 100644 --- a/services/core/java/com/android/server/attention/AttentionManagerService.java +++ b/services/core/java/com/android/server/attention/AttentionManagerService.java @@ -21,6 +21,7 @@ import static android.service.attention.AttentionService.ATTENTION_FAILURE_CANCE import static android.service.attention.AttentionService.ATTENTION_FAILURE_UNKNOWN; import android.Manifest; +import android.annotation.NonNull; import android.annotation.Nullable; import android.annotation.UserIdInt; import android.attention.AttentionManagerInternal; @@ -85,6 +86,10 @@ public class AttentionManagerService extends SystemService { /** If the check attention called within that period - cached value will be returned. */ private static final long STALE_AFTER_MILLIS = 5_000; + /** The size of the buffer that stores recent attention check results. */ + @VisibleForTesting + protected static final int ATTENTION_CACHE_BUFFER_SIZE = 5; + /** DeviceConfig flag name, if {@code true}, enables AttentionManagerService features. */ private static final String SERVICE_ENABLED = "service_enabled"; private static String sTestAttentionServicePackage; @@ -192,7 +197,8 @@ public class AttentionManagerService extends SystemService { userState.bindLocked(); // throttle frequent requests - final AttentionCheckCache cache = userState.mAttentionCheckCache; + final AttentionCheckCache cache = userState.mAttentionCheckCacheBuffer == null ? null + : userState.mAttentionCheckCacheBuffer.getLast(); if (cache != null && now < cache.mLastComputed + STALE_AFTER_MILLIS) { callbackInternal.onSuccess(cache.mResult, cache.mTimestamp); return true; @@ -236,9 +242,11 @@ public class AttentionManagerService extends SystemService { } synchronized (mLock) { - userState.mAttentionCheckCache = new AttentionCheckCache( - SystemClock.uptimeMillis(), result, - timestamp); + if (userState.mAttentionCheckCacheBuffer == null) { + userState.mAttentionCheckCacheBuffer = new AttentionCheckCacheBuffer(); + } + userState.mAttentionCheckCacheBuffer.add( + new AttentionCheckCache(SystemClock.uptimeMillis(), result, timestamp)); } StatsLog.write( StatsLog.ATTENTION_MANAGER_SERVICE_RESULT_REPORTED, @@ -421,7 +429,41 @@ public class AttentionManagerService extends SystemService { } } - private static final class AttentionCheckCache { + @VisibleForTesting + protected static final class AttentionCheckCacheBuffer { + private final AttentionCheckCache[] mQueue; + private int mStartIndex; + private int mSize; + + AttentionCheckCacheBuffer() { + mQueue = new AttentionCheckCache[ATTENTION_CACHE_BUFFER_SIZE]; + mStartIndex = 0; + mSize = 0; + } + + public AttentionCheckCache getLast() { + int lastIdx = (mStartIndex + mSize - 1) % ATTENTION_CACHE_BUFFER_SIZE; + return mSize == 0 ? null : mQueue[lastIdx]; + } + + public void add(@NonNull AttentionCheckCache cache) { + int nextIndex = (mStartIndex + mSize) % ATTENTION_CACHE_BUFFER_SIZE; + mQueue[nextIndex] = cache; + if (mSize == ATTENTION_CACHE_BUFFER_SIZE) { + mStartIndex++; + } else { + mSize++; + } + } + + public AttentionCheckCache get(int offset) { + return offset >= mSize ? null + : mQueue[(mStartIndex + offset) % ATTENTION_CACHE_BUFFER_SIZE]; + } + } + + @VisibleForTesting + protected static final class AttentionCheckCache { private final long mLastComputed; private final int mResult; private final long mTimestamp; @@ -463,7 +505,7 @@ public class AttentionManagerService extends SystemService { @GuardedBy("mLock") AttentionCheck mCurrentAttentionCheck; @GuardedBy("mLock") - AttentionCheckCache mAttentionCheckCache; + AttentionCheckCacheBuffer mAttentionCheckCacheBuffer; @GuardedBy("mLock") private boolean mBinding; @@ -532,13 +574,14 @@ public class AttentionManagerService extends SystemService { pw.println("is fulfilled:=" + mCurrentAttentionCheck.mIsFulfilled); pw.decreaseIndent(); } - pw.println("attention check cache:"); - if (mAttentionCheckCache != null) { - pw.increaseIndent(); - pw.println("last computed=" + mAttentionCheckCache.mLastComputed); - pw.println("timestamp=" + mAttentionCheckCache.mTimestamp); - pw.println("result=" + mAttentionCheckCache.mResult); - pw.decreaseIndent(); + if (mAttentionCheckCacheBuffer != null) { + pw.println("attention check cache:"); + for (int i = 0; i < mAttentionCheckCacheBuffer.mSize; i++) { + pw.increaseIndent(); + pw.println("timestamp=" + mAttentionCheckCacheBuffer.get(i).mTimestamp); + pw.println("result=" + mAttentionCheckCacheBuffer.get(i).mResult); + pw.decreaseIndent(); + } } } } diff --git a/services/core/java/com/android/server/audio/AudioService.java b/services/core/java/com/android/server/audio/AudioService.java index e285bfdcdf4c..6355af6e0b2d 100644 --- a/services/core/java/com/android/server/audio/AudioService.java +++ b/services/core/java/com/android/server/audio/AudioService.java @@ -1583,12 +1583,13 @@ public class AudioService extends IAudioService.Stub setMicrophoneMuteNoCallerCheck(currentUser); } - private int rescaleIndex(int index, int srcStream, int dstStream) { - int srcRange = - mStreamStates[srcStream].getMaxIndex() - mStreamStates[srcStream].getMinIndex(); - int dstRange = - mStreamStates[dstStream].getMaxIndex() - mStreamStates[dstStream].getMinIndex(); + private int getIndexRange(int streamType) { + return (mStreamStates[streamType].getMaxIndex() - mStreamStates[streamType].getMinIndex()); + } + private int rescaleIndex(int index, int srcStream, int dstStream) { + int srcRange = getIndexRange(srcStream); + int dstRange = getIndexRange(dstStream); if (srcRange == 0) { Log.e(TAG, "rescaleIndex : index range should not be zero"); return mStreamStates[dstStream].getMinIndex(); @@ -1599,6 +1600,17 @@ public class AudioService extends IAudioService.Stub / srcRange; } + private int rescaleStep(int step, int srcStream, int dstStream) { + int srcRange = getIndexRange(srcStream); + int dstRange = getIndexRange(dstStream); + if (srcRange == 0) { + Log.e(TAG, "rescaleStep : index range should not be zero"); + return 0; + } + + return ((step * dstRange + srcRange / 2) / srcRange); + } + /////////////////////////////////////////////////////////////////////////// // IPC methods /////////////////////////////////////////////////////////////////////////// @@ -1775,7 +1787,7 @@ public class AudioService extends IAudioService.Stub } } else { // convert one UI step (+/-1) into a number of internal units on the stream alias - step = rescaleIndex(10, streamType, streamTypeAlias); + step = rescaleStep(10, streamType, streamTypeAlias); } // If either the client forces allowing ringer modes for this adjustment, diff --git a/services/core/java/com/android/server/pm/AppsFilter.java b/services/core/java/com/android/server/pm/AppsFilter.java index dc0cd184c188..5195a521dd17 100644 --- a/services/core/java/com/android/server/pm/AppsFilter.java +++ b/services/core/java/com/android/server/pm/AppsFilter.java @@ -211,7 +211,7 @@ public class AppsFilter { final Uri data = intent.getData(); if ("content".equalsIgnoreCase(intent.getScheme()) && data != null - && providerInfo.authority.equalsIgnoreCase(data.getAuthority())) { + && Objects.equals(providerInfo.authority, data.getAuthority())) { return true; } } diff --git a/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java index 91df33a8a16f..ef6b24cd198c 100644 --- a/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java +++ b/services/core/java/com/android/server/pm/UserSystemPackageInstaller.java @@ -116,13 +116,13 @@ class UserSystemPackageInstaller { * <p>Packages that are whitelisted, but then blacklisted so that they aren't to be installed on * any user, are purposefully still present in this list. */ - private final ArrayMap<String, Integer> mWhitelitsedPackagesForUserTypes; + private final ArrayMap<String, Integer> mWhitelistedPackagesForUserTypes; private final UserManagerService mUm; UserSystemPackageInstaller(UserManagerService ums) { mUm = ums; - mWhitelitsedPackagesForUserTypes = + mWhitelistedPackagesForUserTypes = determineWhitelistedPackagesForUserTypes(SystemConfig.getInstance()); } @@ -130,7 +130,7 @@ class UserSystemPackageInstaller { @VisibleForTesting UserSystemPackageInstaller(UserManagerService ums, ArrayMap<String, Integer> whitelist) { mUm = ums; - mWhitelitsedPackagesForUserTypes = whitelist; + mWhitelistedPackagesForUserTypes = whitelist; } /** @@ -249,7 +249,7 @@ class UserSystemPackageInstaller { return (whitelistMode & USER_TYPE_PACKAGE_WHITELIST_MODE_IMPLICIT_WHITELIST) != 0; } - /** Gets the PackageWhitelistMode for use of {@link #mWhitelitsedPackagesForUserTypes}. */ + /** Gets the PackageWhitelistMode for use of {@link #mWhitelistedPackagesForUserTypes}. */ private @PackageWhitelistMode int getWhitelistMode() { final int runtimeMode = SystemProperties.getInt( PACKAGE_WHITELIST_MODE_PROP, USER_TYPE_PACKAGE_WHITELIST_MODE_DEVICE_DEFAULT); @@ -290,7 +290,7 @@ class UserSystemPackageInstaller { if (!pkg.isSystem()) { return; } - if (shouldInstallPackage(pkg, mWhitelitsedPackagesForUserTypes, + if (shouldInstallPackage(pkg, mWhitelistedPackagesForUserTypes, whitelistedPackages, isImplicitWhitelistMode, isSystemUser)) { // Although the whitelist uses manifest names, this function returns packageNames. installPackages.add(pkg.packageName); @@ -340,10 +340,10 @@ class UserSystemPackageInstaller { */ @VisibleForTesting @NonNull Set<String> getWhitelistedPackagesForUserType(int flags) { - Set<String> installablePkgs = new ArraySet<>(mWhitelitsedPackagesForUserTypes.size()); - for (int i = 0; i < mWhitelitsedPackagesForUserTypes.size(); i++) { - String pkgName = mWhitelitsedPackagesForUserTypes.keyAt(i); - int whitelistedUserTypes = mWhitelitsedPackagesForUserTypes.valueAt(i); + Set<String> installablePkgs = new ArraySet<>(mWhitelistedPackagesForUserTypes.size()); + for (int i = 0; i < mWhitelistedPackagesForUserTypes.size(); i++) { + String pkgName = mWhitelistedPackagesForUserTypes.keyAt(i); + int whitelistedUserTypes = mWhitelistedPackagesForUserTypes.valueAt(i); if ((flags & whitelistedUserTypes) != 0) { installablePkgs.add(pkgName); } @@ -360,7 +360,7 @@ class UserSystemPackageInstaller { * completely blacklists an AOSP app). */ private Set<String> getWhitelistedSystemPackages() { - return mWhitelitsedPackagesForUserTypes.keySet(); + return mWhitelistedPackagesForUserTypes.keySet(); } /** @@ -456,18 +456,28 @@ class UserSystemPackageInstaller { } void dump(PrintWriter pw) { - pw.print("Whitelisted packages per user type"); - final int size = mWhitelitsedPackagesForUserTypes.size(); + final String prefix = " "; + final int mode = getWhitelistMode(); + pw.println("Whitelisted packages per user type"); + pw.print(prefix); pw.print("Mode: "); + pw.print(mode); + pw.print(isEnforceMode(mode) ? " (enforced)" : ""); + pw.print(isLogMode(mode) ? " (logged)" : ""); + pw.print(isImplicitWhitelistMode(mode) ? " (implicit)" : ""); + pw.println(); + + final int size = mWhitelistedPackagesForUserTypes.size(); if (size == 0) { - pw.println(": N/A"); + pw.print(prefix); pw.println("No packages"); return; } - pw.println(" (" + size + " packages)"); + final String prefix2 = prefix + prefix; + pw.print(prefix); pw.print(size); pw.println(" packages:"); for (int i = 0; i < size; i++) { - final String pkgName = mWhitelitsedPackagesForUserTypes.keyAt(i); + final String pkgName = mWhitelistedPackagesForUserTypes.keyAt(i); final String whitelistedUserTypes = - UserInfo.flagsToString(mWhitelitsedPackagesForUserTypes.valueAt(i)); - pw.println(" " + pkgName + ": " + whitelistedUserTypes); + UserInfo.flagsToString(mWhitelistedPackagesForUserTypes.valueAt(i)); + pw.print(prefix2); pw.print(pkgName); pw.print(": "); pw.println(whitelistedUserTypes); } } } diff --git a/services/core/java/com/android/server/wm/ActivityRecord.java b/services/core/java/com/android/server/wm/ActivityRecord.java index b95d3272891d..d36004101b0e 100644 --- a/services/core/java/com/android/server/wm/ActivityRecord.java +++ b/services/core/java/com/android/server/wm/ActivityRecord.java @@ -4554,16 +4554,25 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A } /** - * Check if activity should be moved to RESUMED state. The activity: - * - should be eligible to be made active (see {@link #shouldMakeActive(ActivityRecord)}) - * - should be focusable + * Check if activity should be moved to RESUMED state. + * See {@link #shouldBeResumed(ActivityRecord)} * @param activeActivity the activity that is active or just completed pause action. We won't * resume if this activity is active. */ @VisibleForTesting boolean shouldResumeActivity(ActivityRecord activeActivity) { - return shouldMakeActive(activeActivity) && isFocusable() && !isState(RESUMED) - && getActivityStack().getVisibility(activeActivity) == STACK_VISIBILITY_VISIBLE; + return shouldBeResumed(activeActivity) && !isState(RESUMED); + } + + /** + * Check if activity should be RESUMED now. The activity: + * - should be eligible to be made active (see {@link #shouldMakeActive(ActivityRecord)}) + * - should be focusable + */ + private boolean shouldBeResumed(ActivityRecord activeActivity) { + return shouldMakeActive(activeActivity) && isFocusable() + && getActivityStack().getVisibility(activeActivity) == STACK_VISIBILITY_VISIBLE + && canResumeByCompat(); } /** @@ -6837,23 +6846,14 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A deferRelaunchUntilPaused = true; preserveWindowOnDeferredRelaunch = preserveWindow; return true; - } else if (mState == RESUMED) { - // Try to optimize this case: the configuration is changing and we need to restart - // the top, resumed activity. Instead of doing the normal handshaking, just say - // "restart!". + } else { if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, - "Config is relaunching resumed " + this); - + "Config is relaunching " + this); if (DEBUG_STATES && !visible) { - Slog.v(TAG_STATES, "Config is relaunching resumed invisible activity " + this + Slog.v(TAG_STATES, "Config is relaunching invisible activity " + this + " called by " + Debug.getCallers(4)); } - - relaunchActivityLocked(true /* andResume */, preserveWindow); - } else { - if (DEBUG_SWITCH || DEBUG_CONFIGURATION) Slog.v(TAG_CONFIGURATION, - "Config is relaunching non-resumed " + this); - relaunchActivityLocked(false /* andResume */, preserveWindow); + relaunchActivityLocked(preserveWindow); } // All done... tell the caller we weren't able to keep this activity around. @@ -6951,12 +6951,13 @@ final class ActivityRecord extends WindowToken implements WindowManagerService.A | CONFIG_SCREEN_LAYOUT)) != 0; } - void relaunchActivityLocked(boolean andResume, boolean preserveWindow) { + void relaunchActivityLocked(boolean preserveWindow) { if (mAtmService.mSuppressResizeConfigChanges && preserveWindow) { configChangeFlags = 0; return; } + final boolean andResume = shouldBeResumed(null /*activeActivity*/); List<ResultInfo> pendingResults = null; List<ReferrerIntent> pendingNewIntents = null; if (andResume) { diff --git a/services/core/java/com/android/server/wm/ActivityStack.java b/services/core/java/com/android/server/wm/ActivityStack.java index 9dade2cfb037..593318de34e1 100644 --- a/services/core/java/com/android/server/wm/ActivityStack.java +++ b/services/core/java/com/android/server/wm/ActivityStack.java @@ -1782,8 +1782,7 @@ class ActivityStack extends ConfigurationContainer { if (prev.deferRelaunchUntilPaused) { // Complete the deferred relaunch that was waiting for pause to complete. if (DEBUG_PAUSE) Slog.v(TAG_PAUSE, "Re-launching after pause: " + prev); - prev.relaunchActivityLocked(false /* andResume */, - prev.preserveWindowOnDeferredRelaunch); + prev.relaunchActivityLocked(prev.preserveWindowOnDeferredRelaunch); } else if (wasStopping) { // We are also stopping, the stop request must have gone soon after the pause. // We can't clobber it, because the stop confirmation will not be handled. diff --git a/services/core/jni/Android.bp b/services/core/jni/Android.bp index da355ea0ca3b..425b4b632971 100644 --- a/services/core/jni/Android.bp +++ b/services/core/jni/Android.bp @@ -23,7 +23,6 @@ cc_library_static { "com_android_server_AlarmManagerService.cpp", "com_android_server_am_BatteryStatsService.cpp", "com_android_server_connectivity_Vpn.cpp", - "com_android_server_connectivity_tethering_OffloadHardwareInterface.cpp", "com_android_server_ConsumerIrService.cpp", "com_android_server_devicepolicy_CryptoTestHelper.cpp", "com_android_server_HardwarePropertiesManagerService.cpp", @@ -54,6 +53,7 @@ cc_library_static { "com_android_server_am_LowMemDetector.cpp", "onload.cpp", ":lib_networkStatsFactory_native", + ":tethering-jni-srcs", ], include_dirs: [ 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/net/Android.bp b/services/net/Android.bp index e24dec562a46..c56ecd6e19e7 100644 --- a/services/net/Android.bp +++ b/services/net/Android.bp @@ -29,6 +29,7 @@ filegroup { "java/android/net/ConnectivityModuleConnector.java", "java/android/net/NetworkStackClient.java", "java/android/net/ip/InterfaceController.java", + "java/android/net/netlink/*.java", "java/android/net/util/InterfaceParams.java", "java/android/net/util/NetdService.java", "java/android/net/util/NetworkConstants.java", diff --git a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java index 184dc3dfed62..a47a5671ccb3 100644 --- a/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java +++ b/services/tests/servicestests/src/com/android/server/attention/AttentionManagerServiceTest.java @@ -16,6 +16,8 @@ package com.android.server.attention; +import static com.android.server.attention.AttentionManagerService.ATTENTION_CACHE_BUFFER_SIZE; + import static com.google.common.truth.Truth.assertThat; import static org.mockito.ArgumentMatchers.any; @@ -39,6 +41,8 @@ import android.service.attention.IAttentionService; import androidx.test.filters.SmallTest; import com.android.server.attention.AttentionManagerService.AttentionCheck; +import com.android.server.attention.AttentionManagerService.AttentionCheckCache; +import com.android.server.attention.AttentionManagerService.AttentionCheckCacheBuffer; import com.android.server.attention.AttentionManagerService.AttentionHandler; import com.android.server.attention.AttentionManagerService.UserState; @@ -56,11 +60,16 @@ public class AttentionManagerServiceTest { private AttentionManagerService mSpyAttentionManager; private UserState mSpyUserState; private final int mTimeout = 1000; - @Mock private AttentionCallbackInternal mMockAttentionCallbackInternal; - @Mock private AttentionHandler mMockHandler; - @Mock private IAttentionCallback mMockIAttentionCallback; - @Mock private IPowerManager mMockIPowerManager; - @Mock Context mContext; + @Mock + private AttentionCallbackInternal mMockAttentionCallbackInternal; + @Mock + private AttentionHandler mMockHandler; + @Mock + private IAttentionCallback mMockIAttentionCallback; + @Mock + private IPowerManager mMockIPowerManager; + @Mock + Context mContext; @Before public void setUp() throws RemoteException { @@ -140,12 +149,45 @@ public class AttentionManagerServiceTest { mSpyAttentionManager.onSwitchUser(userId); } + @Test + public void testAttentionCheckCacheBuffer_getLast_returnTheLastElement() { + AttentionCheckCacheBuffer buffer = new AttentionCheckCacheBuffer(); + buffer.add(new AttentionCheckCache(0, 0, 1L)); + AttentionCheckCache cache = new AttentionCheckCache(0, 0, 2L); + buffer.add(cache); + assertThat(buffer.getLast()).isEqualTo(cache); + } + + @Test + public void testAttentionCheckCacheBuffer_get_returnNullWhenOutOfBoundary() { + AttentionCheckCacheBuffer buffer = new AttentionCheckCacheBuffer(); + assertThat(buffer.get(1)).isNull(); + } + + @Test + public void testAttentionCheckCacheBuffer_get_handleCircularIndexing() { + AttentionCheckCacheBuffer buffer = new AttentionCheckCacheBuffer(); + AttentionCheckCache cache = new AttentionCheckCache(0L, 0, 1L); + // Insert SIZE+1 elements. + for (int i = 0; i <= ATTENTION_CACHE_BUFFER_SIZE; i++) { + if (i == 1) { + buffer.add(cache); + } else { + buffer.add(new AttentionCheckCache(0L, 0, i)); + } + } + // The element that was at index 1 should be at index 0 after inserting SIZE + 1 elements. + assertThat(buffer.get(0)).isEqualTo(cache); + } + private class MockIAttentionService implements IAttentionService { public void checkAttention(IAttentionCallback callback) throws RemoteException { callback.onSuccess(0, 0); } + public void cancelAttentionCheck(IAttentionCallback callback) { } + public IBinder asBinder() { return null; } diff --git a/telephony/java/android/telephony/CarrierConfigManager.java b/telephony/java/android/telephony/CarrierConfigManager.java index 010446492d16..dbada25f50a8 100755 --- a/telephony/java/android/telephony/CarrierConfigManager.java +++ b/telephony/java/android/telephony/CarrierConfigManager.java @@ -828,13 +828,6 @@ public class CarrierConfigManager { "disable_severe_when_extreme_disabled_bool"; /** - * The message expiration time in milliseconds for duplicate detection purposes. - * @hide - */ - public static final String KEY_MESSAGE_EXPIRATION_TIME_LONG = - "message_expiration_time_long"; - - /** * The data call retry configuration for different types of APN. * @hide */ @@ -3371,7 +3364,6 @@ public class CarrierConfigManager { sDefaults.putBoolean(KEY_BROADCAST_EMERGENCY_CALL_STATE_CHANGES_BOOL, false); sDefaults.putBoolean(KEY_ALWAYS_SHOW_EMERGENCY_ALERT_ONOFF_BOOL, false); sDefaults.putBoolean(KEY_DISABLE_SEVERE_WHEN_EXTREME_DISABLED_BOOL, true); - sDefaults.putLong(KEY_MESSAGE_EXPIRATION_TIME_LONG, 86400000L); sDefaults.putStringArray(KEY_CARRIER_DATA_CALL_RETRY_CONFIG_STRINGS, new String[]{ "default:default_randomization=2000,5000,10000,20000,40000,80000:5000,160000:5000," + "320000:5000,640000:5000,1280000:5000,1800000:5000", diff --git a/telephony/java/android/telephony/SubscriptionManager.java b/telephony/java/android/telephony/SubscriptionManager.java index b5e91d0bad85..75e4fec97825 100644 --- a/telephony/java/android/telephony/SubscriptionManager.java +++ b/telephony/java/android/telephony/SubscriptionManager.java @@ -2371,12 +2371,10 @@ public class SubscriptionManager { * @param plans the list of plans. The first plan is always the primary and * most important plan. Any additional plans are secondary and * may not be displayed or used by decision making logic. - * The list of all plans must meet the requirements defined in - * {@link SubscriptionPlan.Builder#setNetworkTypes(int[])}. * @throws SecurityException if the caller doesn't meet the requirements * outlined above. * @throws IllegalArgumentException if plans don't meet the requirements - * mentioned above. + * defined in {@link SubscriptionPlan}. */ public void setSubscriptionPlans(int subId, @NonNull List<SubscriptionPlan> plans) { try { diff --git a/telephony/java/android/telephony/SubscriptionPlan.java b/telephony/java/android/telephony/SubscriptionPlan.java index e24eb2696c6c..28a5c2086ede 100644 --- a/telephony/java/android/telephony/SubscriptionPlan.java +++ b/telephony/java/android/telephony/SubscriptionPlan.java @@ -44,6 +44,14 @@ import java.util.Objects; * as explaining how much mobile data they have remaining, and what will happen * when they run out. * + * If specifying network types, the developer must supply at least one plan + * that applies to all network types (default), and all additional plans + * may not include a particular network type more than once. + * This is enforced by {@link SubscriptionManager} when setting the plans. + * + * Plan selection will prefer plans that have specific network types defined + * over plans that apply to all network types. + * * @see SubscriptionManager#setSubscriptionPlans(int, java.util.List) * @see SubscriptionManager#getSubscriptionPlans(int) */ @@ -213,7 +221,7 @@ public final class SubscriptionPlan implements Parcelable { /** * Return an array containing all {@link NetworkType}s this SubscriptionPlan applies to. - * A null array means this SubscriptionPlan applies to all network types. + * A null value means this SubscriptionPlan applies to all network types. */ public @Nullable @NetworkType int[] getNetworkTypes() { return networkTypes; @@ -372,20 +380,13 @@ public final class SubscriptionPlan implements Parcelable { /** * Set the network types this SubscriptionPlan applies to. - * The developer must supply at least one plan that applies to all network types (default), - * and all additional plans may not include a particular network type more than once. - * Plan selection will prefer plans that have specific network types defined - * over plans that apply to all network types. * * @param networkTypes a set of all {@link NetworkType}s that apply to this plan. - * A null value or empty array means the plan applies to all network types. + * A null value means the plan applies to all network types, + * and an empty array means the plan applies to no network types. */ public @NonNull Builder setNetworkTypes(@Nullable @NetworkType int[] networkTypes) { - if (networkTypes == null || networkTypes.length == 0) { - plan.networkTypes = null; - } else { - plan.networkTypes = networkTypes; - } + plan.networkTypes = networkTypes; return this; } } diff --git a/telephony/java/android/telephony/TelephonyManager.java b/telephony/java/android/telephony/TelephonyManager.java index 0c663f85b99c..4eb5a362efae 100644 --- a/telephony/java/android/telephony/TelephonyManager.java +++ b/telephony/java/android/telephony/TelephonyManager.java @@ -9567,18 +9567,37 @@ public class TelephonyManager { } /** - * Resets Telephony and IMS settings back to factory defaults. + * Resets telephony manager settings back to factory defaults. * * @hide */ - @SystemApi - @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL) public void factoryReset(int subId) { try { Log.d(TAG, "factoryReset: subId=" + subId); ITelephony telephony = getITelephony(); - if (telephony != null) + if (telephony != null) { telephony.factoryReset(subId); + } + } catch (RemoteException e) { + } + } + + + /** + * Resets Telephony and IMS settings back to factory defaults only for the subscription + * associated with this instance. + * @see #createForSubscriptionId(int) + * @hide + */ + @SystemApi + @RequiresPermission(Manifest.permission.CONNECTIVITY_INTERNAL) + public void resetSettings() { + try { + Log.d(TAG, "resetSettings: subId=" + getSubId()); + ITelephony telephony = getITelephony(); + if (telephony != null) { + telephony.factoryReset(getSubId()); + } } catch (RemoteException e) { } } diff --git a/telephony/java/android/telephony/ims/ImsMmTelManager.java b/telephony/java/android/telephony/ims/ImsMmTelManager.java index 7cafa1ea068c..9fc8e7563a81 100644 --- a/telephony/java/android/telephony/ims/ImsMmTelManager.java +++ b/telephony/java/android/telephony/ims/ImsMmTelManager.java @@ -254,8 +254,8 @@ public class ImsMmTelManager implements RegistrationManager { * the {@link ImsService} associated with the subscription is not available. This can happen if * the service crashed, for example. See {@link ImsException#getCode()} for a more detailed * reason. - * @deprecated Use {@link #registerImsRegistrationCallback( - * RegistrationManager.RegistrationCallback, Executor)} instead. + * @deprecated Use {@link RegistrationManager#registerImsRegistrationCallback(Executor, + * RegistrationManager.RegistrationCallback)} instead. */ @Deprecated @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) @@ -285,9 +285,8 @@ public class ImsMmTelManager implements RegistrationManager { /**{@inheritDoc}*/ @Override @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) - public void registerImsRegistrationCallback( - @NonNull RegistrationManager.RegistrationCallback c, - @NonNull @CallbackExecutor Executor executor) throws ImsException { + public void registerImsRegistrationCallback(@NonNull @CallbackExecutor Executor executor, + @NonNull RegistrationManager.RegistrationCallback c) throws ImsException { if (c == null) { throw new IllegalArgumentException("Must include a non-null RegistrationCallback."); } @@ -348,8 +347,8 @@ public class ImsMmTelManager implements RegistrationManager { /**{@inheritDoc}*/ @Override @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) - public void getRegistrationState(@NonNull @ImsRegistrationState Consumer<Integer> stateCallback, - @NonNull @CallbackExecutor Executor executor) { + public void getRegistrationState(@NonNull @CallbackExecutor Executor executor, + @NonNull @ImsRegistrationState Consumer<Integer> stateCallback) { if (stateCallback == null) { throw new IllegalArgumentException("Must include a non-null callback."); } @@ -371,9 +370,9 @@ public class ImsMmTelManager implements RegistrationManager { /**{@inheritDoc}*/ @Override @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) - public void getRegistrationTransportType( - @NonNull @AccessNetworkConstants.TransportType Consumer<Integer> transportTypeCallback, - @NonNull @CallbackExecutor Executor executor) { + public void getRegistrationTransportType(@NonNull @CallbackExecutor Executor executor, + @NonNull @AccessNetworkConstants.TransportType + Consumer<Integer> transportTypeCallback) { if (transportTypeCallback == null) { throw new IllegalArgumentException("Must include a non-null callback."); } @@ -607,17 +606,17 @@ public class ImsMmTelManager implements RegistrationManager { * {@link CarrierConfigManager#ACTION_CARRIER_CONFIG_CHANGED} broadcast for this subscription. * @param capability The capability that is being queried for support on the carrier network. * @param transportType The transport type of the capability to check support for. + * @param executor The executor that the callback will be called with. * @param callback A consumer containing a Boolean result specifying whether or not the * capability is supported on this carrier network for the transport specified. - * @param executor The executor that the callback will be called with. * @throws ImsException if the subscription is no longer valid or the IMS service is not * available. */ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) public void isSupported(@MmTelFeature.MmTelCapabilities.MmTelCapability int capability, @AccessNetworkConstants.TransportType int transportType, - @NonNull Consumer<Boolean> callback, - @NonNull @CallbackExecutor Executor executor) throws ImsException { + @NonNull @CallbackExecutor Executor executor, + @NonNull Consumer<Boolean> callback) throws ImsException { if (callback == null) { throw new IllegalArgumentException("Must include a non-null Consumer."); } diff --git a/telephony/java/android/telephony/ims/ImsRcsManager.java b/telephony/java/android/telephony/ims/ImsRcsManager.java index 25bd1caea431..6432016ac2c3 100644 --- a/telephony/java/android/telephony/ims/ImsRcsManager.java +++ b/telephony/java/android/telephony/ims/ImsRcsManager.java @@ -141,8 +141,8 @@ public class ImsRcsManager implements RegistrationManager { /**{@inheritDoc}*/ @Override public void registerImsRegistrationCallback( - @NonNull RegistrationManager.RegistrationCallback c, - @NonNull @CallbackExecutor Executor executor) + @NonNull @CallbackExecutor Executor executor, + @NonNull RegistrationCallback c) throws ImsException { if (c == null) { throw new IllegalArgumentException("Must include a non-null RegistrationCallback."); @@ -168,8 +168,8 @@ public class ImsRcsManager implements RegistrationManager { /**{@inheritDoc}*/ @Override - public void getRegistrationState(@NonNull @ImsRegistrationState Consumer<Integer> stateCallback, - @NonNull @CallbackExecutor Executor executor) { + public void getRegistrationState(@NonNull @CallbackExecutor Executor executor, + @NonNull @ImsRegistrationState Consumer<Integer> stateCallback) { if (stateCallback == null) { throw new IllegalArgumentException("Must include a non-null stateCallback."); } @@ -182,9 +182,9 @@ public class ImsRcsManager implements RegistrationManager { /**{@inheritDoc}*/ @Override - public void getRegistrationTransportType( - @NonNull @AccessNetworkConstants.TransportType Consumer<Integer> transportTypeCallback, - @NonNull @CallbackExecutor Executor executor) { + public void getRegistrationTransportType(@NonNull @CallbackExecutor Executor executor, + @NonNull @AccessNetworkConstants.TransportType + Consumer<Integer> transportTypeCallback) { if (transportTypeCallback == null) { throw new IllegalArgumentException("Must include a non-null transportTypeCallback."); } diff --git a/telephony/java/android/telephony/ims/RegistrationManager.java b/telephony/java/android/telephony/ims/RegistrationManager.java index b4c11e3c32a1..23402b88f3b1 100644 --- a/telephony/java/android/telephony/ims/RegistrationManager.java +++ b/telephony/java/android/telephony/ims/RegistrationManager.java @@ -90,7 +90,7 @@ public interface RegistrationManager { /** * Callback class for receiving IMS network Registration callback events. - * @see #registerImsRegistrationCallback(RegistrationCallback, Executor) + * @see #registerImsRegistrationCallback(Executor, RegistrationCallback) * @see #unregisterImsRegistrationCallback(RegistrationCallback) */ class RegistrationCallback { @@ -229,8 +229,8 @@ public interface RegistrationManager { * When the callback is registered, it will initiate the callback c to be called with the * current registration state. * - * @param c The {@link RegistrationCallback} to be added. * @param executor The executor the callback events should be run on. + * @param c The {@link RegistrationCallback} to be added. * @see #unregisterImsRegistrationCallback(RegistrationCallback) * @throws ImsException if the subscription associated with this callback is valid, but * the {@link ImsService} associated with the subscription is not available. This can happen if @@ -238,8 +238,8 @@ public interface RegistrationManager { * reason. */ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) - void registerImsRegistrationCallback(@NonNull RegistrationCallback c, - @NonNull @CallbackExecutor Executor executor) throws ImsException; + void registerImsRegistrationCallback(@NonNull @CallbackExecutor Executor executor, + @NonNull RegistrationCallback c) throws ImsException; /** * Removes an existing {@link RegistrationCallback}. @@ -250,36 +250,36 @@ public interface RegistrationManager { * * @param c The {@link RegistrationCallback} to be removed. * @see SubscriptionManager.OnSubscriptionsChangedListener - * @see #registerImsRegistrationCallback(RegistrationCallback, Executor) + * @see #registerImsRegistrationCallback(Executor, RegistrationCallback) */ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) void unregisterImsRegistrationCallback(@NonNull RegistrationCallback c); /** * Gets the registration state of the IMS service. - * @param stateCallback A callback called on the supplied {@link Executor} that will contain the - * registration state of the IMS service, which will be one of the - * following: {@link #REGISTRATION_STATE_NOT_REGISTERED}, - * {@link #REGISTRATION_STATE_REGISTERING}, or - * {@link #REGISTRATION_STATE_REGISTERED}. * @param executor The {@link Executor} that will be used to call the IMS registration state * callback. + * @param stateCallback A callback called on the supplied {@link Executor} that will contain the + * registration state of the IMS service, which will be one of the + * following: {@link #REGISTRATION_STATE_NOT_REGISTERED}, + * {@link #REGISTRATION_STATE_REGISTERING}, or + * {@link #REGISTRATION_STATE_REGISTERED}. */ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) - void getRegistrationState(@NonNull @ImsRegistrationState Consumer<Integer> stateCallback, - @NonNull @CallbackExecutor Executor executor); + void getRegistrationState(@NonNull @CallbackExecutor Executor executor, + @NonNull @ImsRegistrationState Consumer<Integer> stateCallback); /** * Gets the Transport Type associated with the current IMS registration. - * @param transportTypeCallback The transport type associated with the current IMS registration, - * which will be one of following: - * {@link AccessNetworkConstants#TRANSPORT_TYPE_WWAN}, - * {@link AccessNetworkConstants#TRANSPORT_TYPE_WLAN}, or - * {@link AccessNetworkConstants#TRANSPORT_TYPE_INVALID}. * @param executor The {@link Executor} that will be used to call the transportTypeCallback. + * @param transportTypeCallback The transport type associated with the current IMS registration, + * which will be one of following: + * {@link AccessNetworkConstants#TRANSPORT_TYPE_WWAN}, + * {@link AccessNetworkConstants#TRANSPORT_TYPE_WLAN}, or + * {@link AccessNetworkConstants#TRANSPORT_TYPE_INVALID}. */ @RequiresPermission(Manifest.permission.READ_PRIVILEGED_PHONE_STATE) void getRegistrationTransportType( - @NonNull @AccessNetworkConstants.TransportType Consumer<Integer> transportTypeCallback, - @NonNull @CallbackExecutor Executor executor); + @NonNull @CallbackExecutor Executor executor, + @NonNull @AccessNetworkConstants.TransportType Consumer<Integer> transportTypeCallback); } diff --git a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java index ead4a28beff4..74aaec1eee34 100644 --- a/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java +++ b/tests/BootImageProfileTest/src/com/android/bootimageprofile/BootImageProfileTest.java @@ -108,13 +108,18 @@ public class BootImageProfileTest implements IDeviceTest { // Test the profile contents contain common methods for core-oj that would normally be AOT // compiled. res = mTestDevice.executeShellCommand("profman --dump-classes-and-methods --profile-file=" - + SYSTEM_SERVER_PROFILE + " --apk=/apex/com.android.art/javalib/core-oj.jar"); + + SYSTEM_SERVER_PROFILE + " --apk=/apex/com.android.art/javalib/core-oj.jar" + + " --apk=/system/framework/services.jar"); boolean sawObjectInit = false; + boolean sawPmInit = false; for (String line : res.split("\n")) { if (line.contains("Ljava/lang/Object;-><init>()V")) { sawObjectInit = true; + } else if (line.contains("Lcom/android/server/pm/PackageManagerService;-><init>")) { + sawPmInit = true; } } assertTrue("Did not see Object.<init> in " + res, sawObjectInit); + assertTrue("Did not see PackageManagerService.<init> in " + res, sawPmInit); } } |