diff options
Diffstat (limited to 'core/java/android')
81 files changed, 1743 insertions, 1080 deletions
diff --git a/core/java/android/accounts/AbstractAccountAuthenticator.java b/core/java/android/accounts/AbstractAccountAuthenticator.java index dbc9051..3e4a66d 100644 --- a/core/java/android/accounts/AbstractAccountAuthenticator.java +++ b/core/java/android/accounts/AbstractAccountAuthenticator.java @@ -108,6 +108,14 @@ import java.util.Arrays; public abstract class AbstractAccountAuthenticator { private static final String TAG = "AccountAuthenticator"; + /** + * Bundle key used for the {@code long} expiration time (in millis from the unix epoch) of the + * associated auth token. + * + * @see #getAuthToken + */ + public static final String KEY_CUSTOM_TOKEN_EXPIRY = "android.accounts.expiry"; + private final Context mContext; public AbstractAccountAuthenticator(Context context) { @@ -115,6 +123,7 @@ public abstract class AbstractAccountAuthenticator { } private class Transport extends IAccountAuthenticator.Stub { + @Override public void addAccount(IAccountAuthenticatorResponse response, String accountType, String authTokenType, String[] features, Bundle options) throws RemoteException { @@ -140,6 +149,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void confirmCredentials(IAccountAuthenticatorResponse response, Account account, Bundle options) throws RemoteException { if (Log.isLoggable(TAG, Log.VERBOSE)) { @@ -162,6 +172,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void getAuthTokenLabel(IAccountAuthenticatorResponse response, String authTokenType) throws RemoteException { @@ -184,6 +195,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void getAuthToken(IAccountAuthenticatorResponse response, Account account, String authTokenType, Bundle loginOptions) throws RemoteException { @@ -209,6 +221,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void updateCredentials(IAccountAuthenticatorResponse response, Account account, String authTokenType, Bundle loginOptions) throws RemoteException { if (Log.isLoggable(TAG, Log.VERBOSE)) { @@ -234,6 +247,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void editProperties(IAccountAuthenticatorResponse response, String accountType) throws RemoteException { checkBinderPermission(); @@ -248,6 +262,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void hasFeatures(IAccountAuthenticatorResponse response, Account account, String[] features) throws RemoteException { checkBinderPermission(); @@ -262,6 +277,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void getAccountRemovalAllowed(IAccountAuthenticatorResponse response, Account account) throws RemoteException { checkBinderPermission(); @@ -276,6 +292,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void getAccountCredentialsForCloning(IAccountAuthenticatorResponse response, Account account) throws RemoteException { checkBinderPermission(); @@ -291,6 +308,7 @@ public abstract class AbstractAccountAuthenticator { } } + @Override public void addAccountFromCredentials(IAccountAuthenticatorResponse response, Account account, Bundle accountCredentials) throws RemoteException { @@ -410,21 +428,42 @@ public abstract class AbstractAccountAuthenticator { public abstract Bundle confirmCredentials(AccountAuthenticatorResponse response, Account account, Bundle options) throws NetworkErrorException; + /** - * Gets the authtoken for an account. + * Gets an authtoken for an account. + * + * If not {@code null}, the resultant {@link Bundle} will contain different sets of keys + * depending on whether a token was successfully issued and, if not, whether one + * could be issued via some {@link android.app.Activity}. + * <p> + * If a token cannot be provided without some additional activity, the Bundle should contain + * {@link AccountManager#KEY_INTENT} with an associated {@link Intent}. On the other hand, if + * there is no such activity, then a Bundle containing + * {@link AccountManager#KEY_ERROR_CODE} and {@link AccountManager#KEY_ERROR_MESSAGE} should be + * returned. + * <p> + * If a token can be successfully issued, the implementation should return the + * {@link AccountManager#KEY_ACCOUNT_NAME} and {@link AccountManager#KEY_ACCOUNT_TYPE} of the + * account associated with the token as well as the {@link AccountManager#KEY_AUTHTOKEN}. In + * addition {@link AbstractAccountAuthenticator} implementations that declare themselves + * {@code android:customTokens=true} may also provide a non-negative {@link + * #KEY_CUSTOM_TOKEN_EXPIRY} long value containing the expiration timestamp of the expiration + * time (in millis since the unix epoch). + * <p> + * Implementers should assume that tokens will be cached on the basis of account and + * authTokenType. The system may ignore the contents of the supplied options Bundle when + * determining to re-use a cached token. Furthermore, implementers should assume a supplied + * expiration time will be treated as non-binding advice. + * <p> + * Finally, note that for android:customTokens=false authenticators, tokens are cached + * indefinitely until some client calls {@link + * AccountManager#invalidateAuthToken(String,String)}. + * * @param response to send the result back to the AccountManager, will never be null * @param account the account whose credentials are to be retrieved, will never be null * @param authTokenType the type of auth token to retrieve, will never be null * @param options a Bundle of authenticator-specific options, may be null - * @return a Bundle result or null if the result is to be returned via the response. The result - * will contain either: - * <ul> - * <li> {@link AccountManager#KEY_INTENT}, or - * <li> {@link AccountManager#KEY_ACCOUNT_NAME}, {@link AccountManager#KEY_ACCOUNT_TYPE}, - * and {@link AccountManager#KEY_AUTHTOKEN}, or - * <li> {@link AccountManager#KEY_ERROR_CODE} and {@link AccountManager#KEY_ERROR_MESSAGE} to - * indicate an error - * </ul> + * @return a Bundle result or null if the result is to be returned via the response. * @throws NetworkErrorException if the authenticator could not honor the request due to a * network error */ @@ -518,6 +557,7 @@ public abstract class AbstractAccountAuthenticator { public Bundle getAccountCredentialsForCloning(final AccountAuthenticatorResponse response, final Account account) throws NetworkErrorException { new Thread(new Runnable() { + @Override public void run() { Bundle result = new Bundle(); result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false); @@ -543,6 +583,7 @@ public abstract class AbstractAccountAuthenticator { Account account, Bundle accountCredentials) throws NetworkErrorException { new Thread(new Runnable() { + @Override public void run() { Bundle result = new Bundle(); result.putBoolean(AccountManager.KEY_BOOLEAN_RESULT, false); diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java index 49f5099..073fefc 100644 --- a/core/java/android/app/Activity.java +++ b/core/java/android/app/Activity.java @@ -3746,6 +3746,7 @@ public class Activity extends ContextThemeWrapper * * @see #onRequestPermissionsResult(int, String[], int[]) * @see #checkSelfPermission(String) + * @see #shouldShowRequestPermissionRationale(String) */ public final void requestPermissions(@NonNull String[] permissions, int requestCode) { Intent intent = getPackageManager().buildRequestPermissionsIntent(permissions); @@ -3770,6 +3771,30 @@ public class Activity extends ContextThemeWrapper } /** + * Gets whether you should show UI with rationale for requesting a permission. + * You should do this only if you do not have the permission and the context in + * which the permission is requested does not clearly communicate to the user + * what would be the benefit from granting this permission. + * <p> + * For example, if you write a camera app, requesting the camera permission + * would be expected by the user and no rationale for why it is requested is + * needed. If however, the app needs location for tagging photos then a non-tech + * savvy user may wonder how location is related to taking photos. In this case + * you may choose to show UI with rationale of requesting this permission. + * </p> + * + * @param permission A permission your app wants to request. + * @return Whether you can show permission rationale UI. + * + * @see #checkSelfPermission(String) + * @see #requestPermissions(String[], int) + * @see #onRequestPermissionsResult(int, String[], int[]) + */ + public boolean shouldShowRequestPermissionRationale(@NonNull String permission) { + return getPackageManager().shouldShowRequestPermissionRationale(permission); + } + + /** * Same as calling {@link #startActivityForResult(Intent, int, Bundle)} * with no options. * diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java index 04f6430..41e3db8 100644 --- a/core/java/android/app/ApplicationPackageManager.java +++ b/core/java/android/app/ApplicationPackageManager.java @@ -486,6 +486,16 @@ final class ApplicationPackageManager extends PackageManager { } @Override + public boolean shouldShowRequestPermissionRationale(String permission) { + try { + return mPM.shouldShowRequestPermissionRationale(permission, + mContext.getPackageName(), mContext.getUserId()); + } catch (RemoteException e) { + throw new RuntimeException("Package manager has died", e); + } + } + + @Override public int checkSignatures(String pkg1, String pkg2) { try { return mPM.checkSignatures(pkg1, pkg2); diff --git a/core/java/android/app/VoiceInteractor.java b/core/java/android/app/VoiceInteractor.java index a412952..ba27c54 100644 --- a/core/java/android/app/VoiceInteractor.java +++ b/core/java/android/app/VoiceInteractor.java @@ -510,7 +510,7 @@ public class VoiceInteractor { } /** - * Execute an extended command using the trusted system VoiceInteractionService. + * Execute a vendor-specific command using the trusted system VoiceInteractionService. * This allows an Activity to request additional information from the user needed to * complete an action (e.g. booking a table might have several possible times that the * user could select from or an app might need the user to agree to a terms of service). diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java index 978b4bc..55eaf27 100644 --- a/core/java/android/app/admin/DevicePolicyManager.java +++ b/core/java/android/app/admin/DevicePolicyManager.java @@ -16,6 +16,8 @@ package android.app.admin; +import android.annotation.NonNull; +import android.annotation.Nullable; import android.annotation.SdkConstant; import android.annotation.SdkConstant.SdkConstantType; import android.annotation.SystemApi; @@ -76,7 +78,7 @@ import java.util.List; * <h3>Developer Guides</h3> * <p>For more information about managing policies for device administration, read the * <a href="{@docRoot}guide/topics/admin/device-admin.html">Device Administration</a> - * developer guide.</p> + * developer guide. * </div> */ public class DevicePolicyManager { @@ -122,15 +124,45 @@ public class DevicePolicyManager { * * <p> If provisioning fails, the managedProfile is removed so the device returns to its * previous state. - * - * <p>Input: Nothing.</p> - * <p>Output: Nothing</p> */ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) public static final String ACTION_PROVISION_MANAGED_PROFILE = "android.app.action.PROVISION_MANAGED_PROFILE"; /** + * Activity action: Starts the provisioning flow which sets up a managed device. + * Must be started with {@link android.app.Activity#startActivityForResult(Intent, int)}. + * + * <p> During device owner provisioning a device admin app is set as the owner of the device. + * A device owner has full control over the device. The device owner can not be modified by the + * user. + * + * <p> A typical use case would be a device that is owned by a company, but used by either an + * employee or client. + * + * <p> An intent with this action can be sent only on an unprovisioned device. + * It is possible to check if the device is provisioned or not by looking at + * {@link android.provider.Settings.Global#DEVICE_PROVISIONED} + * + * The intent contains the following extras: + * <ul> + * <li>{@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}</li> + * <li>{@link #EXTRA_PROVISIONING_SKIP_ENCRYPTION}, optional</li> + * <li>{@link #EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED}, optional</li> + * </ul> + * + * <p> When device owner provisioning has completed, an intent of the type + * {@link DeviceAdminReceiver#ACTION_PROFILE_PROVISIONING_COMPLETE} is broadcast to the + * device owner. + * + * <p> If provisioning fails, the device is factory reset. + * + */ + @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION) + public static final String ACTION_PROVISION_MANAGED_DEVICE + = "android.app.action.PROVISION_MANAGED_DEVICE"; + + /** * A {@link android.os.Parcelable} extra of type {@link android.os.PersistableBundle} that allows * a mobile device management application that starts managed profile provisioning to pass data * to itself on the managed profile when provisioning completes. The mobile device management @@ -155,7 +187,7 @@ public class DevicePolicyManager { * message containing an NFC record with MIME type {@link #MIME_TYPE_PROVISIONING_NFC}. * * <p> When this extra is set, the application must have exactly one device admin receiver. - * This receiver will be set as the profile or device owner and active admin.</p> + * This receiver will be set as the profile or device owner and active admin. * @see DeviceAdminReceiver * @deprecated Use {@link #EXTRA_PROVISIONING_DEVICE_ADMIN_COMPONENT_NAME}. This extra is still @@ -170,11 +202,13 @@ public class DevicePolicyManager { * application that will be set as the profile owner or device owner and active admin. * * <p>If an application starts provisioning directly via an intent with action - * {@link #ACTION_PROVISION_MANAGED_PROFILE} the package name of this component has to match the - * package name of the application that started provisioning. + * {@link #ACTION_PROVISION_MANAGED_PROFILE} or + * {@link #ACTION_PROVISION_MANAGED_DEVICE} the package name of this + * component has to match the package name of the application that started provisioning. * * <p>This component is set as device owner and active admin when device owner provisioning is - * started by an NFC message containing an NFC record with MIME type + * started by an intent with action {@link #ACTION_PROVISION_MANAGED_DEVICE} or by an NFC + * message containing an NFC record with MIME type * {@link #MIME_TYPE_PROVISIONING_NFC_V2}. For the NFC record, the component name should be * flattened to a string, via {@link ComponentName#flattenToShortString()}. * @@ -212,10 +246,10 @@ public class DevicePolicyManager { /** * A Boolean extra that can be used by the mobile device management application to skip the - * disabling of system apps during provisioning when set to <code>true</code>. + * disabling of system apps during provisioning when set to {@code true}. * - * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} that starts device owner - * provisioning via an NFC bump. + * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC} or an intent with action + * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning. */ public static final String EXTRA_PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED = "android.app.extra.PROVISIONING_LEAVE_ALL_SYSTEM_APPS_ENABLED"; @@ -415,8 +449,8 @@ public class DevicePolicyManager { * A boolean extra indicating whether device encryption can be skipped as part of Device Owner * provisioning. * - * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} that starts device owner - * provisioning via an NFC bump. + * <p>Use in an NFC record with {@link #MIME_TYPE_PROVISIONING_NFC_V2} or an intent with action + * {@link #ACTION_PROVISION_MANAGED_DEVICE} that starts device owner provisioning. */ public static final String EXTRA_PROVISIONING_SKIP_ENCRYPTION = "android.app.extra.PROVISIONING_SKIP_ENCRYPTION"; @@ -610,8 +644,7 @@ public class DevicePolicyManager { * * <p>During device owner provisioning a device admin app is set as the owner of the device. * A device owner has full control over the device. The device owner can not be modified by the - * user and the only way of resetting the device is if the device owner app calls a factory - * reset. + * user. * * <p> A typical use case would be a device that is owned by a company, but used by either an * employee or client. @@ -644,9 +677,6 @@ public class DevicePolicyManager { * * <p> * If provisioning fails, the device is factory reset. - * - * <p>Input: Nothing.</p> - * <p>Output: Nothing</p> */ public static final String MIME_TYPE_PROVISIONING_NFC_V2 = "application/com.android.managedprovisioning.v2"; @@ -847,18 +877,18 @@ public class DevicePolicyManager { * Return true if the given administrator component is currently * active (enabled) in the system. */ - public boolean isAdminActive(ComponentName who) { - return isAdminActiveAsUser(who, UserHandle.myUserId()); + public boolean isAdminActive(@NonNull ComponentName admin) { + return isAdminActiveAsUser(admin, UserHandle.myUserId()); } /** * @see #isAdminActive(ComponentName) * @hide */ - public boolean isAdminActiveAsUser(ComponentName who, int userId) { + public boolean isAdminActiveAsUser(@NonNull ComponentName admin, int userId) { if (mService != null) { try { - return mService.isAdminActive(who, userId); + return mService.isAdminActive(admin, userId); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -870,10 +900,10 @@ public class DevicePolicyManager { * for the user. * @hide */ - public boolean isRemovingAdmin(ComponentName who, int userId) { + public boolean isRemovingAdmin(@NonNull ComponentName admin, int userId) { if (mService != null) { try { - return mService.isRemovingAdmin(who, userId); + return mService.isRemovingAdmin(admin, userId); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -883,8 +913,8 @@ public class DevicePolicyManager { /** - * Return a list of all currently active device administrator's component - * names. Note that if there are no administrators than null may be + * Return a list of all currently active device administrators' component + * names. If there are no administrators {@code null} may be * returned. */ public List<ComponentName> getActiveAdmins() { @@ -928,10 +958,10 @@ public class DevicePolicyManager { * try to remove someone else's component, a security exception will be * thrown. */ - public void removeActiveAdmin(ComponentName who) { + public void removeActiveAdmin(@NonNull ComponentName admin) { if (mService != null) { try { - mService.removeActiveAdmin(who, UserHandle.myUserId()); + mService.removeActiveAdmin(admin, UserHandle.myUserId()); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -940,14 +970,14 @@ public class DevicePolicyManager { /** * Returns true if an administrator has been granted a particular device policy. This can - * be used to check if the administrator was activated under an earlier set of policies, + * be used to check whether the administrator was activated under an earlier set of policies, * but requires additional policies after an upgrade. * * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Must be * an active administrator, or an exception will be thrown. * @param usesPolicy Which uses-policy to check, as defined in {@link DeviceAdminInfo}. */ - public boolean hasGrantedPolicy(ComponentName admin, int usesPolicy) { + public boolean hasGrantedPolicy(@NonNull ComponentName admin, int usesPolicy) { if (mService != null) { try { return mService.hasGrantedPolicy(admin, usesPolicy, UserHandle.myUserId()); @@ -1048,7 +1078,7 @@ public class DevicePolicyManager { * {@link #PASSWORD_QUALITY_ALPHABETIC}, {@link #PASSWORD_QUALITY_ALPHANUMERIC} * or {@link #PASSWORD_QUALITY_COMPLEX}. */ - public void setPasswordQuality(ComponentName admin, int quality) { + public void setPasswordQuality(@NonNull ComponentName admin, int quality) { if (mService != null) { try { mService.setPasswordQuality(admin, quality); @@ -1061,15 +1091,15 @@ public class DevicePolicyManager { /** * Retrieve the current minimum password quality for all admins of this user * and its profiles or a particular one. - * @param admin The name of the admin component to check, or null to aggregate + * @param admin The name of the admin component to check, or {@code null} to aggregate * all admins. */ - public int getPasswordQuality(ComponentName admin) { + public int getPasswordQuality(@Nullable ComponentName admin) { return getPasswordQuality(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordQuality(ComponentName admin, int userHandle) { + public int getPasswordQuality(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordQuality(admin, userHandle); @@ -1101,7 +1131,7 @@ public class DevicePolicyManager { * @param length The new desired minimum password length. A value of 0 * means there is no restriction. */ - public void setPasswordMinimumLength(ComponentName admin, int length) { + public void setPasswordMinimumLength(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumLength(admin, length); @@ -1114,15 +1144,15 @@ public class DevicePolicyManager { /** * Retrieve the current minimum password length for all admins of this * user and its profiles or a particular one. - * @param admin The name of the admin component to check, or null to aggregate + * @param admin The name of the admin component to check, or {@code null} to aggregate * all admins. */ - public int getPasswordMinimumLength(ComponentName admin) { + public int getPasswordMinimumLength(@Nullable ComponentName admin) { return getPasswordMinimumLength(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumLength(ComponentName admin, int userHandle) { + public int getPasswordMinimumLength(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumLength(admin, userHandle); @@ -1155,7 +1185,7 @@ public class DevicePolicyManager { * required in the password. A value of 0 means there is no * restriction. */ - public void setPasswordMinimumUpperCase(ComponentName admin, int length) { + public void setPasswordMinimumUpperCase(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumUpperCase(admin, length); @@ -1173,17 +1203,17 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of upper case letters required in the * password. */ - public int getPasswordMinimumUpperCase(ComponentName admin) { + public int getPasswordMinimumUpperCase(@Nullable ComponentName admin) { return getPasswordMinimumUpperCase(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumUpperCase(ComponentName admin, int userHandle) { + public int getPasswordMinimumUpperCase(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumUpperCase(admin, userHandle); @@ -1216,7 +1246,7 @@ public class DevicePolicyManager { * required in the password. A value of 0 means there is no * restriction. */ - public void setPasswordMinimumLowerCase(ComponentName admin, int length) { + public void setPasswordMinimumLowerCase(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumLowerCase(admin, length); @@ -1234,17 +1264,17 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of lower case letters required in the * password. */ - public int getPasswordMinimumLowerCase(ComponentName admin) { + public int getPasswordMinimumLowerCase(@Nullable ComponentName admin) { return getPasswordMinimumLowerCase(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumLowerCase(ComponentName admin, int userHandle) { + public int getPasswordMinimumLowerCase(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumLowerCase(admin, userHandle); @@ -1276,7 +1306,7 @@ public class DevicePolicyManager { * @param length The new desired minimum number of letters required in the * password. A value of 0 means there is no restriction. */ - public void setPasswordMinimumLetters(ComponentName admin, int length) { + public void setPasswordMinimumLetters(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumLetters(admin, length); @@ -1293,16 +1323,16 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of letters required in the password. */ - public int getPasswordMinimumLetters(ComponentName admin) { + public int getPasswordMinimumLetters(@Nullable ComponentName admin) { return getPasswordMinimumLetters(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumLetters(ComponentName admin, int userHandle) { + public int getPasswordMinimumLetters(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumLetters(admin, userHandle); @@ -1334,7 +1364,7 @@ public class DevicePolicyManager { * @param length The new desired minimum number of numerical digits required * in the password. A value of 0 means there is no restriction. */ - public void setPasswordMinimumNumeric(ComponentName admin, int length) { + public void setPasswordMinimumNumeric(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumNumeric(admin, length); @@ -1352,16 +1382,16 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of numerical digits required in the password. */ - public int getPasswordMinimumNumeric(ComponentName admin) { + public int getPasswordMinimumNumeric(@Nullable ComponentName admin) { return getPasswordMinimumNumeric(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumNumeric(ComponentName admin, int userHandle) { + public int getPasswordMinimumNumeric(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumNumeric(admin, userHandle); @@ -1393,7 +1423,7 @@ public class DevicePolicyManager { * @param length The new desired minimum number of symbols required in the * password. A value of 0 means there is no restriction. */ - public void setPasswordMinimumSymbols(ComponentName admin, int length) { + public void setPasswordMinimumSymbols(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumSymbols(admin, length); @@ -1410,16 +1440,16 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of symbols required in the password. */ - public int getPasswordMinimumSymbols(ComponentName admin) { + public int getPasswordMinimumSymbols(@Nullable ComponentName admin) { return getPasswordMinimumSymbols(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumSymbols(ComponentName admin, int userHandle) { + public int getPasswordMinimumSymbols(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumSymbols(admin, userHandle); @@ -1451,7 +1481,7 @@ public class DevicePolicyManager { * @param length The new desired minimum number of letters required in the * password. A value of 0 means there is no restriction. */ - public void setPasswordMinimumNonLetter(ComponentName admin, int length) { + public void setPasswordMinimumNonLetter(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordMinimumNonLetter(admin, length); @@ -1469,16 +1499,16 @@ public class DevicePolicyManager { * and only applies when the password quality is * {@link #PASSWORD_QUALITY_COMPLEX}. * - * @param admin The name of the admin component to check, or null to + * @param admin The name of the admin component to check, or {@code null} to * aggregate all admins. * @return The minimum number of letters required in the password. */ - public int getPasswordMinimumNonLetter(ComponentName admin) { + public int getPasswordMinimumNonLetter(@Nullable ComponentName admin) { return getPasswordMinimumNonLetter(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordMinimumNonLetter(ComponentName admin, int userHandle) { + public int getPasswordMinimumNonLetter(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordMinimumNonLetter(admin, userHandle); @@ -1511,7 +1541,7 @@ public class DevicePolicyManager { * @param length The new desired length of password history. A value of 0 * means there is no restriction. */ - public void setPasswordHistoryLength(ComponentName admin, int length) { + public void setPasswordHistoryLength(@NonNull ComponentName admin, int length) { if (mService != null) { try { mService.setPasswordHistoryLength(admin, length); @@ -1543,7 +1573,7 @@ public class DevicePolicyManager { * @param timeout The limit (in ms) that a password can remain in effect. A value of 0 * means there is no restriction (unlimited). */ - public void setPasswordExpirationTimeout(ComponentName admin, long timeout) { + public void setPasswordExpirationTimeout(@NonNull ComponentName admin, long timeout) { if (mService != null) { try { mService.setPasswordExpirationTimeout(admin, timeout); @@ -1557,12 +1587,12 @@ public class DevicePolicyManager { * Get the password expiration timeout for the given admin. The expiration timeout is the * recurring expiration timeout provided in the call to * {@link #setPasswordExpirationTimeout(ComponentName, long)} for the given admin or the - * aggregate of all policy administrators if admin is null. + * aggregate of all policy administrators if {@code admin} is null. * - * @param admin The name of the admin component to check, or null to aggregate all admins. + * @param admin The name of the admin component to check, or {@code null} to aggregate all admins. * @return The timeout for the given admin or the minimum of all timeouts */ - public long getPasswordExpirationTimeout(ComponentName admin) { + public long getPasswordExpirationTimeout(@Nullable ComponentName admin) { if (mService != null) { try { return mService.getPasswordExpirationTimeout(admin, UserHandle.myUserId()); @@ -1580,10 +1610,10 @@ public class DevicePolicyManager { * If admin is null, then a composite of all expiration timeouts is returned * - which will be the minimum of all timeouts. * - * @param admin The name of the admin component to check, or null to aggregate all admins. + * @param admin The name of the admin component to check, or {@code null} to aggregate all admins. * @return The password expiration time, in ms. */ - public long getPasswordExpiration(ComponentName admin) { + public long getPasswordExpiration(@Nullable ComponentName admin) { if (mService != null) { try { return mService.getPasswordExpiration(admin, UserHandle.myUserId()); @@ -1597,16 +1627,16 @@ public class DevicePolicyManager { /** * Retrieve the current password history length for all admins of this * user and its profiles or a particular one. - * @param admin The name of the admin component to check, or null to aggregate + * @param admin The name of the admin component to check, or {@code null} to aggregate * all admins. * @return The length of the password history */ - public int getPasswordHistoryLength(ComponentName admin) { + public int getPasswordHistoryLength(@Nullable ComponentName admin) { return getPasswordHistoryLength(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getPasswordHistoryLength(ComponentName admin, int userHandle) { + public int getPasswordHistoryLength(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getPasswordHistoryLength(admin, userHandle); @@ -1705,7 +1735,7 @@ public class DevicePolicyManager { * @param num The number of failed password attempts at which point the * device will wipe its data. */ - public void setMaximumFailedPasswordsForWipe(ComponentName admin, int num) { + public void setMaximumFailedPasswordsForWipe(@NonNull ComponentName admin, int num) { if (mService != null) { try { mService.setMaximumFailedPasswordsForWipe(admin, num); @@ -1719,15 +1749,15 @@ public class DevicePolicyManager { * Retrieve the current maximum number of login attempts that are allowed * before the device wipes itself, for all admins of this user and its profiles * or a particular one. - * @param admin The name of the admin component to check, or null to aggregate + * @param admin The name of the admin component to check, or {@code null} to aggregate * all admins. */ - public int getMaximumFailedPasswordsForWipe(ComponentName admin) { + public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin) { return getMaximumFailedPasswordsForWipe(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getMaximumFailedPasswordsForWipe(ComponentName admin, int userHandle) { + public int getMaximumFailedPasswordsForWipe(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getMaximumFailedPasswordsForWipe(admin, userHandle); @@ -1824,7 +1854,7 @@ public class DevicePolicyManager { * @param timeMs The new desired maximum time to lock in milliseconds. * A value of 0 means there is no restriction. */ - public void setMaximumTimeToLock(ComponentName admin, long timeMs) { + public void setMaximumTimeToLock(@NonNull ComponentName admin, long timeMs) { if (mService != null) { try { mService.setMaximumTimeToLock(admin, timeMs); @@ -1837,17 +1867,17 @@ public class DevicePolicyManager { /** * Retrieve the current maximum time to unlock for all admins of this user * and its profiles or a particular one. - * @param admin The name of the admin component to check, or null to aggregate + * @param admin The name of the admin component to check, or {@code null} to aggregate * all admins. * @return time in milliseconds for the given admin or the minimum value (strictest) of * all admins if admin is null. Returns 0 if there are no restrictions. */ - public long getMaximumTimeToLock(ComponentName admin) { + public long getMaximumTimeToLock(@Nullable ComponentName admin) { return getMaximumTimeToLock(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public long getMaximumTimeToLock(ComponentName admin, int userHandle) { + public long getMaximumTimeToLock(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getMaximumTimeToLock(admin, userHandle); @@ -1922,21 +1952,20 @@ public class DevicePolicyManager { * this method; if it has not, a security exception will be thrown. * Only the first device admin can set the proxy. If a second admin attempts * to set the proxy, the {@link ComponentName} of the admin originally setting the - * proxy will be returned. If successful in setting the proxy, null will + * proxy will be returned. If successful in setting the proxy, {@code null} will * be returned. * The method can be called repeatedly by the device admin alrady setting the * proxy to update the proxy and exclusion list. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated - * with. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param proxySpec the global proxy desired. Must be an HTTP Proxy. * Pass Proxy.NO_PROXY to reset the proxy. * @param exclusionList a list of domains to be excluded from the global proxy. - * @return returns null if the proxy was successfully set, or a {@link ComponentName} - * of the device admin that sets thew proxy otherwise. + * @return {@code null} if the proxy was successfully set, or otherwise a {@link ComponentName} + * of the device admin that sets the proxy. * @hide */ - public ComponentName setGlobalProxy(ComponentName admin, Proxy proxySpec, + public ComponentName setGlobalProxy(@NonNull ComponentName admin, Proxy proxySpec, List<String> exclusionList ) { if (proxySpec == null) { throw new NullPointerException(); @@ -2001,7 +2030,8 @@ public class DevicePolicyManager { * @param proxyInfo The a {@link ProxyInfo} object defining the new global * HTTP proxy. A {@code null} value will clear the global HTTP proxy. */ - public void setRecommendedGlobalProxy(ComponentName admin, ProxyInfo proxyInfo) { + public void setRecommendedGlobalProxy(@NonNull ComponentName admin, @Nullable ProxyInfo + proxyInfo) { if (mService != null) { try { mService.setRecommendedGlobalProxy(admin, proxyInfo); @@ -2013,8 +2043,8 @@ public class DevicePolicyManager { /** * Returns the component name setting the global proxy. - * @return ComponentName object of the device admin that set the global proxy, or - * null if no admin has set the proxy. + * @return ComponentName object of the device admin that set the global proxy, or {@code null} + * if no admin has set the proxy. * @hide */ public ComponentName getGlobalProxyAdmin() { @@ -2147,7 +2177,7 @@ public class DevicePolicyManager { * {@link #ENCRYPTION_STATUS_ACTIVE}. This is the value of the requests; Use * {@link #getStorageEncryptionStatus()} to query the actual device state. */ - public int setStorageEncryption(ComponentName admin, boolean encrypt) { + public int setStorageEncryption(@NonNull ComponentName admin, boolean encrypt) { if (mService != null) { try { return mService.setStorageEncryption(admin, encrypt); @@ -2167,7 +2197,7 @@ public class DevicePolicyManager { * administrators. * @return true if the admin(s) are requesting encryption, false if not. */ - public boolean getStorageEncryption(ComponentName admin) { + public boolean getStorageEncryption(@Nullable ComponentName admin) { if (mService != null) { try { return mService.getStorageEncryption(admin, UserHandle.myUserId()); @@ -2216,14 +2246,14 @@ public class DevicePolicyManager { /** * Installs the given certificate as a user CA. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. * @param certBuffer encoded form of the certificate to install. * * @return false if the certBuffer cannot be parsed or installation is * interrupted, true otherwise. */ - public boolean installCaCert(ComponentName admin, byte[] certBuffer) { + public boolean installCaCert(@Nullable ComponentName admin, byte[] certBuffer) { if (mService != null) { try { return mService.installCaCert(admin, certBuffer); @@ -2237,11 +2267,11 @@ public class DevicePolicyManager { /** * Uninstalls the given certificate from trusted user CAs, if present. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. * @param certBuffer encoded form of the certificate to remove. */ - public void uninstallCaCert(ComponentName admin, byte[] certBuffer) { + public void uninstallCaCert(@Nullable ComponentName admin, byte[] certBuffer) { if (mService != null) { try { final String alias = getCaCertAlias(certBuffer); @@ -2259,11 +2289,11 @@ public class DevicePolicyManager { * If a user has installed any certificates by other means than device policy these will be * included too. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. * @return a List of byte[] arrays, each encoding one user CA certificate. */ - public List<byte[]> getInstalledCaCerts(ComponentName admin) { + public List<byte[]> getInstalledCaCerts(@Nullable ComponentName admin) { List<byte[]> certs = new ArrayList<byte[]>(); if (mService != null) { try { @@ -2287,10 +2317,10 @@ public class DevicePolicyManager { * Uninstalls all custom trusted CA certificates from the profile. Certificates installed by * means other than device policy will also be removed, except for system CA certificates. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. */ - public void uninstallAllUserCaCerts(ComponentName admin) { + public void uninstallAllUserCaCerts(@Nullable ComponentName admin) { if (mService != null) { for (String alias : new TrustedCertificateStore().userAliases()) { try { @@ -2305,11 +2335,11 @@ public class DevicePolicyManager { /** * Returns whether this certificate is installed as a trusted CA. * - * @param admin Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. * @param certBuffer encoded form of the certificate to look up. */ - public boolean hasCaCertInstalled(ComponentName admin, byte[] certBuffer) { + public boolean hasCaCertInstalled(@Nullable ComponentName admin, byte[] certBuffer) { if (mService != null) { try { mService.enforceCanManageCaCerts(admin); @@ -2327,21 +2357,21 @@ public class DevicePolicyManager { * Called by a device or profile owner to install a certificate and private key pair. The * keypair will be visible to all apps within the profile. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. Use - * <code>null</code> if calling from a delegated certificate installer. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if calling from a delegated certificate installer. * @param privKey The private key to install. * @param cert The certificate to install. * @param alias The private key alias under which to install the certificate. If a certificate * with that alias already exists, it will be overwritten. * @return {@code true} if the keys were installed, {@code false} otherwise. */ - public boolean installKeyPair(ComponentName who, PrivateKey privKey, Certificate cert, + public boolean installKeyPair(@Nullable ComponentName admin, PrivateKey privKey, Certificate cert, String alias) { try { final byte[] pemCert = Credentials.convertToPem(cert); final byte[] pkcs8Key = KeyFactory.getInstance(privKey.getAlgorithm()) .getKeySpec(privKey, PKCS8EncodedKeySpec.class).getEncoded(); - return mService.installKeyPair(who, pkcs8Key, pemCert, alias); + return mService.installKeyPair(admin, pkcs8Key, pemCert, alias); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { @@ -2353,7 +2383,7 @@ public class DevicePolicyManager { } /** - * Returns the alias of a given CA certificate in the certificate store, or null if it + * @return the alias of a given CA certificate in the certificate store, or {@code null} if it * doesn't exist. */ private static String getCaCertAlias(byte[] certBuffer) throws CertificateException { @@ -2373,15 +2403,15 @@ public class DevicePolicyManager { * it is later cleared by calling this method with a null value or uninstallling the certificate * installer. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param installerPackage The package name of the certificate installer which will be given - * access. If <code>null</code> is given the current package will be cleared. + * access. If {@code null} is given the current package will be cleared. */ - public void setCertInstallerPackage(ComponentName who, String installerPackage) - throws SecurityException { + public void setCertInstallerPackage(@NonNull ComponentName admin, @Nullable String + installerPackage) throws SecurityException { if (mService != null) { try { - mService.setCertInstallerPackage(who, installerPackage); + mService.setCertInstallerPackage(admin, installerPackage); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -2392,14 +2422,14 @@ public class DevicePolicyManager { * Called by a profile owner or device owner to retrieve the certificate installer for the * current user. null if none is set. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. - * @return The package name of the current delegated certificate installer. <code>null</code> + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. + * @return The package name of the current delegated certificate installer, or {@code null} * if none is set. */ - public String getCertInstallerPackage(ComponentName who) throws SecurityException { + public String getCertInstallerPackage(@NonNull ComponentName admin) throws SecurityException { if (mService != null) { try { - return mService.getCertInstallerPackage(who); + return mService.getCertInstallerPackage(admin); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -2419,7 +2449,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param disabled Whether or not the camera should be disabled. */ - public void setCameraDisabled(ComponentName admin, boolean disabled) { + public void setCameraDisabled(@NonNull ComponentName admin, boolean disabled) { if (mService != null) { try { mService.setCameraDisabled(admin, disabled); @@ -2432,15 +2462,15 @@ public class DevicePolicyManager { /** * Determine whether or not the device's cameras have been disabled for this user, * either by the current admin, if specified, or all admins. - * @param admin The name of the admin component to check, or null to check if any admins + * @param admin The name of the admin component to check, or {@code null} to check whether any admins * have disabled the camera */ - public boolean getCameraDisabled(ComponentName admin) { + public boolean getCameraDisabled(@Nullable ComponentName admin) { return getCameraDisabled(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public boolean getCameraDisabled(ComponentName admin, int userHandle) { + public boolean getCameraDisabled(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getCameraDisabled(admin, userHandle); @@ -2463,7 +2493,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param disabled Whether screen capture is disabled or not. */ - public void setScreenCaptureDisabled(ComponentName admin, boolean disabled) { + public void setScreenCaptureDisabled(@NonNull ComponentName admin, boolean disabled) { if (mService != null) { try { mService.setScreenCaptureDisabled(admin, disabled); @@ -2476,15 +2506,15 @@ public class DevicePolicyManager { /** * Determine whether or not screen capture has been disabled by the current * admin, if specified, or all admins. - * @param admin The name of the admin component to check, or null to check if any admins + * @param admin The name of the admin component to check, or {@code null} to check whether any admins * have disabled screen capture. */ - public boolean getScreenCaptureDisabled(ComponentName admin) { + public boolean getScreenCaptureDisabled(@Nullable ComponentName admin) { return getScreenCaptureDisabled(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public boolean getScreenCaptureDisabled(ComponentName admin, int userHandle) { + public boolean getScreenCaptureDisabled(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getScreenCaptureDisabled(admin, userHandle); @@ -2507,7 +2537,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param required Whether auto time is set required or not. */ - public void setAutoTimeRequired(ComponentName admin, boolean required) { + public void setAutoTimeRequired(@NonNull ComponentName admin, boolean required) { if (mService != null) { try { mService.setAutoTimeRequired(admin, required); @@ -2561,7 +2591,7 @@ public class DevicePolicyManager { * {@link #KEYGUARD_DISABLE_UNREDACTED_NOTIFICATIONS}, {@link #KEYGUARD_DISABLE_FINGERPRINT}, * {@link #KEYGUARD_DISABLE_FEATURES_ALL} */ - public void setKeyguardDisabledFeatures(ComponentName admin, int which) { + public void setKeyguardDisabledFeatures(@NonNull ComponentName admin, int which) { if (mService != null) { try { mService.setKeyguardDisabledFeatures(admin, which); @@ -2574,17 +2604,17 @@ public class DevicePolicyManager { /** * Determine whether or not features have been disabled in keyguard either by the current * admin, if specified, or all admins. - * @param admin The name of the admin component to check, or null to check if any admins + * @param admin The name of the admin component to check, or {@code null} to check whether any admins * have disabled features in keyguard. * @return bitfield of flags. See {@link #setKeyguardDisabledFeatures(ComponentName, int)} * for a list. */ - public int getKeyguardDisabledFeatures(ComponentName admin) { + public int getKeyguardDisabledFeatures(@Nullable ComponentName admin) { return getKeyguardDisabledFeatures(admin, UserHandle.myUserId()); } /** @hide per-user version */ - public int getKeyguardDisabledFeatures(ComponentName admin, int userHandle) { + public int getKeyguardDisabledFeatures(@Nullable ComponentName admin, int userHandle) { if (mService != null) { try { return mService.getKeyguardDisabledFeatures(admin, userHandle); @@ -2598,7 +2628,8 @@ public class DevicePolicyManager { /** * @hide */ - public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing, int userHandle) { + public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing, + int userHandle) { if (mService != null) { try { mService.setActiveAdmin(policyReceiver, refreshing, userHandle); @@ -2611,15 +2642,15 @@ public class DevicePolicyManager { /** * @hide */ - public void setActiveAdmin(ComponentName policyReceiver, boolean refreshing) { + public void setActiveAdmin(@NonNull ComponentName policyReceiver, boolean refreshing) { setActiveAdmin(policyReceiver, refreshing, UserHandle.myUserId()); } /** - * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data + * Returns the DeviceAdminInfo as defined by the administrator's package info & meta-data * @hide */ - public DeviceAdminInfo getAdminInfo(ComponentName cn) { + public DeviceAdminInfo getAdminInfo(@NonNull ComponentName cn) { ActivityInfo ai; try { ai = mContext.getPackageManager().getReceiverInfo(cn, @@ -2646,7 +2677,7 @@ public class DevicePolicyManager { /** * @hide */ - public void getRemoveWarning(ComponentName admin, RemoteCallback result) { + public void getRemoveWarning(@Nullable ComponentName admin, RemoteCallback result) { if (mService != null) { try { mService.getRemoveWarning(admin, result, UserHandle.myUserId()); @@ -2740,10 +2771,10 @@ public class DevicePolicyManager { /** * Used to determine if a particular package has been registered as a Device Owner app. * A device owner app is a special device admin that cannot be deactivated by the user, once - * activated as a device admin. It also cannot be uninstalled. To check if a particular + * activated as a device admin. It also cannot be uninstalled. To check whether a particular * package is currently registered as the device owner app, pass in the package name from * {@link Context#getPackageName()} to this method.<p/>This is useful for device - * admin apps that want to check if they are also registered as the device owner app. The + * admin apps that want to check whether they are also registered as the device owner app. The * exact mechanism by which a device admin app is registered as a device owner app is defined by * the setup process. * @param packageName the package name of the app, to compare with the registered device owner @@ -2820,19 +2851,20 @@ public class DevicePolicyManager { * MANAGE_DEVICE_ADMINS permission before the device is provisioned or by a device owner app. A * device initializer app is granted device owner privileges during device initialization and * profile owner privileges during secondary user initialization. - * @param who Which {@link DeviceAdminReceiver} this request is associated with, or null if not - * called by the device owner. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with, or + * {@code null} if not called by the device owner. * @param initializer Which {@link DeviceAdminReceiver} to make device initializer. * @return whether the component was successfully registered as the device initializer. * @throws IllegalArgumentException if the componentname is null or invalid * @throws IllegalStateException if the caller is not device owner or the device has * already been provisioned or a device initializer already exists. */ - public boolean setDeviceInitializer(ComponentName who, ComponentName initializer) + public boolean setDeviceInitializer(@Nullable ComponentName admin, + @NonNull ComponentName initializer) throws IllegalArgumentException, IllegalStateException { if (mService != null) { try { - return mService.setDeviceInitializer(who, initializer); + return mService.setDeviceInitializer(admin, initializer); } catch (RemoteException re) { Log.w(TAG, "Failed to set device initializer"); } @@ -2863,12 +2895,12 @@ public class DevicePolicyManager { * subsequently created users. This method can be called by either the device owner or device * initializer itself. The caller must be an active administrator. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. */ - public void clearDeviceInitializerApp(ComponentName who) { + public void clearDeviceInitializerApp(@NonNull ComponentName admin) { if (mService != null) { try { - mService.clearDeviceInitializer(who); + mService.clearDeviceInitializer(admin); } catch (RemoteException re) { Log.w(TAG, "Failed to clear device initializer"); } @@ -2927,7 +2959,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @return whether the user is now enabled. */ - public boolean setUserEnabled(ComponentName admin) { + public boolean setUserEnabled(@NonNull ComponentName admin) { if (mService != null) { try { return mService.setUserEnabled(admin); @@ -2955,7 +2987,7 @@ public class DevicePolicyManager { * the user has already been set up. */ @SystemApi - public boolean setActiveProfileOwner(ComponentName admin, @Deprecated String ownerName) + public boolean setActiveProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName) throws IllegalArgumentException { if (mService != null) { try { @@ -2980,7 +3012,7 @@ public class DevicePolicyManager { * @return */ @SystemApi - public void clearProfileOwner(ComponentName admin) { + public void clearProfileOwner(@NonNull ComponentName admin) { if (mService != null) { try { mService.clearProfileOwner(admin); @@ -2992,14 +3024,14 @@ public class DevicePolicyManager { /** * @hide - * Checks if the user was already setup. + * Checks whether the user was already setup. */ public boolean hasUserSetupCompleted() { if (mService != null) { try { return mService.hasUserSetupCompleted(); } catch (RemoteException re) { - Log.w(TAG, "Failed to check if user setup has completed"); + Log.w(TAG, "Failed to check whether user setup has completed"); } } return true; @@ -3021,7 +3053,7 @@ public class DevicePolicyManager { * @throws IllegalArgumentException if admin is null, the package isn't installed, or the * preconditions mentioned are not met. */ - public boolean setProfileOwner(ComponentName admin, @Deprecated String ownerName, + public boolean setProfileOwner(@NonNull ComponentName admin, @Deprecated String ownerName, int userHandle) throws IllegalArgumentException { if (admin == null) { throw new NullPointerException("admin cannot be null"); @@ -3048,7 +3080,7 @@ public class DevicePolicyManager { * * @param admin Which {@link DeviceAdminReceiver} this request is associated with. */ - public void setProfileEnabled(ComponentName admin) { + public void setProfileEnabled(@NonNull ComponentName admin) { if (mService != null) { try { mService.setProfileEnabled(admin); @@ -3066,12 +3098,13 @@ public class DevicePolicyManager { * @see #isProfileOwnerApp * @see #isDeviceOwnerApp * + * @param admin Which {@link DeviceAdminReceiver} this request is associate with. * @param profileName The name of the profile. */ - public void setProfileName(ComponentName who, String profileName) { + public void setProfileName(@NonNull ComponentName admin, String profileName) { if (mService != null) { try { - mService.setProfileName(who, profileName); + mService.setProfileName(admin, profileName); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -3102,7 +3135,7 @@ public class DevicePolicyManager { /** * @hide - * @return the packageName of the owner of the given user profile or null if no profile + * @return the packageName of the owner of the given user profile or {@code null} if no profile * owner has been set for that user. * @throws IllegalArgumentException if the userId is invalid. */ @@ -3130,8 +3163,8 @@ public class DevicePolicyManager { /** * @hide - * @return the human readable name of the organisation associated with this DPM or null if - * one is not set. + * @return the human readable name of the organisation associated with this DPM or {@code null} + * if one is not set. * @throws IllegalArgumentException if the userId is invalid. */ public String getProfileOwnerName() throws IllegalArgumentException { @@ -3185,8 +3218,8 @@ public class DevicePolicyManager { * @param filter The IntentFilter for which a default handler is added. * @param activity The Activity that is added as default intent handler. */ - public void addPersistentPreferredActivity(ComponentName admin, IntentFilter filter, - ComponentName activity) { + public void addPersistentPreferredActivity(@NonNull ComponentName admin, IntentFilter filter, + @NonNull ComponentName activity) { if (mService != null) { try { mService.addPersistentPreferredActivity(admin, filter, activity); @@ -3206,7 +3239,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param packageName The name of the package for which preferences are removed. */ - public void clearPackagePersistentPreferredActivities(ComponentName admin, + public void clearPackagePersistentPreferredActivities(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { @@ -3241,7 +3274,7 @@ public class DevicePolicyManager { * * @see UserManager#KEY_RESTRICTIONS_PENDING */ - public void setApplicationRestrictions(ComponentName admin, String packageName, + public void setApplicationRestrictions(@NonNull ComponentName admin, String packageName, Bundle settings) { if (mService != null) { try { @@ -3271,8 +3304,8 @@ public class DevicePolicyManager { * then it's up to the TrustAgent itself to aggregate the values from all device admins. * <p>Consult documentation for the specific TrustAgent to determine legal options parameters. */ - public void setTrustAgentConfiguration(ComponentName admin, ComponentName target, - PersistableBundle configuration) { + public void setTrustAgentConfiguration(@NonNull ComponentName admin, + @NonNull ComponentName target, PersistableBundle configuration) { if (mService != null) { try { mService.setTrustAgentConfiguration(admin, target, configuration); @@ -3296,14 +3329,14 @@ public class DevicePolicyManager { * @param agent Which component to get enabled features for. * @return configuration for the given trust agent. */ - public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, - ComponentName agent) { + public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin, + @NonNull ComponentName agent) { return getTrustAgentConfiguration(admin, agent, UserHandle.myUserId()); } /** @hide per-user version */ - public List<PersistableBundle> getTrustAgentConfiguration(ComponentName admin, - ComponentName agent, int userHandle) { + public List<PersistableBundle> getTrustAgentConfiguration(@Nullable ComponentName admin, + @NonNull ComponentName agent, int userHandle) { if (mService != null) { try { return mService.getTrustAgentConfiguration(admin, agent, userHandle); @@ -3321,13 +3354,13 @@ public class DevicePolicyManager { * <p>The calling device admin must be a profile owner. If it is not, a * security exception will be thrown. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param disabled If true caller-Id information in the managed profile is not displayed. */ - public void setCrossProfileCallerIdDisabled(ComponentName who, boolean disabled) { + public void setCrossProfileCallerIdDisabled(@NonNull ComponentName admin, boolean disabled) { if (mService != null) { try { - mService.setCrossProfileCallerIdDisabled(who, disabled); + mService.setCrossProfileCallerIdDisabled(admin, disabled); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -3341,12 +3374,12 @@ public class DevicePolicyManager { * <p>The calling device admin must be a profile owner. If it is not, a * security exception will be thrown. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. */ - public boolean getCrossProfileCallerIdDisabled(ComponentName who) { + public boolean getCrossProfileCallerIdDisabled(@NonNull ComponentName admin) { if (mService != null) { try { - return mService.getCrossProfileCallerIdDisabled(who); + return mService.getCrossProfileCallerIdDisabled(admin); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -3396,15 +3429,15 @@ public class DevicePolicyManager { * <p> * This API works on managed profile only. * - * @param who Which {@link DeviceAdminReceiver} this request is associated + * @param admin Which {@link DeviceAdminReceiver} this request is associated * with. * @param disabled If true, bluetooth devices cannot access enterprise * contacts. */ - public void setBluetoothContactSharingDisabled(ComponentName who, boolean disabled) { + public void setBluetoothContactSharingDisabled(@NonNull ComponentName admin, boolean disabled) { if (mService != null) { try { - mService.setBluetoothContactSharingDisabled(who, disabled); + mService.setBluetoothContactSharingDisabled(admin, disabled); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -3420,13 +3453,13 @@ public class DevicePolicyManager { * <p> * This API works on managed profile only. * - * @param who Which {@link DeviceAdminReceiver} this request is associated + * @param admin Which {@link DeviceAdminReceiver} this request is associated * with. */ - public boolean getBluetoothContactSharingDisabled(ComponentName who) { + public boolean getBluetoothContactSharingDisabled(@NonNull ComponentName admin) { if (mService != null) { try { - return mService.getBluetoothContactSharingDisabled(who); + return mService.getBluetoothContactSharingDisabled(admin); } catch (RemoteException e) { Log.w(TAG, "Failed talking with device policy service", e); } @@ -3465,7 +3498,7 @@ public class DevicePolicyManager { * @param flags {@link DevicePolicyManager#FLAG_MANAGED_CAN_ACCESS_PARENT} and * {@link DevicePolicyManager#FLAG_PARENT_CAN_ACCESS_MANAGED} are supported. */ - public void addCrossProfileIntentFilter(ComponentName admin, IntentFilter filter, int flags) { + public void addCrossProfileIntentFilter(@NonNull ComponentName admin, IntentFilter filter, int flags) { if (mService != null) { try { mService.addCrossProfileIntentFilter(admin, filter, flags); @@ -3481,7 +3514,7 @@ public class DevicePolicyManager { * Only removes those that have been set by the profile owner. * @param admin Which {@link DeviceAdminReceiver} this request is associated with. */ - public void clearCrossProfileIntentFilters(ComponentName admin) { + public void clearCrossProfileIntentFilters(@NonNull ComponentName admin) { if (mService != null) { try { mService.clearCrossProfileIntentFilters(admin); @@ -3512,7 +3545,7 @@ public class DevicePolicyManager { * @return true if setting the restriction succeeded. It fail if there is * one or more non-system accessibility services enabled, that are not in the list. */ - public boolean setPermittedAccessibilityServices(ComponentName admin, + public boolean setPermittedAccessibilityServices(@NonNull ComponentName admin, List<String> packageNames) { if (mService != null) { try { @@ -3533,7 +3566,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @return List of accessiblity service package names. */ - public List<String> getPermittedAccessibilityServices(ComponentName admin) { + public List<String> getPermittedAccessibilityServices(@NonNull ComponentName admin) { if (mService != null) { try { return mService.getPermittedAccessibilityServices(admin); @@ -3591,7 +3624,7 @@ public class DevicePolicyManager { * one or more non-system input methods currently enabled that are not in * the packageNames list. */ - public boolean setPermittedInputMethods(ComponentName admin, List<String> packageNames) { + public boolean setPermittedInputMethods(@NonNull ComponentName admin, List<String> packageNames) { if (mService != null) { try { return mService.setPermittedInputMethods(admin, packageNames); @@ -3612,7 +3645,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @return List of input method package names. */ - public List<String> getPermittedInputMethods(ComponentName admin) { + public List<String> getPermittedInputMethods(@NonNull ComponentName admin) { if (mService != null) { try { return mService.getPermittedInputMethods(admin); @@ -3655,9 +3688,10 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param name the user's name * @see UserHandle - * @return the UserHandle object for the created user, or null if the user could not be created. + * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the + * user could not be created. */ - public UserHandle createUser(ComponentName admin, String name) { + public UserHandle createUser(@NonNull ComponentName admin, String name) { try { return mService.createUser(admin, name); } catch (RemoteException re) { @@ -3688,10 +3722,11 @@ public class DevicePolicyManager { * @param adminExtras Extras that will be passed to onEnable of the admin receiver * on the new user. * @see UserHandle - * @return the UserHandle object for the created user, or null if the user could not be created. + * @return the {@link android.os.UserHandle} object for the created user, or {@code null} if the + * user could not be created. */ - public UserHandle createAndInitializeUser(ComponentName admin, String name, String ownerName, - ComponentName profileOwnerComponent, Bundle adminExtras) { + public UserHandle createAndInitializeUser(@NonNull ComponentName admin, String name, + String ownerName, @NonNull ComponentName profileOwnerComponent, Bundle adminExtras) { try { return mService.createAndInitializeUser(admin, name, ownerName, profileOwnerComponent, adminExtras); @@ -3709,7 +3744,7 @@ public class DevicePolicyManager { * @param userHandle the user to remove. * @return {@code true} if the user was removed, {@code false} otherwise. */ - public boolean removeUser(ComponentName admin, UserHandle userHandle) { + public boolean removeUser(@NonNull ComponentName admin, UserHandle userHandle) { try { return mService.removeUser(admin, userHandle); } catch (RemoteException re) { @@ -3727,7 +3762,7 @@ public class DevicePolicyManager { * * @see Intent#ACTION_USER_FOREGROUND */ - public boolean switchUser(ComponentName admin, UserHandle userHandle) { + public boolean switchUser(@NonNull ComponentName admin, @Nullable UserHandle userHandle) { try { return mService.switchUser(admin, userHandle); } catch (RemoteException re) { @@ -3749,7 +3784,7 @@ public class DevicePolicyManager { * {@link DevicePolicyManager#setApplicationRestrictions} was called, or an empty {@link Bundle} * if no restrictions have been set. */ - public Bundle getApplicationRestrictions(ComponentName admin, String packageName) { + public Bundle getApplicationRestrictions(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { return mService.getApplicationRestrictions(admin, packageName); @@ -3771,7 +3806,7 @@ public class DevicePolicyManager { * @param key The key of the restriction. See the constants in * {@link android.os.UserManager} for the list of keys. */ - public void addUserRestriction(ComponentName admin, String key) { + public void addUserRestriction(@NonNull ComponentName admin, String key) { if (mService != null) { try { mService.setUserRestriction(admin, key, true); @@ -3792,7 +3827,7 @@ public class DevicePolicyManager { * @param key The key of the restriction. See the constants in * {@link android.os.UserManager} for the list of keys. */ - public void clearUserRestriction(ComponentName admin, String key) { + public void clearUserRestriction(@NonNull ComponentName admin, String key) { if (mService != null) { try { mService.setUserRestriction(admin, key, false); @@ -3812,7 +3847,7 @@ public class DevicePolicyManager { * unhidden. * @return boolean Whether the hidden setting of the package was successfully updated. */ - public boolean setApplicationHidden(ComponentName admin, String packageName, + public boolean setApplicationHidden(@NonNull ComponentName admin, String packageName, boolean hidden) { if (mService != null) { try { @@ -3831,7 +3866,7 @@ public class DevicePolicyManager { * @param packageName The name of the package to retrieve the hidden status of. * @return boolean {@code true} if the package is hidden, {@code false} otherwise. */ - public boolean isApplicationHidden(ComponentName admin, String packageName) { + public boolean isApplicationHidden(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { return mService.isApplicationHidden(admin, packageName); @@ -3849,7 +3884,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param packageName The package to be re-enabled in the current profile. */ - public void enableSystemApp(ComponentName admin, String packageName) { + public void enableSystemApp(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { mService.enableSystemApp(admin, packageName); @@ -3868,7 +3903,7 @@ public class DevicePolicyManager { * intent will be re-enabled in the current profile. * @return int The number of activities that matched the intent and were installed. */ - public int enableSystemApp(ComponentName admin, Intent intent) { + public int enableSystemApp(@NonNull ComponentName admin, Intent intent) { if (mService != null) { try { return mService.enableSystemAppWithIntent(admin, intent); @@ -3894,7 +3929,7 @@ public class DevicePolicyManager { * @param disabled The boolean indicating that account management will be disabled (true) or * enabled (false). */ - public void setAccountManagementDisabled(ComponentName admin, String accountType, + public void setAccountManagementDisabled(@NonNull ComponentName admin, String accountType, boolean disabled) { if (mService != null) { try { @@ -3950,7 +3985,7 @@ public class DevicePolicyManager { * @see DeviceAdminReceiver#onLockTaskModeExiting(Context, Intent) * @see UserManager#DISALLOW_CREATE_WINDOWS */ - public void setLockTaskPackages(ComponentName admin, String[] packages) + public void setLockTaskPackages(@NonNull ComponentName admin, String[] packages) throws SecurityException { if (mService != null) { try { @@ -3967,7 +4002,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @hide */ - public String[] getLockTaskPackages(ComponentName admin) { + public String[] getLockTaskPackages(@NonNull ComponentName admin) { if (mService != null) { try { return mService.getLockTaskPackages(admin); @@ -4024,7 +4059,7 @@ public class DevicePolicyManager { * @param setting The name of the setting to update. * @param value The value to update the setting to. */ - public void setGlobalSetting(ComponentName admin, String setting, String value) { + public void setGlobalSetting(@NonNull ComponentName admin, String setting, String value) { if (mService != null) { try { mService.setGlobalSetting(admin, setting, value); @@ -4052,7 +4087,7 @@ public class DevicePolicyManager { * @param setting The name of the setting to update. * @param value The value to update the setting to. */ - public void setSecureSetting(ComponentName admin, String setting, String value) { + public void setSecureSetting(@NonNull ComponentName admin, String setting, String value) { if (mService != null) { try { mService.setSecureSetting(admin, setting, value); @@ -4072,7 +4107,8 @@ public class DevicePolicyManager { * {@link RestrictionsReceiver}. If this param is null, * it removes the restrictions provider previously assigned. */ - public void setRestrictionsProvider(ComponentName admin, ComponentName provider) { + public void setRestrictionsProvider(@NonNull ComponentName admin, + @Nullable ComponentName provider) { if (mService != null) { try { mService.setRestrictionsProvider(admin, provider); @@ -4088,7 +4124,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param on {@code true} to mute master volume, {@code false} to turn mute off. */ - public void setMasterVolumeMuted(ComponentName admin, boolean on) { + public void setMasterVolumeMuted(@NonNull ComponentName admin, boolean on) { if (mService != null) { try { mService.setMasterVolumeMuted(admin, on); @@ -4104,7 +4140,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @return {@code true} if master volume is muted, {@code false} if it's not. */ - public boolean isMasterVolumeMuted(ComponentName admin) { + public boolean isMasterVolumeMuted(@NonNull ComponentName admin) { if (mService != null) { try { return mService.isMasterVolumeMuted(admin); @@ -4123,7 +4159,7 @@ public class DevicePolicyManager { * @param packageName package to change. * @param uninstallBlocked true if the user shouldn't be able to uninstall the package. */ - public void setUninstallBlocked(ComponentName admin, String packageName, + public void setUninstallBlocked(@NonNull ComponentName admin, String packageName, boolean uninstallBlocked) { if (mService != null) { try { @@ -4139,16 +4175,16 @@ public class DevicePolicyManager { * Requires the caller to be the profile owner if checking a specific admin's policy. * <p> * <strong>Note:</strong> Starting from {@link android.os.Build.VERSION_CODES#LOLLIPOP_MR1}, the - * behavior of this API is changed such that passing <code>null</code> as the <code>admin</code> + * behavior of this API is changed such that passing {@code null} as the {@code admin} * parameter will return if any admin has blocked the uninstallation. Before L MR1, passing - * <code>null</code> will cause a NullPointerException to be raised. + * {@code null} will cause a NullPointerException to be raised. * - * @param admin The name of the admin component whose blocking policy will be checked, or null - * to check if any admin has blocked the uninstallation. + * @param admin The name of the admin component whose blocking policy will be checked, or + * {@code null} to check whether any admin has blocked the uninstallation. * @param packageName package to check. * @return true if uninstallation is blocked. */ - public boolean isUninstallBlocked(ComponentName admin, String packageName) { + public boolean isUninstallBlocked(@Nullable ComponentName admin, String packageName) { if (mService != null) { try { return mService.isUninstallBlocked(admin, packageName); @@ -4168,7 +4204,6 @@ public class DevicePolicyManager { * provides a different widget type. * <p> * <strong>Note:</strong> By default no widget provider package is white-listed. - * </p> * * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param packageName The package from which widget providers are white-listed. @@ -4177,7 +4212,7 @@ public class DevicePolicyManager { * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String) * @see #getCrossProfileWidgetProviders(android.content.ComponentName) */ - public boolean addCrossProfileWidgetProvider(ComponentName admin, String packageName) { + public boolean addCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { return mService.addCrossProfileWidgetProvider(admin, packageName); @@ -4195,7 +4230,6 @@ public class DevicePolicyManager { * android.content.ComponentName, String)}. * <p> * <strong>Note:</strong> By default no widget provider package is white-listed. - * </p> * * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param packageName The package from which widget providers are no longer @@ -4205,7 +4239,7 @@ public class DevicePolicyManager { * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String) * @see #getCrossProfileWidgetProviders(android.content.ComponentName) */ - public boolean removeCrossProfileWidgetProvider(ComponentName admin, String packageName) { + public boolean removeCrossProfileWidgetProvider(@NonNull ComponentName admin, String packageName) { if (mService != null) { try { return mService.removeCrossProfileWidgetProvider(admin, packageName); @@ -4226,7 +4260,7 @@ public class DevicePolicyManager { * @see #addCrossProfileWidgetProvider(android.content.ComponentName, String) * @see #removeCrossProfileWidgetProvider(android.content.ComponentName, String) */ - public List<String> getCrossProfileWidgetProviders(ComponentName admin) { + public List<String> getCrossProfileWidgetProviders(@NonNull ComponentName admin) { if (mService != null) { try { List<String> providers = mService.getCrossProfileWidgetProviders(admin); @@ -4246,7 +4280,7 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param icon the bitmap to set as the photo. */ - public void setUserIcon(ComponentName admin, Bitmap icon) { + public void setUserIcon(@NonNull ComponentName admin, Bitmap icon) { try { mService.setUserIcon(admin, icon); } catch (RemoteException re) { @@ -4273,16 +4307,17 @@ public class DevicePolicyManager { * Called by device owners to set a local system update policy. When a new policy is set, * {@link #ACTION_SYSTEM_UPDATE_POLICY_CHANGED} is broadcasted. * - * @param who Which {@link DeviceAdminReceiver} this request is associated with. All components - * in the device owner package can set system update policies and the most recent policy takes + * @param admin Which {@link DeviceAdminReceiver} this request is associated with. All + * components in the device owner package can set system update policies and the + * most recent policy takes * effect. - * @param policy the new policy, or null to clear the current policy. + * @param policy the new policy, or {@code null} to clear the current policy. * @see SystemUpdatePolicy */ - public void setSystemUpdatePolicy(ComponentName who, SystemUpdatePolicy policy) { + public void setSystemUpdatePolicy(@NonNull ComponentName admin, SystemUpdatePolicy policy) { if (mService != null) { try { - mService.setSystemUpdatePolicy(who, policy); + mService.setSystemUpdatePolicy(admin, policy); } catch (RemoteException re) { Log.w(TAG, "Error calling setSystemUpdatePolicy", re); } @@ -4292,7 +4327,7 @@ public class DevicePolicyManager { /** * Retrieve a local system update policy set previously by {@link #setSystemUpdatePolicy}. * - * @return The current policy object, or null if no policy is set. + * @return The current policy object, or {@code null} if no policy is set. */ public SystemUpdatePolicy getSystemUpdatePolicy() { if (mService != null) { @@ -4319,7 +4354,7 @@ public class DevicePolicyManager { * @return {@code false} if attempting to disable the keyguard while a lock password was in * place. {@code true} otherwise. */ - public boolean setKeyguardDisabled(ComponentName admin, boolean disabled) { + public boolean setKeyguardDisabled(@NonNull ComponentName admin, boolean disabled) { try { return mService.setKeyguardDisabled(admin, disabled); } catch (RemoteException re) { @@ -4339,7 +4374,7 @@ public class DevicePolicyManager { * @return {@code false} if attempting to disable the status bar failed. * {@code true} otherwise. */ - public boolean setStatusBarDisabled(ComponentName admin, boolean disabled) { + public boolean setStatusBarDisabled(@NonNull ComponentName admin, boolean disabled) { try { return mService.setStatusBarDisabled(admin, disabled); } catch (RemoteException re) { @@ -4377,7 +4412,8 @@ public class DevicePolicyManager { * @param admin Which {@link DeviceAdminReceiver} this request is associated with. * @param activity The Activity to be started by default during user setup. */ - public void setPreferredSetupActivity(ComponentName admin, ComponentName activity) { + public void setPreferredSetupActivity(@NonNull ComponentName admin, + @NonNull ComponentName activity) { try { mService.setPreferredSetupActivity(admin, activity); } catch (RemoteException re) { @@ -4395,7 +4431,7 @@ public class DevicePolicyManager { * @param policy One of the policy constants {@link #PERMISSION_POLICY_PROMPT}, * {@link #PERMISSION_POLICY_AUTO_GRANT} and {@link #PERMISSION_POLICY_AUTO_DENY}. */ - public void setPermissionPolicy(ComponentName admin, int policy) { + public void setPermissionPolicy(@NonNull ComponentName admin, int policy) { try { mService.setPermissionPolicy(admin, policy); } catch (RemoteException re) { @@ -4409,7 +4445,7 @@ public class DevicePolicyManager { * @param admin Which profile or device owner this request is associated with. * @return the current policy for future permission requests. */ - public int getPermissionPolicy(ComponentName admin) { + public int getPermissionPolicy(@NonNull ComponentName admin) { try { return mService.getPermissionPolicy(admin); } catch (RemoteException re) { @@ -4439,7 +4475,7 @@ public class DevicePolicyManager { * @see #PERMISSION_GRANT_STATE_DEFAULT * @see #PERMISSION_GRANT_STATE_GRANTED */ - public boolean setPermissionGrantState(ComponentName admin, String packageName, + public boolean setPermissionGrantState(@NonNull ComponentName admin, String packageName, String permission, int grantState) { try { return mService.setPermissionGrantState(admin, packageName, permission, grantState); @@ -4466,7 +4502,7 @@ public class DevicePolicyManager { * @see #setPermissionGrantState(ComponentName, String, String, int) * @see PackageManager#checkPermission(String, String) */ - public int getPermissionGrantState(ComponentName admin, String packageName, + public int getPermissionGrantState(@NonNull ComponentName admin, String packageName, String permission) { try { return mService.getPermissionGrantState(admin, packageName, permission); diff --git a/core/java/android/app/usage/IUsageStatsManager.aidl b/core/java/android/app/usage/IUsageStatsManager.aidl index 254408a..a9328bc 100644 --- a/core/java/android/app/usage/IUsageStatsManager.aidl +++ b/core/java/android/app/usage/IUsageStatsManager.aidl @@ -32,4 +32,5 @@ interface IUsageStatsManager { UsageEvents queryEvents(long beginTime, long endTime, String callingPackage); void setAppInactive(String packageName, boolean inactive, int userId); boolean isAppInactive(String packageName, int userId); + void whitelistAppTemporarily(String packageName, long duration, int userId); } diff --git a/core/java/android/app/usage/UsageStatsManager.java b/core/java/android/app/usage/UsageStatsManager.java index 34699d8..c74b0f2 100644 --- a/core/java/android/app/usage/UsageStatsManager.java +++ b/core/java/android/app/usage/UsageStatsManager.java @@ -16,6 +16,7 @@ package android.app.usage; +import android.annotation.SystemApi; import android.content.Context; import android.content.pm.ParceledListSlice; import android.os.RemoteException; @@ -245,4 +246,25 @@ public final class UsageStatsManager { // fall through } } + + /** + * {@hide} + * Temporarily whitelist the specified app for a short duration. This is to allow an app + * receiving a high priority message to be able to access the network and acquire wakelocks + * even if the device is in power-save mode or the app is currently considered inactive. + * The caller must hold the CHANGE_DEVICE_IDLE_TEMP_WHITELIST permission. + * @param packageName The package name of the app to whitelist. + * @param duration Duration to whitelist the app for, in milliseconds. It is recommended that + * this be limited to 10s of seconds. Requested duration will be clamped to a few minutes. + * @param user The user for whom the package should be whitelisted. Passing in a user that is + * not the same as the caller's process will require the INTERACT_ACROSS_USERS permission. + * @see #isAppInactive(String) + */ + @SystemApi + public void whitelistAppTemporarily(String packageName, long duration, UserHandle user) { + try { + mService.whitelistAppTemporarily(packageName, duration, user.getIdentifier()); + } catch (RemoteException re) { + } + } } diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java index b22b914..ab3f7bc 100644 --- a/core/java/android/bluetooth/BluetoothAdapter.java +++ b/core/java/android/bluetooth/BluetoothAdapter.java @@ -410,6 +410,7 @@ public final class BluetoothAdapter { * Broadcast Action: The Bluetooth adapter state has changed in LE only mode. * @hide */ + @SystemApi public static final String ACTION_BLE_STATE_CHANGED = "android.bluetooth.adapter.action.BLE_STATE_CHANGED"; @@ -620,17 +621,18 @@ public final class BluetoothAdapter { * @return true if the local Bluetooth LE adapter is turned on * @hide */ - public boolean isLeEnabled() { - final int state = getLeState(); - if (state == BluetoothAdapter.STATE_ON) { - if (DBG) Log.d (TAG, "STATE_ON"); - } else if (state == BluetoothAdapter.STATE_BLE_ON) { - if (DBG) Log.d (TAG, "STATE_BLE_ON"); - } else { - if (DBG) Log.d (TAG, "STATE_OFF"); - return false; - } - return true; + @SystemApi + public boolean isLeEnabled() { + final int state = getLeState(); + if (state == BluetoothAdapter.STATE_ON) { + if (DBG) Log.d (TAG, "STATE_ON"); + } else if (state == BluetoothAdapter.STATE_BLE_ON) { + if (DBG) Log.d (TAG, "STATE_BLE_ON"); + } else { + if (DBG) Log.d (TAG, "STATE_OFF"); + return false; + } + return true; } /** @@ -680,6 +682,7 @@ public final class BluetoothAdapter { * immediate error * @hide */ + @SystemApi public boolean disableBLE() { if (!isBleScanAlwaysAvailable()) return false; @@ -742,6 +745,7 @@ public final class BluetoothAdapter { * immediate error * @hide */ + @SystemApi public boolean enableBLE() { if (!isBleScanAlwaysAvailable()) return false; @@ -1463,10 +1467,31 @@ public final class BluetoothAdapter { * @hide */ public BluetoothServerSocket listenUsingRfcommOn(int channel) throws IOException { + return listenUsingRfcommOn(channel, false); + } + + /** + * Create a listening, secure RFCOMM Bluetooth socket. + * <p>A remote device connecting to this socket will be authenticated and + * communication on this socket will be encrypted. + * <p>Use {@link BluetoothServerSocket#accept} to retrieve incoming + * connections from a listening {@link BluetoothServerSocket}. + * <p>Valid RFCOMM channels are in range 1 to 30. + * <p>Requires {@link android.Manifest.permission#BLUETOOTH_ADMIN} + * <p>To auto assign a channel without creating a SDP record use + * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as channel number. + * @param channel RFCOMM channel to listen on + * @param mitm enforce man-in-the-middle protection for authentication. + * @return a listening RFCOMM BluetoothServerSocket + * @throws IOException on error, for example Bluetooth not available, or + * insufficient permissions, or channel in use. + * @hide + */ + public BluetoothServerSocket listenUsingRfcommOn(int channel, boolean mitm) throws IOException { BluetoothServerSocket socket = new BluetoothServerSocket( - BluetoothSocket.TYPE_RFCOMM, true, true, channel); + BluetoothSocket.TYPE_RFCOMM, true, true, channel, mitm); int errno = socket.mSocket.bindListen(); - if(channel == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { + if (channel == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { socket.setChannel(socket.mSocket.getPort()); } if (errno != 0) { @@ -1665,14 +1690,18 @@ public final class BluetoothAdapter { /** * Construct an encrypted, authenticated, L2CAP server socket. * Call #accept to retrieve connections to this socket. + * <p>To auto assign a port without creating a SDP record use + * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as port number. + * @param port the PSM to listen on + * @param mitm enforce man-in-the-middle protection for authentication. * @return An L2CAP BluetoothServerSocket * @throws IOException On error, for example Bluetooth not available, or * insufficient permissions. * @hide */ - public BluetoothServerSocket listenUsingL2capOn(int port) throws IOException { + public BluetoothServerSocket listenUsingL2capOn(int port, boolean mitm) throws IOException { BluetoothServerSocket socket = new BluetoothServerSocket( - BluetoothSocket.TYPE_L2CAP, true, true, port); + BluetoothSocket.TYPE_L2CAP, true, true, port, mitm); int errno = socket.mSocket.bindListen(); if(port == SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { socket.setChannel(socket.mSocket.getPort()); @@ -1687,6 +1716,21 @@ public final class BluetoothAdapter { } /** + * Construct an encrypted, authenticated, L2CAP server socket. + * Call #accept to retrieve connections to this socket. + * <p>To auto assign a port without creating a SDP record use + * {@link SOCKET_CHANNEL_AUTO_STATIC_NO_SDP} as port number. + * @param port the PSM to listen on + * @return An L2CAP BluetoothServerSocket + * @throws IOException On error, for example Bluetooth not available, or + * insufficient permissions. + * @hide + */ + public BluetoothServerSocket listenUsingL2capOn(int port) throws IOException { + return listenUsingL2capOn(port, false); + } + + /** * Read the local Out of Band Pairing Data * <p>Requires {@link android.Manifest.permission#BLUETOOTH} * diff --git a/core/java/android/bluetooth/BluetoothDevice.java b/core/java/android/bluetooth/BluetoothDevice.java index 26a91e4..dcf06d8 100644 --- a/core/java/android/bluetooth/BluetoothDevice.java +++ b/core/java/android/bluetooth/BluetoothDevice.java @@ -567,19 +567,16 @@ public final class BluetoothDevice implements Parcelable { /** * No preferrence of physical transport for GATT connections to remote dual-mode devices - * @hide */ public static final int TRANSPORT_AUTO = 0; /** * Prefer BR/EDR transport for GATT connections to remote dual-mode devices - * @hide */ public static final int TRANSPORT_BREDR = 1; /** * Prefer LE transport for GATT connections to remote dual-mode devices - * @hide */ public static final int TRANSPORT_LE = 2; @@ -1564,7 +1561,6 @@ public final class BluetoothDevice implements Parcelable { * {@link BluetoothDevice#TRANSPORT_AUTO} or * {@link BluetoothDevice#TRANSPORT_BREDR} or {@link BluetoothDevice#TRANSPORT_LE} * @throws IllegalArgumentException if callback is null - * @hide */ public BluetoothGatt connectGatt(Context context, boolean autoConnect, BluetoothGattCallback callback, int transport) { diff --git a/core/java/android/bluetooth/BluetoothPan.java b/core/java/android/bluetooth/BluetoothPan.java index eb6166a..744f942 100644 --- a/core/java/android/bluetooth/BluetoothPan.java +++ b/core/java/android/bluetooth/BluetoothPan.java @@ -138,7 +138,6 @@ public final class BluetoothPan implements BluetoothProfile { } if (VDBG) Log.d(TAG, "BluetoothPan() call bindService"); doBind(); - if (VDBG) Log.d(TAG, "BluetoothPan(), bindService called"); } boolean doBind() { @@ -185,12 +184,22 @@ public final class BluetoothPan implements BluetoothProfile { final private IBluetoothStateChangeCallback mStateChangeCallback = new IBluetoothStateChangeCallback.Stub() { @Override - public void onBluetoothStateChange(boolean on) throws RemoteException { - //Handle enable request to bind again. + public void onBluetoothStateChange(boolean on) { + // Handle enable request to bind again. + Log.d(TAG, "onBluetoothStateChange on: " + on); if (on) { - Log.d(TAG, "onBluetoothStateChange(on) call bindService"); - doBind(); - if (VDBG) Log.d(TAG, "BluetoothPan(), bindService called"); + try { + if (mPanService == null) { + if (VDBG) Log.d(TAG, "onBluetoothStateChange calling doBind()"); + doBind(); + } + + } catch (IllegalStateException e) { + Log.e(TAG,"onBluetoothStateChange: could not bind to PAN service: ", e); + + } catch (SecurityException e) { + Log.e(TAG,"onBluetoothStateChange: could not bind to PAN service: ", e); + } } else { if (VDBG) Log.d(TAG,"Unbinding service..."); synchronized (mConnection) { diff --git a/core/java/android/bluetooth/BluetoothServerSocket.java b/core/java/android/bluetooth/BluetoothServerSocket.java index 21024a6..a80f55c 100644 --- a/core/java/android/bluetooth/BluetoothServerSocket.java +++ b/core/java/android/bluetooth/BluetoothServerSocket.java @@ -86,6 +86,26 @@ public final class BluetoothServerSocket implements Closeable { throws IOException { mChannel = port; mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null); + if (port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { + mSocket.setExcludeSdp(true); + } + } + + /** + * Construct a socket for incoming connections. + * @param type type of socket + * @param auth require the remote device to be authenticated + * @param encrypt require the connection to be encrypted + * @param port remote port + * @param mitm enforce man-in-the-middle protection for authentication. + * @throws IOException On error, for example Bluetooth not available, or + * insufficient privileges + */ + /*package*/ BluetoothServerSocket(int type, boolean auth, boolean encrypt, int port, + boolean mitm) + throws IOException { + mChannel = port; + mSocket = new BluetoothSocket(type, -1, auth, encrypt, null, port, null, mitm); if(port == BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { mSocket.setExcludeSdp(true); } diff --git a/core/java/android/bluetooth/BluetoothSocket.java b/core/java/android/bluetooth/BluetoothSocket.java index 5cf2300..6ca6976 100644 --- a/core/java/android/bluetooth/BluetoothSocket.java +++ b/core/java/android/bluetooth/BluetoothSocket.java @@ -106,6 +106,7 @@ public final class BluetoothSocket implements Closeable { /*package*/ static final int SEC_FLAG_ENCRYPT = 1; /*package*/ static final int SEC_FLAG_AUTH = 1 << 1; /*package*/ static final int BTSOCK_FLAG_NO_SDP = 1 << 2; + /*package*/ static final int SEC_FLAG_AUTH_MITM = 1 << 3; private final int mType; /* one of TYPE_RFCOMM etc */ private BluetoothDevice mDevice; /* remote device */ @@ -115,7 +116,8 @@ public final class BluetoothSocket implements Closeable { private final BluetoothInputStream mInputStream; private final BluetoothOutputStream mOutputStream; private final ParcelUuid mUuid; - private boolean mExcludeSdp = false; + private boolean mExcludeSdp = false; /* when true no SPP SDP record will be created */ + private boolean mAuthMitm = false; /* when true Man-in-the-middle protection will be enabled*/ private ParcelFileDescriptor mPfd; private LocalSocket mSocket; private InputStream mSocketIS; @@ -158,6 +160,24 @@ public final class BluetoothSocket implements Closeable { */ /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, BluetoothDevice device, int port, ParcelUuid uuid) throws IOException { + this(type, fd, auth, encrypt, device, port, uuid, false); + } + + /** + * Construct a BluetoothSocket. + * @param type type of socket + * @param fd fd to use for connected socket, or -1 for a new socket + * @param auth require the remote device to be authenticated + * @param encrypt require the connection to be encrypted + * @param device remote device that this socket can connect to + * @param port remote port + * @param uuid SDP uuid + * @param mitm enforce man-in-the-middle protection. + * @throws IOException On error, for example Bluetooth not available, or + * insufficient privileges + */ + /*package*/ BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, + BluetoothDevice device, int port, ParcelUuid uuid, boolean mitm) throws IOException { if (VDBG) Log.d(TAG, "Creating new BluetoothSocket of type: " + type); if (type == BluetoothSocket.TYPE_RFCOMM && uuid == null && fd == -1 && port != BluetoothAdapter.SOCKET_CHANNEL_AUTO_STATIC_NO_SDP) { @@ -170,6 +190,7 @@ public final class BluetoothSocket implements Closeable { else mUuid = new ParcelUuid(new UUID(0, 0)); mType = type; mAuth = auth; + mAuthMitm = mitm; mEncrypt = encrypt; mDevice = device; mPort = port; @@ -201,6 +222,7 @@ public final class BluetoothSocket implements Closeable { mServiceName = s.mServiceName; mExcludeSdp = s.mExcludeSdp; + mAuthMitm = s.mAuthMitm; } private BluetoothSocket acceptSocket(String RemoteAddr) throws IOException { BluetoothSocket as = new BluetoothSocket(this); @@ -232,7 +254,7 @@ public final class BluetoothSocket implements Closeable { */ private BluetoothSocket(int type, int fd, boolean auth, boolean encrypt, String address, int port) throws IOException { - this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null); + this(type, fd, auth, encrypt, new BluetoothDevice(address), port, null, false); } /** @hide */ @@ -252,6 +274,8 @@ public final class BluetoothSocket implements Closeable { flags |= SEC_FLAG_ENCRYPT; if(mExcludeSdp) flags |= BTSOCK_FLAG_NO_SDP; + if(mAuthMitm) + flags |= SEC_FLAG_AUTH_MITM; return flags; } diff --git a/core/java/android/bluetooth/SdpSapsRecord.java b/core/java/android/bluetooth/SdpSapsRecord.java new file mode 100644 index 0000000..84a29b9 --- /dev/null +++ b/core/java/android/bluetooth/SdpSapsRecord.java @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2015 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.bluetooth; + +import android.os.Parcel; +import android.os.Parcelable; + +/** @hide */ +public class SdpSapsRecord implements Parcelable { + private final int mRfcommChannelNumber; + private final int mProfileVersion; + private final String mServiceName; + + public SdpSapsRecord(int rfcomm_channel_number, + int profile_version, + String service_name) { + this.mRfcommChannelNumber = rfcomm_channel_number; + this.mProfileVersion = profile_version; + this.mServiceName = service_name; + } + + public SdpSapsRecord(Parcel in) { + this.mRfcommChannelNumber = in.readInt(); + this.mProfileVersion = in.readInt(); + this.mServiceName = in.readString(); + } + + @Override + public int describeContents() { + return 0; + } + + public int getRfcommCannelNumber() { + return mRfcommChannelNumber; + } + + public int getProfileVersion() { + return mProfileVersion; + } + + public String getServiceName() { + return mServiceName; + } + + @Override + public void writeToParcel(Parcel dest, int flags) { + dest.writeInt(this.mRfcommChannelNumber); + dest.writeInt(this.mProfileVersion); + dest.writeString(this.mServiceName); + + } + + @Override + public String toString() { + String ret = "Bluetooth MAS SDP Record:\n"; + + if (mRfcommChannelNumber != -1) { + ret += "RFCOMM Chan Number: " + mRfcommChannelNumber + "\n"; + } + if (mServiceName != null) { + ret += "Service Name: " + mServiceName + "\n"; + } + if (mProfileVersion != -1) { + ret += "Profile version: " + mProfileVersion + "\n"; + } + return ret; + } + + public static final Parcelable.Creator CREATOR = new Parcelable.Creator() { + public SdpSapsRecord createFromParcel(Parcel in) { + return new SdpSapsRecord(in); + } + public SdpRecord[] newArray(int size) { + return new SdpRecord[size]; + } + }; +} diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl index ddff782..00b8c71 100644 --- a/core/java/android/content/pm/IPackageManager.aidl +++ b/core/java/android/content/pm/IPackageManager.aidl @@ -105,6 +105,9 @@ interface IPackageManager { void updatePermissionFlags(String permissionName, String packageName, int flagMask, int flagValues, int userId); + boolean shouldShowRequestPermissionRationale(String permissionName, + String packageName, int userId); + boolean isProtectedBroadcast(String actionName); int checkSignatures(String pkg1, String pkg2); diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java index 2ca0306..45245e4 100644 --- a/core/java/android/content/pm/PackageManager.java +++ b/core/java/android/content/pm/PackageManager.java @@ -2539,6 +2539,19 @@ public abstract class PackageManager { @NonNull UserHandle user); /** + * Gets whether you should show UI with rationale for requesting a permission. + * You should do this only if you do not have the permission and the context in + * which the permission is requested does not clearly communicate to the user + * what would be the benefit from grating this permission. + * + * @param permission A permission your app wants to request. + * @return Whether you can show permission rationale UI. + * + * @hide + */ + public abstract boolean shouldShowRequestPermissionRationale(String permission); + + /** * Returns an {@link android.content.Intent} suitable for passing to * {@link android.app.Activity#startActivityForResult(android.content.Intent, int)} * which prompts the user to grant permissions to this application. diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java index 14bfac5..579634f 100644 --- a/core/java/android/content/res/ColorStateList.java +++ b/core/java/android/content/res/ColorStateList.java @@ -382,6 +382,14 @@ public class ColorStateList implements Parcelable { defaultAlphaMod = 1.0f; } + // Extract the theme attributes, if any, before attempting to + // read from the typed array. This prevents a crash if we have + // unresolved attrs. + themeAttrsList[i] = a.extractThemeAttrs(themeAttrsList[i]); + if (themeAttrsList[i] != null) { + hasUnresolvedAttrs = true; + } + final int baseColor = a.getColor( R.styleable.ColorStateListItem_color, mColors[i]); final float alphaMod = a.getFloat( @@ -391,12 +399,6 @@ public class ColorStateList implements Parcelable { // Account for any configuration changes. mChangingConfigurations |= a.getChangingConfigurations(); - // Extract the theme attributes, if any. - themeAttrsList[i] = a.extractThemeAttrs(themeAttrsList[i]); - if (themeAttrsList[i] != null) { - hasUnresolvedAttrs = true; - } - a.recycle(); } } diff --git a/core/java/android/content/res/TypedArray.java b/core/java/android/content/res/TypedArray.java index f0c3f2d..8bcd5d1 100644 --- a/core/java/android/content/res/TypedArray.java +++ b/core/java/android/content/res/TypedArray.java @@ -160,7 +160,6 @@ public class TypedArray { final TypedValue v = mValue; if (getValueAt(index, v)) { - StrictMode.noteResourceMismatch(v); return v.coerceToString(); } @@ -183,24 +182,6 @@ public class TypedArray { */ @Nullable public String getString(int index) { - return getString(index, true); - } - - /** - * Returns a string representation of the value at the given index, - * optionally throwing a resource mismatch strict mode violation if the - * value must be coerced to a string. - * - * @param index the index of the attribute to retrieve - * @param strict {@code true} to throw a strict mode violation for string - * coercion, {@code false} otherwise - * @return a string representation of the value at the given index, or - * {@code null} if the resource could not be coerced to a string - * @see StrictMode#noteResourceMismatch(Object) - * @hide Used internally for view attribute inspection. - */ - @Nullable - public String getString(int index, boolean strict) { if (mRecycled) { throw new RuntimeException("Cannot make calls to a recycled instance!"); } @@ -216,9 +197,6 @@ public class TypedArray { final TypedValue v = mValue; if (getValueAt(index, v)) { - if (strict) { - StrictMode.noteResourceMismatch(v); - } final CharSequence cs = v.coerceToString(); return cs != null ? cs.toString() : null; } @@ -292,7 +270,6 @@ public class TypedArray { final TypedValue v = mValue; if (getValueAt(index, v)) { - StrictMode.noteResourceMismatch(v); final CharSequence cs = v.coerceToString(); return cs != null ? cs.toString() : null; } diff --git a/core/java/android/database/DatabaseUtils.java b/core/java/android/database/DatabaseUtils.java index e61664c..227066d 100644 --- a/core/java/android/database/DatabaseUtils.java +++ b/core/java/android/database/DatabaseUtils.java @@ -270,7 +270,7 @@ public class DatabaseUtils { window.setStartPosition(position); window.setNumColumns(numColumns); if (cursor.moveToPosition(position)) { - do { + rowloop: do { if (!window.allocRow()) { break; } @@ -307,7 +307,7 @@ public class DatabaseUtils { } if (!success) { window.freeLastRow(); - break; + break rowloop; } } position += 1; diff --git a/core/java/android/hardware/camera2/CameraCaptureSession.java b/core/java/android/hardware/camera2/CameraCaptureSession.java index b3e7cfc..c22ee5f 100644 --- a/core/java/android/hardware/camera2/CameraCaptureSession.java +++ b/core/java/android/hardware/camera2/CameraCaptureSession.java @@ -654,16 +654,22 @@ public abstract class CameraCaptureSession implements AutoCloseable { /** * This method is called when the camera device has started capturing - * the output image for the request, at the beginning of image exposure. + * the output image for the request, at the beginning of image exposure, or + * when the camera device has started processing an input image for a reprocess + * request. * - * <p>This callback is invoked right as the capture of a frame begins, - * so it is the most appropriate time for playing a shutter sound, - * or triggering UI indicators of capture.</p> + * <p>For a regular capture request, this callback is invoked right as + * the capture of a frame begins, so it is the most appropriate time + * for playing a shutter sound, or triggering UI indicators of capture.</p> * * <p>The request that is being used for this capture is provided, along - * with the actual timestamp for the start of exposure. This timestamp - * matches the timestamp that will be included in - * {@link CaptureResult#SENSOR_TIMESTAMP the result timestamp field}, + * with the actual timestamp for the start of exposure. For a reprocess + * request, this timestamp will be the input image's start of exposure + * which matches {@link CaptureResult#SENSOR_TIMESTAMP the result timestamp field} + * of the {@link TotalCaptureResult} that was used to + * {@link CameraDevice#createReprocessCaptureRequest create the reprocess request}. + * This timestamp matches the timestamps that will be + * included in {@link CaptureResult#SENSOR_TIMESTAMP the result timestamp field}, * and in the buffers sent to each output Surface. These buffer * timestamps are accessible through, for example, * {@link android.media.Image#getTimestamp() Image.getTimestamp()} or @@ -679,7 +685,9 @@ public abstract class CameraCaptureSession implements AutoCloseable { * * @param session the session returned by {@link CameraDevice#createCaptureSession} * @param request the request for the capture that just begun - * @param timestamp the timestamp at start of capture, in nanoseconds. + * @param timestamp the timestamp at start of capture for a regular request, or + * the timestamp at the input image's start of capture for a + * reprocess request, in nanoseconds. * @param frameNumber the frame number for this capture * * @see android.media.MediaActionSound diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java index 4fe257c..d5867a9 100644 --- a/core/java/android/hardware/camera2/CameraCharacteristics.java +++ b/core/java/android/hardware/camera2/CameraCharacteristics.java @@ -1068,20 +1068,35 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri /** * <p>The correction coefficients to correct for this camera device's - * radial lens distortion.</p> - * <p>Three cofficients <code>[kappa_1, kappa_2, kappa_3]</code> that - * can be used to correct the lens's radial geometric - * distortion with the mapping equations:</p> - * <pre><code> x_c = x_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) - * y_c = y_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + * radial and tangential lens distortion.</p> + * <p>Three radial distortion coefficients <code>[kappa_1, kappa_2, + * kappa_3]</code> and two tangential distortion coefficients + * <code>[kappa_4, kappa_5]</code> that can be used to correct the + * lens's geometric distortion with the mapping equations:</p> + * <pre><code> x_c = x_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + + * kappa_4 * (2 * x_i * y_i) + kappa_5 * ( r^2 + 2 * x_i^2 ) + * y_c = y_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + + * kappa_5 * (2 * x_i * y_i) + kappa_4 * ( r^2 + 2 * y_i^2 ) * </code></pre> - * <p>where <code>[x_i, y_i]</code> are normalized coordinates with <code>(0,0)</code> - * at the lens optical center, and <code>[-1, 1]</code> are the edges of - * the active pixel array; and where <code>[x_c, y_c]</code> are the - * corrected normalized coordinates with radial distortion - * removed; and <code>r^2 = x_i^2 + y_i^2</code>.</p> + * <p>Here, <code>[x_c, y_c]</code> are the coordinates to sample in the + * input image that correspond to the pixel values in the + * corrected image at the coordinate <code>[x_i, y_i]</code>:</p> + * <pre><code> correctedImage(x_i, y_i) = sample_at(x_c, y_c, inputImage) + * </code></pre> + * <p>The pixel coordinates are defined in a normalized + * coordinate system related to the + * android.lens.intrinsicCalibration calibration fields. + * Both <code>[x_i, y_i]</code> and <code>[x_c, y_c]</code> have <code>(0,0)</code> at the + * lens optical center <code>[c_x, c_y]</code>. The maximum magnitudes + * of both x and y coordinates are normalized to be 1 at the + * edge further from the optical center, so the range + * for both dimensions is <code>-1 <= x <= 1</code>.</p> + * <p>Finally, <code>r</code> represents the radial distance from the + * optical center, <code>r^2 = x_i^2 + y_i^2</code>, and its magnitude + * is therefore no larger than <code>|r| <= sqrt(2)</code>.</p> + * <p>The distortion model used is the Brown-Conrady model.</p> * <p><b>Units</b>: - * Coefficients for a 6th-degree even radial polynomial.</p> + * Unitless coefficients.</p> * <p><b>Optional</b> - This value may be {@code null} on some devices.</p> */ @PublicKey diff --git a/core/java/android/hardware/camera2/CameraManager.java b/core/java/android/hardware/camera2/CameraManager.java index 20e1610..0f002a9 100644 --- a/core/java/android/hardware/camera2/CameraManager.java +++ b/core/java/android/hardware/camera2/CameraManager.java @@ -56,7 +56,7 @@ import java.util.ArrayList; public final class CameraManager { private static final String TAG = "CameraManager"; - private final boolean DEBUG; + private final boolean DEBUG = false; private static final int USE_CALLING_UID = -1; @@ -73,7 +73,6 @@ public final class CameraManager { * @hide */ public CameraManager(Context context) { - DEBUG = Log.isLoggable(TAG, Log.DEBUG); synchronized(mLock) { mContext = context; } @@ -722,7 +721,7 @@ public final class CameraManager { implements IBinder.DeathRecipient { private static final String TAG = "CameraManagerGlobal"; - private final boolean DEBUG = Log.isLoggable(TAG, Log.DEBUG); + private final boolean DEBUG = false; // Singleton instance private static final CameraManagerGlobal gCameraManager = diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java index cf091a9..ac29f80 100644 --- a/core/java/android/hardware/camera2/CameraMetadata.java +++ b/core/java/android/hardware/camera2/CameraMetadata.java @@ -51,7 +51,7 @@ import java.util.List; public abstract class CameraMetadata<TKey> { private static final String TAG = "CameraMetadataAb"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; /** * Set a camera metadata field to a value. The field definitions can be @@ -131,7 +131,7 @@ public abstract class CameraMetadata<TKey> { CameraMetadata<TKey> instance, int[] filterTags) { - if (VERBOSE) Log.v(TAG, "getKeysStatic for " + type); + if (DEBUG) Log.v(TAG, "getKeysStatic for " + type); // TotalCaptureResult does not have any of the keys on it, use CaptureResult instead if (type.equals(TotalCaptureResult.class)) { @@ -163,10 +163,10 @@ public abstract class CameraMetadata<TKey> { if (shouldKeyBeAdded(key, field, filterTags)) { keyList.add(key); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "getKeysStatic - key was added - " + key); } - } else if (VERBOSE) { + } else if (DEBUG) { Log.v(TAG, "getKeysStatic - key was filtered - " + key); } } diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java index f4017d0..df6c986 100644 --- a/core/java/android/hardware/camera2/CaptureResult.java +++ b/core/java/android/hardware/camera2/CaptureResult.java @@ -2649,20 +2649,35 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> { /** * <p>The correction coefficients to correct for this camera device's - * radial lens distortion.</p> - * <p>Three cofficients <code>[kappa_1, kappa_2, kappa_3]</code> that - * can be used to correct the lens's radial geometric - * distortion with the mapping equations:</p> - * <pre><code> x_c = x_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) - * y_c = y_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + * radial and tangential lens distortion.</p> + * <p>Three radial distortion coefficients <code>[kappa_1, kappa_2, + * kappa_3]</code> and two tangential distortion coefficients + * <code>[kappa_4, kappa_5]</code> that can be used to correct the + * lens's geometric distortion with the mapping equations:</p> + * <pre><code> x_c = x_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + + * kappa_4 * (2 * x_i * y_i) + kappa_5 * ( r^2 + 2 * x_i^2 ) + * y_c = y_i * ( 1 + kappa_1 * r^2 + kappa_2 * r^4 + kappa_3 * r^6 ) + + * kappa_5 * (2 * x_i * y_i) + kappa_4 * ( r^2 + 2 * y_i^2 ) * </code></pre> - * <p>where <code>[x_i, y_i]</code> are normalized coordinates with <code>(0,0)</code> - * at the lens optical center, and <code>[-1, 1]</code> are the edges of - * the active pixel array; and where <code>[x_c, y_c]</code> are the - * corrected normalized coordinates with radial distortion - * removed; and <code>r^2 = x_i^2 + y_i^2</code>.</p> + * <p>Here, <code>[x_c, y_c]</code> are the coordinates to sample in the + * input image that correspond to the pixel values in the + * corrected image at the coordinate <code>[x_i, y_i]</code>:</p> + * <pre><code> correctedImage(x_i, y_i) = sample_at(x_c, y_c, inputImage) + * </code></pre> + * <p>The pixel coordinates are defined in a normalized + * coordinate system related to the + * android.lens.intrinsicCalibration calibration fields. + * Both <code>[x_i, y_i]</code> and <code>[x_c, y_c]</code> have <code>(0,0)</code> at the + * lens optical center <code>[c_x, c_y]</code>. The maximum magnitudes + * of both x and y coordinates are normalized to be 1 at the + * edge further from the optical center, so the range + * for both dimensions is <code>-1 <= x <= 1</code>.</p> + * <p>Finally, <code>r</code> represents the radial distance from the + * optical center, <code>r^2 = x_i^2 + y_i^2</code>, and its magnitude + * is therefore no larger than <code>|r| <= sqrt(2)</code>.</p> + * <p>The distortion model used is the Brown-Conrady model.</p> * <p><b>Units</b>: - * Coefficients for a 6th-degree even radial polynomial.</p> + * Unitless coefficients.</p> * <p><b>Optional</b> - This value may be {@code null} on some devices.</p> */ @PublicKey @@ -2988,6 +3003,10 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> { * timestamps measure time in the same timebase as {@link android.os.SystemClock#elapsedRealtimeNanos }, and they can * be compared to other timestamps from other subsystems that * are using that base.</p> + * <p>For reprocessing, the timestamp will match the start of exposure of + * the input image, i.e. {@link CaptureResult#SENSOR_TIMESTAMP the + * timestamp} in the TotalCaptureResult that was used to create the + * reprocess capture request.</p> * <p><b>Units</b>: Nanoseconds</p> * <p><b>Range of valid values:</b><br> * > 0</p> diff --git a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java index 7f4a76c..7a39dd5 100644 --- a/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java +++ b/core/java/android/hardware/camera2/impl/CameraCaptureSessionImpl.java @@ -38,7 +38,7 @@ import static com.android.internal.util.Preconditions.*; public class CameraCaptureSessionImpl extends CameraCaptureSession { private static final String TAG = "CameraCaptureSession"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; /** Simple integer ID for session for debugging */ private final int mId; @@ -124,7 +124,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { if (configureSuccess) { mStateCallback.onConfigured(this); - if (VERBOSE) Log.v(TAG, mIdString + "Created session successfully"); + if (DEBUG) Log.v(TAG, mIdString + "Created session successfully"); mConfigureSuccess = true; } else { mStateCallback.onConfigureFailed(this); @@ -160,7 +160,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { handler = checkHandler(handler, callback); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, mIdString + "capture - request " + request + ", callback " + callback + " handler " + handler); } @@ -194,7 +194,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { handler = checkHandler(handler, callback); - if (VERBOSE) { + if (DEBUG) { CaptureRequest[] requestArray = requests.toArray(new CaptureRequest[0]); Log.v(TAG, mIdString + "captureBurst - requests " + Arrays.toString(requestArray) + ", callback " + callback + " handler " + handler); @@ -218,7 +218,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { handler = checkHandler(handler, callback); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, mIdString + "setRepeatingRequest - request " + request + ", callback " + callback + " handler" + " " + handler); } @@ -247,7 +247,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { handler = checkHandler(handler, callback); - if (VERBOSE) { + if (DEBUG) { CaptureRequest[] requestArray = requests.toArray(new CaptureRequest[0]); Log.v(TAG, mIdString + "setRepeatingBurst - requests " + Arrays.toString(requestArray) + ", callback " + callback + " handler" + "" + handler); @@ -261,7 +261,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { public synchronized void stopRepeating() throws CameraAccessException { checkNotClosed(); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, mIdString + "stopRepeating"); } @@ -272,7 +272,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { public synchronized void abortCaptures() throws CameraAccessException { checkNotClosed(); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, mIdString + "abortCaptures"); } @@ -325,7 +325,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { * but this would introduce nondeterministic behavior. */ - if (VERBOSE) Log.v(TAG, mIdString + "replaceSessionClose"); + if (DEBUG) Log.v(TAG, mIdString + "replaceSessionClose"); // Set up fast shutdown. Possible alternative paths: // - This session is active, so close() below starts the shutdown drain @@ -345,11 +345,11 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { public synchronized void close() { if (mClosed) { - if (VERBOSE) Log.v(TAG, mIdString + "close - reentering"); + if (DEBUG) Log.v(TAG, mIdString + "close - reentering"); return; } - if (VERBOSE) Log.v(TAG, mIdString + "close - first time"); + if (DEBUG) Log.v(TAG, mIdString + "close - first time"); mClosed = true; @@ -498,7 +498,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { @Override public void onDisconnected(CameraDevice camera) { - if (VERBOSE) Log.v(TAG, mIdString + "onDisconnected"); + if (DEBUG) Log.v(TAG, mIdString + "onDisconnected"); close(); } @@ -513,14 +513,14 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { mIdleDrainer.taskStarted(); mActive = true; - if (VERBOSE) Log.v(TAG, mIdString + "onActive"); + if (DEBUG) Log.v(TAG, mIdString + "onActive"); mStateCallback.onActive(session); } @Override public void onIdle(CameraDevice camera) { boolean isAborting; - if (VERBOSE) Log.v(TAG, mIdString + "onIdle"); + if (DEBUG) Log.v(TAG, mIdString + "onIdle"); synchronized (session) { isAborting = mAborting; @@ -562,17 +562,17 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { // TODO: Queue captures during abort instead of failing them // since the app won't be able to distinguish the two actives // Don't signal the application since there's no clean mapping here - if (VERBOSE) Log.v(TAG, mIdString + "onBusy"); + if (DEBUG) Log.v(TAG, mIdString + "onBusy"); } @Override public void onUnconfigured(CameraDevice camera) { - if (VERBOSE) Log.v(TAG, mIdString + "onUnconfigured"); + if (DEBUG) Log.v(TAG, mIdString + "onUnconfigured"); } @Override public void onSurfacePrepared(Surface surface) { - if (VERBOSE) Log.v(TAG, mIdString + "onPrepared"); + if (DEBUG) Log.v(TAG, mIdString + "onPrepared"); mStateCallback.onSurfacePrepared(session, surface); } @@ -631,7 +631,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { * If the camera is already "IDLE" and no aborts are pending, * then the drain immediately finishes. */ - if (VERBOSE) Log.v(TAG, mIdString + "onSequenceDrained"); + if (DEBUG) Log.v(TAG, mIdString + "onSequenceDrained"); // Fire session close as soon as all sequences are complete. @@ -652,7 +652,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { private class AbortDrainListener implements TaskDrainer.DrainListener { @Override public void onDrained() { - if (VERBOSE) Log.v(TAG, mIdString + "onAbortDrained"); + if (DEBUG) Log.v(TAG, mIdString + "onAbortDrained"); synchronized (CameraCaptureSessionImpl.this) { /* * Any queued aborts have now completed. @@ -676,7 +676,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { private class IdleDrainListener implements TaskDrainer.DrainListener { @Override public void onDrained() { - if (VERBOSE) Log.v(TAG, mIdString + "onIdleDrained"); + if (DEBUG) Log.v(TAG, mIdString + "onIdleDrained"); // Take device lock before session lock so that we can call back into device // without causing a deadlock @@ -690,7 +690,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { * * This operation is idempotent; a session will not be closed twice. */ - if (VERBOSE) + if (DEBUG) Log.v(TAG, mIdString + "Session drain complete, skip unconfigure: " + mSkipUnconfigure); @@ -712,7 +712,7 @@ public class CameraCaptureSessionImpl extends CameraCaptureSession { // TODO: call onError instead of onClosed if this happens } catch (IllegalStateException e) { // Camera is already closed, so nothing left to do - if (VERBOSE) Log.v(TAG, mIdString + + if (DEBUG) Log.v(TAG, mIdString + "Camera was already closed or busy, skipping unconfigure"); } diff --git a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java index c4e8b15..e60e266 100644 --- a/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java +++ b/core/java/android/hardware/camera2/impl/CameraDeviceImpl.java @@ -58,7 +58,7 @@ import java.util.TreeMap; */ public class CameraDeviceImpl extends CameraDevice { private final String TAG; - private final boolean DEBUG; + private final boolean DEBUG = false; private static final int REQUEST_ID_NONE = -1; @@ -240,7 +240,6 @@ public class CameraDeviceImpl extends CameraDevice { tag = tag.substring(0, MAX_TAG_LEN); } TAG = tag; - DEBUG = Log.isLoggable(TAG, Log.DEBUG); Integer partialCount = mCharacteristics.get(CameraCharacteristics.REQUEST_PARTIAL_RESULT_COUNT); diff --git a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java index b8b7d12..10dd8ae 100644 --- a/core/java/android/hardware/camera2/impl/CameraMetadataNative.java +++ b/core/java/android/hardware/camera2/impl/CameraMetadataNative.java @@ -222,7 +222,8 @@ public class CameraMetadataNative implements Parcelable { } private static final String TAG = "CameraMetadataJV"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; + // this should be in sync with HAL_PIXEL_FORMAT_BLOB defined in graphics.h public static final int NATIVE_JPEG_FORMAT = 0x21; @@ -1197,7 +1198,7 @@ public class CameraMetadataNative implements Parcelable { @SuppressWarnings({ "unchecked", "rawtypes" }) private static void registerAllMarshalers() { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "Shall register metadata marshalers"); } @@ -1234,7 +1235,7 @@ public class CameraMetadataNative implements Parcelable { for (MarshalQueryable query : queryList) { MarshalRegistry.registerMarshalQueryable(query); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "Registered metadata marshalers"); } } diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceState.java b/core/java/android/hardware/camera2/legacy/CameraDeviceState.java index 89e2d98..2c2ad1c 100644 --- a/core/java/android/hardware/camera2/legacy/CameraDeviceState.java +++ b/core/java/android/hardware/camera2/legacy/CameraDeviceState.java @@ -41,7 +41,7 @@ import android.util.Log; */ public class CameraDeviceState { private static final String TAG = "CameraDeviceState"; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private static final int STATE_ERROR = 0; private static final int STATE_UNCONFIGURED = 1; diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java index edad00f..bc0a3a8 100644 --- a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java +++ b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java @@ -61,7 +61,7 @@ import java.util.List; public class CameraDeviceUserShim implements ICameraDeviceUser { private static final String TAG = "CameraDeviceUserShim"; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private static final int OPEN_CAMERA_TIMEOUT_MS = 5000; // 5 sec (same as api1 cts timeout) private final LegacyCameraDevice mLegacyDevice; diff --git a/core/java/android/hardware/camera2/legacy/CaptureCollector.java b/core/java/android/hardware/camera2/legacy/CaptureCollector.java index 8404e86..eb48a01 100644 --- a/core/java/android/hardware/camera2/legacy/CaptureCollector.java +++ b/core/java/android/hardware/camera2/legacy/CaptureCollector.java @@ -34,7 +34,7 @@ import java.util.concurrent.locks.ReentrantLock; public class CaptureCollector { private static final String TAG = "CaptureCollector"; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private static final int FLAG_RECEIVED_JPEG = 1; private static final int FLAG_RECEIVED_JPEG_TS = 2; diff --git a/core/java/android/hardware/camera2/legacy/GLThreadManager.java b/core/java/android/hardware/camera2/legacy/GLThreadManager.java index b160d2a..152d82d 100644 --- a/core/java/android/hardware/camera2/legacy/GLThreadManager.java +++ b/core/java/android/hardware/camera2/legacy/GLThreadManager.java @@ -35,7 +35,7 @@ import static com.android.internal.util.Preconditions.*; */ public class GLThreadManager { private final String TAG; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private static final int MSG_NEW_CONFIGURATION = 1; private static final int MSG_NEW_FRAME = 2; diff --git a/core/java/android/hardware/camera2/legacy/LegacyCameraDevice.java b/core/java/android/hardware/camera2/legacy/LegacyCameraDevice.java index b5a019d..098c2d8 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyCameraDevice.java +++ b/core/java/android/hardware/camera2/legacy/LegacyCameraDevice.java @@ -59,10 +59,9 @@ import static com.android.internal.util.Preconditions.*; * </p> */ public class LegacyCameraDevice implements AutoCloseable { - public static final String DEBUG_PROP = "HAL1ShimLogging"; private final String TAG; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private final int mCameraId; private final CameraCharacteristics mStaticCharacteristics; private final ICameraDeviceCallbacks mDeviceCallbacks; diff --git a/core/java/android/hardware/camera2/legacy/LegacyFaceDetectMapper.java b/core/java/android/hardware/camera2/legacy/LegacyFaceDetectMapper.java index e576beb..882a7f4 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyFaceDetectMapper.java +++ b/core/java/android/hardware/camera2/legacy/LegacyFaceDetectMapper.java @@ -44,7 +44,7 @@ import static com.android.internal.util.Preconditions.*; @SuppressWarnings("deprecation") public class LegacyFaceDetectMapper { private static String TAG = "LegacyFaceDetectMapper"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private final Camera mCamera; /** Is the camera capable of face detection? */ @@ -97,7 +97,7 @@ public class LegacyFaceDetectMapper { } } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "onFaceDetection - read " + lengthFaces + " faces"); } } @@ -170,13 +170,13 @@ public class LegacyFaceDetectMapper { if (enableFaceDetect) { mCamera.startFaceDetection(); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "processFaceDetectMode - start face detection"); } } else { mCamera.stopFaceDetection(); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "processFaceDetectMode - stop face detection"); } @@ -248,7 +248,7 @@ public class LegacyFaceDetectMapper { } } - if (VERBOSE && previousFaces != faces) { // Log only in verbose and IF the faces changed + if (DEBUG && previousFaces != faces) { // Log only in verbose and IF the faces changed Log.v(TAG, "mapResultFaces - changed to " + ListUtils.listToString(convertedFaces)); } diff --git a/core/java/android/hardware/camera2/legacy/LegacyFocusStateMapper.java b/core/java/android/hardware/camera2/legacy/LegacyFocusStateMapper.java index d5ec71a..d33c09e 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyFocusStateMapper.java +++ b/core/java/android/hardware/camera2/legacy/LegacyFocusStateMapper.java @@ -38,7 +38,7 @@ import static com.android.internal.util.Preconditions.*; @SuppressWarnings("deprecation") public class LegacyFocusStateMapper { private static String TAG = "LegacyFocusStateMapper"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private final Camera mCamera; @@ -90,7 +90,7 @@ public class LegacyFocusStateMapper { final String afMode = parameters.getFocusMode(); if (!Objects.equals(mAfModePrevious, afMode)) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "processRequestTriggers - AF mode switched from " + mAfModePrevious + " to " + afMode); } @@ -120,7 +120,7 @@ public class LegacyFocusStateMapper { synchronized (mLock) { int latestAfRun = mAfRun; - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "onAutoFocusMoving - start " + start + " latest AF run " + latestAfRun + ", last AF run " + currentAfRun @@ -192,7 +192,7 @@ public class LegacyFocusStateMapper { mAfState = afStateAfterStart; } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "processRequestTriggers - got AF_TRIGGER_START, " + "new AF run is " + currentAfRun); } @@ -208,7 +208,7 @@ public class LegacyFocusStateMapper { synchronized (mLock) { int latestAfRun = mAfRun; - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "onAutoFocus - success " + success + " latest AF run " + latestAfRun + ", last AF run " + currentAfRun); } @@ -255,7 +255,7 @@ public class LegacyFocusStateMapper { mCamera.cancelAutoFocus(); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "processRequestTriggers - got AF_TRIGGER_CANCEL, " + "new AF run is " + updatedAfRun); } @@ -288,7 +288,7 @@ public class LegacyFocusStateMapper { newAfState = mAfState; } - if (VERBOSE && newAfState != mAfStatePrevious) { + if (DEBUG && newAfState != mAfStatePrevious) { Log.v(TAG, String.format("mapResultTriggers - afState changed from %s to %s", afStateToString(mAfStatePrevious), afStateToString(newAfState))); } diff --git a/core/java/android/hardware/camera2/legacy/LegacyMetadataMapper.java b/core/java/android/hardware/camera2/legacy/LegacyMetadataMapper.java index 2de846c..33a802b 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyMetadataMapper.java +++ b/core/java/android/hardware/camera2/legacy/LegacyMetadataMapper.java @@ -55,7 +55,7 @@ import static android.hardware.camera2.legacy.ParameterUtils.*; @SuppressWarnings("deprecation") public class LegacyMetadataMapper { private static final String TAG = "LegacyMetadataMapper"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private static final long NS_PER_MS = 1000000; @@ -152,7 +152,7 @@ public class LegacyMetadataMapper { params.unflatten(parameters); mapCharacteristicsFromParameters(m, params); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "createCharacteristics metadata:"); Log.v(TAG, "--------------------------------------------------- (start)"); m.dumpToLog(); @@ -284,7 +284,7 @@ public class LegacyMetadataMapper { Camera.Size maxJpegSize = SizeAreaComparator.findLargestByArea(jpegSizes); float jpegAspectRatio = maxJpegSize.width * 1.0f / maxJpegSize.height; - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, String.format("mapScalerStreamConfigs - largest JPEG area %dx%d, AR=%f", maxJpegSize.width, maxJpegSize.height, jpegAspectRatio)); } @@ -300,7 +300,7 @@ public class LegacyMetadataMapper { PREVIEW_ASPECT_RATIO_TOLERANCE) { previewSizes.remove(index); // Assume removing from end is O(1) - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, String.format( "mapScalerStreamConfigs - removed preview size %dx%d, AR=%f " + "was not the same", @@ -329,7 +329,7 @@ public class LegacyMetadataMapper { for (int format : p.getSupportedPreviewFormats()) { if (ImageFormat.isPublicFormat(format) && format != ImageFormat.NV21) { appendStreamConfig(availableStreamConfigs, format, previewSizes); - } else if (VERBOSE) { + } else if (DEBUG) { /* * Do not add any formats unknown to us * (since it would fail runtime checks in StreamConfigurationMap) @@ -388,7 +388,7 @@ public class LegacyMetadataMapper { int j = 0; for (String mode : antiBandingModes) { int convertedMode = convertAntiBandingMode(mode); - if (VERBOSE && convertedMode == -1) { + if (DEBUG && convertedMode == -1) { Log.v(TAG, "Antibanding mode " + ((mode == null) ? "NULL" : mode) + " not supported, skipping..."); } else { @@ -525,7 +525,7 @@ public class LegacyMetadataMapper { m.set(CONTROL_AF_AVAILABLE_MODES, ArrayUtils.toIntArray(afAvail)); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapControlAf - control.afAvailableModes set to " + ListUtils.listToString(afAvail)); } @@ -575,7 +575,7 @@ public class LegacyMetadataMapper { m.set(CONTROL_AWB_AVAILABLE_MODES, ArrayUtils.toIntArray(awbAvail)); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapControlAwb - control.awbAvailableModes set to " + ListUtils.listToString(awbAvail)); } @@ -681,7 +681,7 @@ public class LegacyMetadataMapper { * We can tell if the lens is fixed focus; * but if it's not, we can't tell the minimum focus distance, so leave it null then. */ - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapLens - focus-mode='" + p.getFocusMode() + "'"); } @@ -691,11 +691,11 @@ public class LegacyMetadataMapper { */ m.set(LENS_INFO_MINIMUM_FOCUS_DISTANCE, LENS_INFO_MINIMUM_FOCUS_DISTANCE_FIXED_FOCUS); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapLens - lens.info.minimumFocusDistance = 0"); } } else { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapLens - lens.info.minimumFocusDistance is unknown"); } } @@ -752,12 +752,14 @@ public class LegacyMetadataMapper { CameraCharacteristics.CONTROL_AE_AVAILABLE_TARGET_FPS_RANGES , CameraCharacteristics.CONTROL_AE_COMPENSATION_RANGE , CameraCharacteristics.CONTROL_AE_COMPENSATION_STEP , + CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE , CameraCharacteristics.CONTROL_AF_AVAILABLE_MODES , CameraCharacteristics.CONTROL_AVAILABLE_EFFECTS , CameraCharacteristics.CONTROL_AVAILABLE_MODES , CameraCharacteristics.CONTROL_AVAILABLE_SCENE_MODES , CameraCharacteristics.CONTROL_AVAILABLE_VIDEO_STABILIZATION_MODES , CameraCharacteristics.CONTROL_AWB_AVAILABLE_MODES , + CameraCharacteristics.CONTROL_AWB_LOCK_AVAILABLE , CameraCharacteristics.CONTROL_MAX_REGIONS , CameraCharacteristics.FLASH_INFO_AVAILABLE , CameraCharacteristics.INFO_SUPPORTED_HARDWARE_LEVEL , @@ -1340,7 +1342,7 @@ public class LegacyMetadataMapper { } } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "createRequestTemplate (templateId=" + templateId + ")," + " afMode=" + afMode + ", minimumFocusDistance=" + minimumFocusDistance); } diff --git a/core/java/android/hardware/camera2/legacy/LegacyRequestMapper.java b/core/java/android/hardware/camera2/legacy/LegacyRequestMapper.java index 3688610..d5d7f0d 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyRequestMapper.java +++ b/core/java/android/hardware/camera2/legacy/LegacyRequestMapper.java @@ -42,7 +42,7 @@ import static android.hardware.camera2.CaptureRequest.*; @SuppressWarnings("deprecation") public class LegacyRequestMapper { private static final String TAG = "LegacyRequestMapper"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; /** Default quality for android.jpeg.quality, android.jpeg.thumbnailQuality */ private static final byte DEFAULT_JPEG_QUALITY = 85; @@ -75,7 +75,7 @@ public class LegacyRequestMapper { if (params.isZoomSupported()) { params.setZoom(zoomData.zoomIndex); - } else if (VERBOSE) { + } else if (DEBUG) { Log.v(TAG, "convertRequestToMetadata - zoom is not supported"); } } @@ -210,7 +210,7 @@ public class LegacyRequestMapper { params.setAutoExposureLock(aeLock); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertRequestToMetadata - control.aeLock set to " + aeLock); } @@ -231,7 +231,7 @@ public class LegacyRequestMapper { params.setFocusMode(focusMode); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertRequestToMetadata - control.afMode " + afMode + " mapped to " + focusMode); } @@ -250,7 +250,7 @@ public class LegacyRequestMapper { params.setWhiteBalance(whiteBalanceMode); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertRequestToMetadata - control.awbMode " + awbMode + " mapped to " + whiteBalanceMode); } @@ -520,7 +520,7 @@ public class LegacyRequestMapper { " regions, ignoring all beyond the first " + maxNumMeteringAreas); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertMeteringRegionsToLegacy - " + regionName + " areas = " + ParameterUtils.stringFromAreaList(meteringAreaList)); } @@ -593,7 +593,7 @@ public class LegacyRequestMapper { p.setFlashMode(flashModeSetting); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapAeAndFlashMode - set flash.mode (api1) to " + flashModeSetting + ", requested (api2) " + flashMode diff --git a/core/java/android/hardware/camera2/legacy/LegacyResultMapper.java b/core/java/android/hardware/camera2/legacy/LegacyResultMapper.java index bad1d28..ce85005 100644 --- a/core/java/android/hardware/camera2/legacy/LegacyResultMapper.java +++ b/core/java/android/hardware/camera2/legacy/LegacyResultMapper.java @@ -42,7 +42,7 @@ import static android.hardware.camera2.CaptureResult.*; @SuppressWarnings("deprecation") public class LegacyResultMapper { private static final String TAG = "LegacyResultMapper"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private LegacyRequest mCachedRequest = null; private CameraMetadataNative mCachedResult = null; @@ -88,7 +88,7 @@ public class LegacyResultMapper { result.set(SENSOR_TIMESTAMP, timestamp); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "cachedConvertResultMetadata - cached? " + cached + " timestamp = " + timestamp); @@ -306,7 +306,7 @@ public class LegacyResultMapper { { boolean lock = p.isAutoExposureLockSupported() ? p.getAutoExposureLock() : false; m.set(CONTROL_AE_LOCK, lock); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "mapAe - android.control.aeLock = " + lock + ", supported = " + p.isAutoExposureLockSupported()); @@ -332,7 +332,7 @@ public class LegacyResultMapper { // control.aeRegions if (p.getMaxNumMeteringAreas() > 0) { - if (VERBOSE) { + if (DEBUG) { String meteringAreas = p.get("metering-areas"); Log.v(TAG, "mapAe - parameter dump; metering-areas: " + meteringAreas); } @@ -352,7 +352,7 @@ public class LegacyResultMapper { // control.afRegions if (p.getMaxNumFocusAreas() > 0) { - if (VERBOSE) { + if (DEBUG) { String focusAreas = p.get("focus-areas"); Log.v(TAG, "mapAe - parameter dump; focus-areas: " + focusAreas); } @@ -392,7 +392,7 @@ public class LegacyResultMapper { } } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "Metering rectangles for " + regionName + ": " + ListUtils.listToString(meteringRectList)); diff --git a/core/java/android/hardware/camera2/legacy/ParameterUtils.java b/core/java/android/hardware/camera2/legacy/ParameterUtils.java index 32bbc51..3cfd020 100644 --- a/core/java/android/hardware/camera2/legacy/ParameterUtils.java +++ b/core/java/android/hardware/camera2/legacy/ParameterUtils.java @@ -225,7 +225,7 @@ public class ParameterUtils { } private static final String TAG = "ParameterUtils"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; /** getZoomRatios stores zoom ratios in 1/100 increments, e.x. a zoom of 3.2 is 320 */ private static final int ZOOM_RATIO_MULTIPLIER = 100; @@ -398,7 +398,7 @@ public class ParameterUtils { Rect cropRegionAsPreview = shrinkToSameAspectRatioCentered(previewCrop, actualCrop); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "getClosestAvailableZoomCrop - actualCrop = " + actualCrop); Log.v(TAG, "getClosestAvailableZoomCrop - previewCrop = " + previewCrop); @@ -418,7 +418,7 @@ public class ParameterUtils { List<Rect> availablePreviewCropRegions = getAvailablePreviewZoomCropRectangles(params, activeArray, streamSize); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "getClosestAvailableZoomCrop - availableReportedCropRegions = " + ListUtils.listToString(availableReportedCropRegions)); @@ -758,7 +758,7 @@ public class ParameterUtils { userCropRegion = activeArraySizeOnly; } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertScalerCropRegion - user crop region was " + userCropRegion); } @@ -768,7 +768,7 @@ public class ParameterUtils { previewSize, userCropRegion, /*out*/reportedCropRegion, /*out*/previewCropRegion); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "convertScalerCropRegion - zoom calculated to: " + "zoomIndex = " + zoomIdx + ", reported crop region = " + reportedCropRegion + @@ -862,7 +862,7 @@ public class ParameterUtils { reportedMetering = reportedMeteringRect.rect; } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, String.format( "convertMeteringRectangleToLegacy - activeArray = %s, meteringRect = %s, " + "previewCrop = %s, meteringArea = %s, previewMetering = %s, " + diff --git a/core/java/android/hardware/camera2/legacy/RequestThreadManager.java b/core/java/android/hardware/camera2/legacy/RequestThreadManager.java index 691798f..5ea1ab8 100644 --- a/core/java/android/hardware/camera2/legacy/RequestThreadManager.java +++ b/core/java/android/hardware/camera2/legacy/RequestThreadManager.java @@ -62,10 +62,9 @@ public class RequestThreadManager { private final int mCameraId; private final RequestHandlerThread mRequestThread; - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; // For slightly more spammy messages that will get repeated every frame - private static final boolean VERBOSE = - Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.VERBOSE); + private static final boolean VERBOSE = false; private Camera mCamera; private final CameraCharacteristics mCharacteristics; diff --git a/core/java/android/hardware/camera2/legacy/SurfaceTextureRenderer.java b/core/java/android/hardware/camera2/legacy/SurfaceTextureRenderer.java index 615b2c8..f928a55 100644 --- a/core/java/android/hardware/camera2/legacy/SurfaceTextureRenderer.java +++ b/core/java/android/hardware/camera2/legacy/SurfaceTextureRenderer.java @@ -49,7 +49,7 @@ import java.util.List; */ public class SurfaceTextureRenderer { private static final String TAG = SurfaceTextureRenderer.class.getSimpleName(); - private static final boolean DEBUG = Log.isLoggable(LegacyCameraDevice.DEBUG_PROP, Log.DEBUG); + private static final boolean DEBUG = false; private static final int EGL_RECORDABLE_ANDROID = 0x3142; // from EGL/eglext.h private static final int GL_MATRIX_SIZE = 16; private static final int VERTEX_POS_SIZE = 3; diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableArray.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableArray.java index d89518b..ebc74f0 100644 --- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableArray.java +++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableArray.java @@ -39,7 +39,7 @@ import java.util.ArrayList; public class MarshalQueryableArray<T> implements MarshalQueryable<T> { private static final String TAG = MarshalQueryableArray.class.getSimpleName(); - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private class MarshalerArray extends Marshaler<T> { private final Class<T> mClass; @@ -81,7 +81,7 @@ public class MarshalQueryableArray<T> implements MarshalQueryable<T> { + "; but there are " + (remaining % elementSize) + " left over bytes"); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, String.format( "Attempting to unpack array (count = %d, element size = %d, bytes " + "remaining = %d) for type %s", diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java index fa53db2..621a418 100644 --- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java +++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableEnum.java @@ -38,7 +38,7 @@ import static android.hardware.camera2.marshal.MarshalHelpers.*; public class MarshalQueryableEnum<T extends Enum<T>> implements MarshalQueryable<T> { private static final String TAG = MarshalQueryableEnum.class.getSimpleName(); - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private static final int UINT8_MIN = 0x0; private static final int UINT8_MAX = (1 << Byte.SIZE) - 1; @@ -110,7 +110,7 @@ public class MarshalQueryableEnum<T extends Enum<T>> implements MarshalQueryable Class<?> typeClass = (Class<?>)managedType.getType(); if (typeClass.isEnum()) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "possible enum detected for " + typeClass); } @@ -151,7 +151,7 @@ public class MarshalQueryableEnum<T extends Enum<T>> implements MarshalQueryable "Expected values array to be the same size as the enumTypes values " + values.length + " for type " + enumType); } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "Registered enum values for type " + enumType + " values"); } diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableParcelable.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableParcelable.java index 0b7a4bf..fdde205 100644 --- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableParcelable.java +++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableParcelable.java @@ -34,7 +34,7 @@ public class MarshalQueryableParcelable<T extends Parcelable> implements MarshalQueryable<T> { private static final String TAG = "MarshalParcelable"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private static final String FIELD_CREATOR = "CREATOR"; @@ -70,7 +70,7 @@ public class MarshalQueryableParcelable<T extends Parcelable> @Override public void marshal(T value, ByteBuffer buffer) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "marshal " + value); } @@ -100,7 +100,7 @@ public class MarshalQueryableParcelable<T extends Parcelable> @Override public T unmarshal(ByteBuffer buffer) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "unmarshal, buffer remaining " + buffer.remaining()); } @@ -142,7 +142,7 @@ public class MarshalQueryableParcelable<T extends Parcelable> buffer.reset(); buffer.position(buffer.position() + actualLength); - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "unmarshal, parcel length was " + actualLength); Log.v(TAG, "unmarshal, value is " + value); } @@ -165,7 +165,7 @@ public class MarshalQueryableParcelable<T extends Parcelable> value.writeToParcel(parcel, /*flags*/0); int length = parcel.marshall().length; - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "calculateMarshalSize, length when parceling " + value + " is " + length); } diff --git a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableString.java b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableString.java index bf518bb..d2c3908 100644 --- a/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableString.java +++ b/core/java/android/hardware/camera2/marshal/impl/MarshalQueryableString.java @@ -31,7 +31,7 @@ import static android.hardware.camera2.impl.CameraMetadataNative.*; public class MarshalQueryableString implements MarshalQueryable<String> { private static final String TAG = MarshalQueryableString.class.getSimpleName(); - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; private static final Charset UTF8_CHARSET = Charset.forName("UTF-8"); private static final byte NUL = (byte)'\0'; // used as string terminator @@ -72,7 +72,7 @@ public class MarshalQueryableString implements MarshalQueryable<String> { stringLength++; } - if (VERBOSE) { + if (DEBUG) { Log.v(TAG, "unmarshal - scanned " + stringLength + " characters; found null? " + foundNull); diff --git a/core/java/android/hardware/camera2/utils/ArrayUtils.java b/core/java/android/hardware/camera2/utils/ArrayUtils.java index 79a335c..99ddf6e 100644 --- a/core/java/android/hardware/camera2/utils/ArrayUtils.java +++ b/core/java/android/hardware/camera2/utils/ArrayUtils.java @@ -28,7 +28,7 @@ import java.util.Objects; public class ArrayUtils { private static final String TAG = "ArrayUtils"; - private static final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private static final boolean DEBUG = false; /** Return the index of {@code needle} in the {@code array}, or else {@code -1} */ public static <T> int getArrayIndex(T[] array, T needle) { @@ -117,7 +117,7 @@ public class ArrayUtils { // Guard against unexpected values if (strIndex < 0) { - if (VERBOSE) Log.v(TAG, "Ignoring invalid value " + str); + if (DEBUG) Log.v(TAG, "Ignoring invalid value " + str); continue; } diff --git a/core/java/android/hardware/camera2/utils/TaskDrainer.java b/core/java/android/hardware/camera2/utils/TaskDrainer.java index dc09f62..7c46e50 100644 --- a/core/java/android/hardware/camera2/utils/TaskDrainer.java +++ b/core/java/android/hardware/camera2/utils/TaskDrainer.java @@ -52,7 +52,7 @@ public class TaskDrainer<T> { } private static final String TAG = "TaskDrainer"; - private final boolean VERBOSE = Log.isLoggable(TAG, Log.VERBOSE); + private final boolean DEBUG = false; private final Handler mHandler; private final DrainListener mListener; @@ -110,7 +110,7 @@ public class TaskDrainer<T> { */ public void taskStarted(T task) { synchronized (mLock) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG + "[" + mName + "]", "taskStarted " + task); } @@ -141,7 +141,7 @@ public class TaskDrainer<T> { */ public void taskFinished(T task) { synchronized (mLock) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG + "[" + mName + "]", "taskFinished " + task); } @@ -163,7 +163,7 @@ public class TaskDrainer<T> { public void beginDrain() { synchronized (mLock) { if (!mDraining) { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG + "[" + mName + "]", "beginDrain started"); } @@ -172,7 +172,7 @@ public class TaskDrainer<T> { // If all tasks that had started had already finished by now, fire #onDrained checkIfDrainFinished(); } else { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG + "[" + mName + "]", "beginDrain ignored"); } } @@ -190,7 +190,7 @@ public class TaskDrainer<T> { mHandler.post(new Runnable() { @Override public void run() { - if (VERBOSE) { + if (DEBUG) { Log.v(TAG + "[" + mName + "]", "onDrained"); } diff --git a/core/java/android/net/IpReachabilityMonitor.java b/core/java/android/net/IpReachabilityMonitor.java index 3cfd8b2..88fb014 100644 --- a/core/java/android/net/IpReachabilityMonitor.java +++ b/core/java/android/net/IpReachabilityMonitor.java @@ -99,16 +99,10 @@ public class IpReachabilityMonitor { public static boolean probeNeighbor(int ifIndex, InetAddress ip) { final long IO_TIMEOUT = 300L; final String msgSnippet = "probing ip=" + ip.getHostAddress() + "%" + ifIndex; - // This currently does not cause neighbor probing if the target |ip| - // has been confirmed reachable within the past "delay_probe_time" - // seconds, i.e. within the past 5 seconds. - // - // TODO: replace with a transition directly to NUD_PROBE state once - // kernels are updated to do so correctly. if (DBG) { Log.d(TAG, msgSnippet); } final byte[] msg = RtNetlinkNeighborMessage.newNewNeighborMessage( - 1, ip, StructNdMsg.NUD_DELAY, ifIndex, null); + 1, ip, StructNdMsg.NUD_PROBE, ifIndex, null); boolean returnValue = false; try (NetlinkSocket nlSocket = new NetlinkSocket(OsConstants.NETLINK_ROUTE)) { diff --git a/core/java/android/os/BatteryStats.java b/core/java/android/os/BatteryStats.java index 56e919a..0a45b8b 100644 --- a/core/java/android/os/BatteryStats.java +++ b/core/java/android/os/BatteryStats.java @@ -132,6 +132,16 @@ public abstract class BatteryStats implements Parcelable { public static final int AUDIO_TURNED_ON = 15; /** + * A constant indicating a flashlight turn on timer + */ + public static final int FLASHLIGHT_TURNED_ON = 16; + + /** + * A constant indicating a camera turn on timer + */ + public static final int CAMERA_TURNED_ON = 17; + + /** * Include all of the data in the stats, including previously saved data. */ public static final int STATS_SINCE_CHARGED = 0; @@ -208,6 +218,10 @@ public abstract class BatteryStats implements Parcelable { private static final String CHARGE_STEP_DATA = "csd"; private static final String DISCHARGE_TIME_REMAIN_DATA = "dtr"; private static final String CHARGE_TIME_REMAIN_DATA = "ctr"; + private static final String FLASHLIGHT_DATA = "fla"; + private static final String CAMERA_DATA = "cam"; + private static final String VIDEO_DATA = "vid"; + private static final String AUDIO_DATA = "aud"; private final StringBuilder mFormatBuilder = new StringBuilder(32); private final Formatter mFormatter = new Formatter(mFormatBuilder); @@ -381,8 +395,10 @@ public abstract class BatteryStats implements Parcelable { public abstract long getWifiBatchedScanTime(int csphBin, long elapsedRealtimeUs, int which); public abstract int getWifiBatchedScanCount(int csphBin, int which); public abstract long getWifiMulticastTime(long elapsedRealtimeUs, int which); - public abstract long getAudioTurnedOnTime(long elapsedRealtimeUs, int which); - public abstract long getVideoTurnedOnTime(long elapsedRealtimeUs, int which); + public abstract Timer getAudioTurnedOnTimer(); + public abstract Timer getVideoTurnedOnTimer(); + public abstract Timer getFlashlightTurnedOnTimer(); + public abstract Timer getCameraTurnedOnTimer(); public abstract Timer getForegroundActivityTimer(); // Time this uid has any processes in foreground state. @@ -1106,6 +1122,7 @@ public abstract class BatteryStats implements Parcelable { public static final int STATE2_CHARGING_FLAG = 1<<25; public static final int STATE2_PHONE_IN_CALL_FLAG = 1<<24; public static final int STATE2_BLUETOOTH_ON_FLAG = 1<<23; + public static final int STATE2_CAMERA_FLAG = 1<<22; public static final int MOST_INTERESTING_STATES2 = STATE2_POWER_SAVE_FLAG | STATE2_WIFI_ON_FLAG | STATE2_DEVICE_IDLE_FLAG @@ -1813,6 +1830,7 @@ public abstract class BatteryStats implements Parcelable { new BitDescription(HistoryItem.STATE2_WIFI_SUPPL_STATE_MASK, HistoryItem.STATE2_WIFI_SUPPL_STATE_SHIFT, "wifi_suppl", "Wsp", WIFI_SUPPL_STATE_NAMES, WIFI_SUPPL_STATE_SHORT_NAMES), + new BitDescription(HistoryItem.STATE2_CAMERA_FLAG, "camera", "ca"), }; public static final String[] HISTORY_EVENT_NAMES = new String[] { @@ -2317,10 +2335,10 @@ public abstract class BatteryStats implements Parcelable { */ private static final String printWakeLock(StringBuilder sb, Timer timer, long elapsedRealtimeUs, String name, int which, String linePrefix) { - + if (timer != null) { long totalTimeMillis = computeWakeLock(timer, elapsedRealtimeUs, which); - + int count = timer.getCountLocked(which); if (totalTimeMillis != 0) { sb.append(linePrefix); @@ -2337,6 +2355,40 @@ public abstract class BatteryStats implements Parcelable { } return linePrefix; } + + /** + * + * @param pw a PrintWriter object to print to. + * @param sb a StringBuilder object. + * @param timer a Timer object contining the wakelock times. + * @param rawRealtime the current on-battery time in microseconds. + * @param which which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT. + * @param prefix a String to be prepended to each line of output. + * @param type the name of the timer. + */ + private static final boolean printTimer(PrintWriter pw, StringBuilder sb, Timer timer, + long rawRealtime, int which, String prefix, String type) { + if (timer != null) { + // Convert from microseconds to milliseconds with rounding + final long totalTime = (timer.getTotalTimeLocked( + rawRealtime, which) + 500) / 1000; + final int count = timer.getCountLocked(which); + if (totalTime != 0) { + sb.setLength(0); + sb.append(prefix); + sb.append(" "); + sb.append(type); + sb.append(": "); + formatTimeMs(sb, totalTime); + sb.append("realtime ("); + sb.append(count); + sb.append(" times)"); + pw.println(sb.toString()); + return true; + } + } + return false; + } /** * Checkin version of wakelock printer. Prints simple comma-separated list. @@ -2375,12 +2427,15 @@ public abstract class BatteryStats implements Parcelable { */ private static final void dumpLine(PrintWriter pw, int uid, String category, String type, Object... args ) { - pw.print(BATTERY_STATS_CHECKIN_VERSION); pw.print(','); - pw.print(uid); pw.print(','); - pw.print(category); pw.print(','); + pw.print(BATTERY_STATS_CHECKIN_VERSION); + pw.print(','); + pw.print(uid); + pw.print(','); + pw.print(category); + pw.print(','); pw.print(type); - - for (Object arg : args) { + + for (Object arg : args) { pw.print(','); pw.print(arg); } @@ -2388,6 +2443,30 @@ public abstract class BatteryStats implements Parcelable { } /** + * Dump a given timer stat for terse checkin mode. + * + * @param pw the PageWriter to dump log to + * @param uid the UID to log + * @param category category of data (e.g. "total", "last", "unplugged", "current" ) + * @param type type of data (e.g. "wakelock", "sensor", "process", "apk" , "process", "network") + * @param timer a {@link Timer} to dump stats for + * @param rawRealtime the current elapsed realtime of the system in microseconds + * @param which one of STATS_SINCE_CHARGED, STATS_SINCE_UNPLUGGED, or STATS_CURRENT + */ + private static final void dumpTimer(PrintWriter pw, int uid, String category, String type, + Timer timer, long rawRealtime, int which) { + if (timer != null) { + // Convert from microseconds to milliseconds with rounding + final long totalTime = (timer.getTotalTimeLocked(rawRealtime, which) + 500) + / 1000; + final int count = timer.getCountLocked(which); + if (totalTime != 0) { + dumpLine(pw, uid, category, type, totalTime, count); + } + } + } + + /** * Temporary for settings. */ public final void dumpCheckinLocked(Context context, PrintWriter pw, int which, int reqUid) { @@ -2764,6 +2843,15 @@ public abstract class BatteryStats implements Parcelable { } } + dumpTimer(pw, uid, category, FLASHLIGHT_DATA, u.getFlashlightTurnedOnTimer(), + rawRealtime, which); + dumpTimer(pw, uid, category, CAMERA_DATA, u.getCameraTurnedOnTimer(), + rawRealtime, which); + dumpTimer(pw, uid, category, VIDEO_DATA, u.getVideoTurnedOnTimer(), + rawRealtime, which); + dumpTimer(pw, uid, category, AUDIO_DATA, u.getAudioTurnedOnTimer(), + rawRealtime, which); + final SparseArray<? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats(); final int NSE = sensors.size(); for (int ise=0; ise<NSE; ise++) { @@ -2781,27 +2869,11 @@ public abstract class BatteryStats implements Parcelable { } } - final Timer vibTimer = u.getVibratorOnTimer(); - if (vibTimer != null) { - // Convert from microseconds to milliseconds with rounding - final long totalTime = (vibTimer.getTotalTimeLocked(rawRealtime, which) + 500) - / 1000; - final int count = vibTimer.getCountLocked(which); - if (totalTime != 0) { - dumpLine(pw, uid, category, VIBRATOR_DATA, totalTime, count); - } - } + dumpTimer(pw, uid, category, VIBRATOR_DATA, u.getVibratorOnTimer(), + rawRealtime, which); - final Timer fgTimer = u.getForegroundActivityTimer(); - if (fgTimer != null) { - // Convert from microseconds to milliseconds with rounding - final long totalTime = (fgTimer.getTotalTimeLocked(rawRealtime, which) + 500) - / 1000; - final int count = fgTimer.getCountLocked(which); - if (totalTime != 0) { - dumpLine(pw, uid, category, FOREGROUND_DATA, totalTime, count); - } - } + dumpTimer(pw, uid, category, FOREGROUND_DATA, u.getForegroundActivityTimer(), + rawRealtime, which); final Object[] stateTimes = new Object[Uid.NUM_PROCESS_STATE]; long totalStateTime = 0; @@ -3810,6 +3882,15 @@ public abstract class BatteryStats implements Parcelable { uidActivity = true; } + uidActivity |= printTimer(pw, sb, u.getFlashlightTurnedOnTimer(), rawRealtime, which, + prefix, "Flashlight"); + uidActivity |= printTimer(pw, sb, u.getCameraTurnedOnTimer(), rawRealtime, which, + prefix, "Camera"); + uidActivity |= printTimer(pw, sb, u.getVideoTurnedOnTimer(), rawRealtime, which, + prefix, "Video"); + uidActivity |= printTimer(pw, sb, u.getAudioTurnedOnTimer(), rawRealtime, which, + prefix, "Audio"); + final SparseArray<? extends BatteryStats.Uid.Sensor> sensors = u.getSensorStats(); final int NSE = sensors.size(); for (int ise=0; ise<NSE; ise++) { @@ -3849,44 +3930,10 @@ public abstract class BatteryStats implements Parcelable { uidActivity = true; } - final Timer vibTimer = u.getVibratorOnTimer(); - if (vibTimer != null) { - // Convert from microseconds to milliseconds with rounding - final long totalTime = (vibTimer.getTotalTimeLocked( - rawRealtime, which) + 500) / 1000; - final int count = vibTimer.getCountLocked(which); - //timer.logState(); - if (totalTime != 0) { - sb.setLength(0); - sb.append(prefix); - sb.append(" Vibrator: "); - formatTimeMs(sb, totalTime); - sb.append("realtime ("); - sb.append(count); - sb.append(" times)"); - pw.println(sb.toString()); - uidActivity = true; - } - } - - final Timer fgTimer = u.getForegroundActivityTimer(); - if (fgTimer != null) { - // Convert from microseconds to milliseconds with rounding - final long totalTime = (fgTimer.getTotalTimeLocked(rawRealtime, which) + 500) - / 1000; - final int count = fgTimer.getCountLocked(which); - if (totalTime != 0) { - sb.setLength(0); - sb.append(prefix); - sb.append(" Foreground activities: "); - formatTimeMs(sb, totalTime); - sb.append("realtime ("); - sb.append(count); - sb.append(" times)"); - pw.println(sb.toString()); - uidActivity = true; - } - } + uidActivity |= printTimer(pw, sb, u.getVibratorOnTimer(), rawRealtime, which, prefix, + "Vibrator"); + uidActivity |= printTimer(pw, sb, u.getForegroundActivityTimer(), rawRealtime, which, + prefix, "Foreground activities"); long totalStateTime = 0; for (int ips=0; ips<Uid.NUM_PROCESS_STATE; ips++) { diff --git a/core/java/android/os/Build.java b/core/java/android/os/Build.java index dfd523a..50eed3e 100644 --- a/core/java/android/os/Build.java +++ b/core/java/android/os/Build.java @@ -685,8 +685,6 @@ public class Build { final String bootimage = SystemProperties.get("ro.bootimage.build.fingerprint"); final String requiredBootloader = SystemProperties.get("ro.build.expect.bootloader"); final String currentBootloader = SystemProperties.get("ro.bootloader"); - final String requiredRecovery = SystemProperties.get("ro.expect.recovery_id"); - final String currentRecovery = SystemProperties.get("ro.recovery_id"); final String requiredRadio = SystemProperties.get("ro.build.expect.baseband"); final String currentRadio = SystemProperties.get("gsm.version.baseband"); @@ -703,6 +701,7 @@ public class Build { } } + /* TODO: Figure out issue with checks failing if (!TextUtils.isEmpty(bootimage)) { if (!Objects.equals(system, bootimage)) { Slog.e(TAG, "Mismatched fingerprints; system reported " + system @@ -719,15 +718,6 @@ public class Build { } } - if (!TextUtils.isEmpty(requiredRecovery)) { - if (!Objects.equals(currentRecovery, requiredRecovery)) { - Slog.e(TAG, "Mismatched recovery version: build requires " + requiredRecovery - + " but runtime reports " + currentRecovery); - return false; - } - } - - /* TODO: uncomment when new bootloader lands b/20860620 if (!TextUtils.isEmpty(requiredRadio)) { if (!Objects.equals(currentRadio, requiredRadio)) { Slog.e(TAG, "Mismatched radio version: build requires " + requiredRadio diff --git a/core/java/android/os/IDeviceIdleController.aidl b/core/java/android/os/IDeviceIdleController.aidl index 602bfea..268295d 100644 --- a/core/java/android/os/IDeviceIdleController.aidl +++ b/core/java/android/os/IDeviceIdleController.aidl @@ -16,6 +16,8 @@ package android.os; +import android.os.UserHandle; + /** @hide */ interface IDeviceIdleController { void addPowerSaveWhitelistApp(String name); @@ -23,5 +25,7 @@ interface IDeviceIdleController { String[] getSystemPowerWhitelist(); String[] getFullPowerWhitelist(); int[] getAppIdWhitelist(); + int[] getAppIdTempWhitelist(); boolean isPowerSaveWhitelistApp(String name); + void addPowerSaveTempWhitelistApp(String name, long duration, int userId); } diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java index 1d9d7d2..8b18f32 100644 --- a/core/java/android/os/PowerManager.java +++ b/core/java/android/os/PowerManager.java @@ -928,6 +928,14 @@ public final class PowerManager { = "android.os.action.POWER_SAVE_WHITELIST_CHANGED"; /** + * @hide Intent that is broadcast when the set of temporarily whitelisted apps has changed. + * This broadcast is only sent to registered receivers. + */ + @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION) + public static final String ACTION_POWER_SAVE_TEMP_WHITELIST_CHANGED + = "android.os.action.POWER_SAVE_TEMP_WHITELIST_CHANGED"; + + /** * Intent that is broadcast when the state of {@link #isPowerSaveMode()} is about to change. * This broadcast is only sent to registered receivers. * diff --git a/core/java/android/os/PowerManagerInternal.java b/core/java/android/os/PowerManagerInternal.java index e523285..e742f98 100644 --- a/core/java/android/os/PowerManagerInternal.java +++ b/core/java/android/os/PowerManagerInternal.java @@ -137,6 +137,8 @@ public abstract class PowerManagerInternal { public abstract void setDeviceIdleWhitelist(int[] appids); + public abstract void setDeviceIdleTempWhitelist(int[] appids); + public abstract void updateUidProcState(int uid, int procState); public abstract void uidGone(int uid); diff --git a/core/java/android/os/UserManager.java b/core/java/android/os/UserManager.java index a81b83f..ef7e747 100644 --- a/core/java/android/os/UserManager.java +++ b/core/java/android/os/UserManager.java @@ -200,6 +200,20 @@ public class UserManager { public static final String DISALLOW_CONFIG_TETHERING = "no_config_tethering"; /** + * Specifies if a user is disallowed from resetting network settings + * from Settings. This can only be set by device owners and profile owners on the primary user. + * The default value is <code>false</code>. + * <p/>This restriction has no effect on secondary users and managed profiles since only the + * primary user can reset the network settings of the device. + * + * <p/>Key for user restrictions. + * <p/>Type: Boolean + * @see #setUserRestrictions(Bundle) + * @see #getUserRestrictions() + */ + public static final String DISALLOW_NETWORK_RESET = "no_network_reset"; + + /** * Specifies if a user is disallowed from factory resetting * from Settings. This can only be set by device owners and profile owners on the primary user. * The default value is <code>false</code>. diff --git a/core/java/android/provider/ContactsContract.java b/core/java/android/provider/ContactsContract.java index 76a5f967..df2e5f9 100644 --- a/core/java/android/provider/ContactsContract.java +++ b/core/java/android/provider/ContactsContract.java @@ -7930,8 +7930,6 @@ public final class ContactsContract { /** * API for inquiring about the general status of the provider. - * - * @hide */ public static final class ProviderStatus { @@ -7965,21 +7963,16 @@ public final class ContactsContract { public static final int STATUS_NORMAL = 0; /** - * The status used when the provider is in the process of upgrading. Contacts - * are temporarily unaccessible. - */ - public static final int STATUS_UPGRADING = 1; - - /** - * The status used during a locale change. + * The provider won't respond to queries. It is in the middle of a long running task, such + * as a database upgrade or locale change. */ - public static final int STATUS_CHANGING_LOCALE = 3; + public static final int STATUS_BUSY = 1; /** * The status that indicates that there are no accounts and no contacts * on the device. */ - public static final int STATUS_NO_ACCOUNTS_NO_CONTACTS = 4; + public static final int STATUS_EMPTY = 2; } /** diff --git a/core/java/android/provider/MediaStore.java b/core/java/android/provider/MediaStore.java index 7565654b..51dbdee 100644 --- a/core/java/android/provider/MediaStore.java +++ b/core/java/android/provider/MediaStore.java @@ -22,6 +22,7 @@ import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.Context; +import android.content.Intent; import android.database.Cursor; import android.database.DatabaseUtils; import android.database.sqlite.SQLiteException; @@ -33,6 +34,7 @@ import android.media.ThumbnailUtils; import android.net.Uri; import android.os.Environment; import android.os.ParcelFileDescriptor; +import android.service.media.CameraPrewarmService; import android.util.Log; import java.io.FileInputStream; @@ -226,33 +228,24 @@ public final class MediaStore { public static final String INTENT_ACTION_STILL_IMAGE_CAMERA = "android.media.action.STILL_IMAGE_CAMERA"; /** - * The name of the Intent action used to indicate that a camera launch might be imminent. This - * broadcast should be targeted to the package that is receiving - * {@link #INTENT_ACTION_STILL_IMAGE_CAMERA} or - * {@link #INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE}, depending on the context. If such - * intent would launch the resolver activity, this broadcast should not be sent at all. + * Name under which an activity handling {@link #INTENT_ACTION_STILL_IMAGE_CAMERA} or + * {@link #INTENT_ACTION_STILL_IMAGE_CAMERA_SECURE} publishes the service name for its prewarm + * service. * <p> - * A receiver of this broadcast should do the absolute minimum amount of work to initialize the - * camera in order to reduce startup time in likely case that shortly after an actual camera - * launch intent would be sent. + * This meta-data should reference the fully qualified class name of the prewarm service + * extending {@link CameraPrewarmService}. * <p> - * In case the actual intent will not be fired, the target package will receive - * {@link #ACTION_STILL_IMAGE_CAMERA_COOLDOWN}. However, it is recommended that the receiver - * also implements a timeout to close the camera after receiving this intent, as there is no - * guarantee that {@link #ACTION_STILL_IMAGE_CAMERA_COOLDOWN} will be delivered. - */ - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String ACTION_STILL_IMAGE_CAMERA_PREWARM = "android.media.action.STILL_IMAGE_CAMERA_PREWARM"; - - /** - * The name of the Intent action used to indicate that an imminent camera launch has been - * cancelled by the user. This broadcast should be targeted to the package that has received - * {@link #ACTION_STILL_IMAGE_CAMERA_PREWARM}. + * The prewarm service will get bound and receive a prewarm signal + * {@link CameraPrewarmService#onPrewarm()} when a camera launch intent fire might be imminent. + * An application implementing a prewarm service should do the absolute minimum amount of work + * to initialize the camera in order to reduce startup time in likely case that shortly after a + * camera launch intent would be sent. * <p> - * A receiver of this broadcast should close the camera immediately. + * If the camera launch intent gets fired shortly after, the service will be unbound + * asynchronously, without receiving */ - @SdkConstant(SdkConstantType.BROADCAST_INTENT_ACTION) - public static final String ACTION_STILL_IMAGE_CAMERA_COOLDOWN = "android.media.action.STILL_IMAGE_CAMERA_COOLDOWN"; + public static final String META_DATA_STILL_IMAGE_CAMERA_PREWARM_SERVICE = + "android.media.still_image_camera_preview_service"; /** * The name of the Intent action used to launch a camera in still image mode @@ -2268,5 +2261,4 @@ public final class MediaStore { } return null; } - } diff --git a/core/java/android/security/IKeystoreService.aidl b/core/java/android/security/IKeystoreService.aidl index 30ea8e7..2097d5a 100644 --- a/core/java/android/security/IKeystoreService.aidl +++ b/core/java/android/security/IKeystoreService.aidl @@ -65,7 +65,7 @@ interface IKeystoreService { ExportResult exportKey(String alias, int format, in KeymasterBlob clientId, in KeymasterBlob appId); OperationResult begin(IBinder appToken, String alias, int purpose, boolean pruneable, - in KeymasterArguments params, in byte[] entropy, out KeymasterArguments operationParams); + in KeymasterArguments params, in byte[] entropy); OperationResult update(IBinder token, in KeymasterArguments params, in byte[] input); OperationResult finish(IBinder token, in KeymasterArguments params, in byte[] signature); int abort(IBinder handle); diff --git a/core/java/android/security/keymaster/KeymasterDefs.java b/core/java/android/security/keymaster/KeymasterDefs.java index b354b6c..6e40c6c 100644 --- a/core/java/android/security/keymaster/KeymasterDefs.java +++ b/core/java/android/security/keymaster/KeymasterDefs.java @@ -50,8 +50,7 @@ public final class KeymasterDefs { public static final int KM_TAG_BLOCK_MODE = KM_ENUM_REP | 4; public static final int KM_TAG_DIGEST = KM_ENUM_REP | 5; public static final int KM_TAG_PADDING = KM_ENUM_REP | 6; - public static final int KM_TAG_RETURN_UNAUTHED = KM_BOOL | 7; - public static final int KM_TAG_CALLER_NONCE = KM_BOOL | 8; + public static final int KM_TAG_CALLER_NONCE = KM_BOOL | 7; public static final int KM_TAG_RESCOPING_ADD = KM_ENUM_REP | 101; public static final int KM_TAG_RESCOPING_DEL = KM_ENUM_REP | 102; @@ -82,7 +81,7 @@ public final class KeymasterDefs { public static final int KM_TAG_ASSOCIATED_DATA = KM_BYTES | 1000; public static final int KM_TAG_NONCE = KM_BYTES | 1001; - public static final int KM_TAG_CHUNK_LENGTH = KM_INT | 1002; + public static final int KM_TAG_AEAD_TAG = KM_BYTES | 1002; public static final int KM_TAG_AUTH_TOKEN = KM_BYTES | 1003; public static final int KM_TAG_MAC_LENGTH = KM_INT | 1004; @@ -192,7 +191,7 @@ public final class KeymasterDefs { public static final int KM_ERROR_UNSUPPORTED_EC_FIELD = -50; public static final int KM_ERROR_MISSING_NONCE = -51; public static final int KM_ERROR_INVALID_NONCE = -52; - public static final int KM_ERROR_UNSUPPORTED_CHUNK_LENGTH = -53; + public static final int KM_ERROR_MISSING_MAC_LENGTH = -53; public static final int KM_ERROR_RESCOPABLE_KEY_NOT_USABLE = -54; public static final int KM_ERROR_CALLER_NONCE_PROHIBITED = -55; public static final int KM_ERROR_UNIMPLEMENTED = -100; diff --git a/core/java/android/security/keymaster/OperationResult.java b/core/java/android/security/keymaster/OperationResult.java index 9b46ad3..911a05a 100644 --- a/core/java/android/security/keymaster/OperationResult.java +++ b/core/java/android/security/keymaster/OperationResult.java @@ -31,6 +31,7 @@ public class OperationResult implements Parcelable { public final long operationHandle; public final int inputConsumed; public final byte[] output; + public final KeymasterArguments outParams; public static final Parcelable.Creator<OperationResult> CREATOR = new Parcelable.Creator<OperationResult>() { @@ -49,6 +50,7 @@ public class OperationResult implements Parcelable { operationHandle = in.readLong(); inputConsumed = in.readInt(); output = in.createByteArray(); + outParams = KeymasterArguments.CREATOR.createFromParcel(in); } @Override @@ -63,5 +65,6 @@ public class OperationResult implements Parcelable { out.writeLong(operationHandle); out.writeInt(inputConsumed); out.writeByteArray(output); + outParams.writeToParcel(out, flags); } } diff --git a/core/java/android/service/media/CameraPrewarmService.java b/core/java/android/service/media/CameraPrewarmService.java new file mode 100644 index 0000000..335b00a --- /dev/null +++ b/core/java/android/service/media/CameraPrewarmService.java @@ -0,0 +1,96 @@ +/* + * Copyright (C) 2015 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.service.media; + +import android.app.Service; +import android.content.Intent; +import android.os.Handler; +import android.os.IBinder; +import android.os.Message; +import android.os.Messenger; + +/** + * Extend this class to implement a camera prewarm service. See + * {@link android.provider.MediaStore#META_DATA_STILL_IMAGE_CAMERA_PREWARM_SERVICE}. + */ +public abstract class CameraPrewarmService extends Service { + + /** + * Intent action to bind the service as a prewarm service. + * @hide + */ + public static final String ACTION_PREWARM = + "android.service.media.CameraPrewarmService.ACTION_PREWARM"; + + /** + * Message sent by the client indicating that the camera intent has been fired. + * @hide + */ + public static final int MSG_CAMERA_FIRED = 1; + + private final Handler mHandler = new Handler() { + + @Override + public void handleMessage(Message msg) { + switch (msg.what) { + case MSG_CAMERA_FIRED: + mCameraIntentFired = true; + break; + default: + super.handleMessage(msg); + } + } + }; + private boolean mCameraIntentFired; + + @Override + public IBinder onBind(Intent intent) { + if (ACTION_PREWARM.equals(intent.getAction())) { + onPrewarm(); + return new Messenger(mHandler).getBinder(); + } else { + return null; + } + } + + @Override + public boolean onUnbind(Intent intent) { + if (ACTION_PREWARM.equals(intent.getAction())) { + onCooldown(mCameraIntentFired); + } + return false; + } + + /** + * Called when the camera should be prewarmed. + */ + public abstract void onPrewarm(); + + /** + * Called when prewarm phase is done, either because the camera launch intent has been fired + * at this point or prewarm is no longer needed. A client should close the camera + * immediately in the latter case. + * <p> + * In case the camera launch intent has been fired, there is no guarantee about the ordering + * of these two events. Cooldown might happen either before or after the activity has been + * created that handles the camera intent. + * + * @param cameraIntentFired Indicates whether the intent to launch the camera has been + * fired. + */ + public abstract void onCooldown(boolean cameraIntentFired); +} diff --git a/core/java/android/service/voice/VoiceInteractionService.java b/core/java/android/service/voice/VoiceInteractionService.java index 77e2125..8119049 100644 --- a/core/java/android/service/voice/VoiceInteractionService.java +++ b/core/java/android/service/voice/VoiceInteractionService.java @@ -70,25 +70,6 @@ public class VoiceInteractionService extends Service { */ public static final String SERVICE_META_DATA = "android.voice_interaction"; - /** - * Flag for use with {@link #showSession}: request that the session be started with - * assist data from the currently focused activity. - */ - public static final int START_WITH_ASSIST = 1<<0; - - /** - * @hide - * Flag for use with {@link #showSession}: request that the session be started with - * a screen shot of the currently focused activity. - */ - public static final int START_WITH_SCREENSHOT = 1<<1; - - /** - * Flag for use with {@link #showSession}: indicate that the session has been started from the - * system assist gesture. - */ - public static final int START_SOURCE_ASSIST_GESTURE = 1<<2; - IVoiceInteractionService mInterface = new IVoiceInteractionService.Stub() { @Override public void ready() { mHandler.sendEmptyMessage(MSG_READY); @@ -176,6 +157,10 @@ public class VoiceInteractionService extends Service { * Request that the associated {@link android.service.voice.VoiceInteractionSession} be * shown to the user, starting it if necessary. * @param args Arbitrary arguments that will be propagated to the session. + * @param flags Indicates additional optional behavior that should be performed. May + * be {@link VoiceInteractionSession#SHOW_WITH_ASSIST VoiceInteractionSession.SHOW_WITH_ASSIST} + * to request that the system generate and deliver assist data on the current foreground + * app as part of showing the session UI. */ public void showSession(Bundle args, int flags) { if (mSystemService == null) { diff --git a/core/java/android/service/voice/VoiceInteractionSession.java b/core/java/android/service/voice/VoiceInteractionSession.java index f09b6a2..48ad5a8 100644 --- a/core/java/android/service/voice/VoiceInteractionSession.java +++ b/core/java/android/service/voice/VoiceInteractionSession.java @@ -68,11 +68,29 @@ import static android.view.ViewGroup.LayoutParams.MATCH_PARENT; * when done. It can also initiate voice interactions with applications by calling * {@link #startVoiceActivity}</p>. */ -public abstract class VoiceInteractionSession implements KeyEvent.Callback, - ComponentCallbacks2 { +public class VoiceInteractionSession implements KeyEvent.Callback, ComponentCallbacks2 { static final String TAG = "VoiceInteractionSession"; static final boolean DEBUG = true; + /** + * Flag received in {@link #onShow}: originator requested that the session be started with + * assist data from the currently focused activity. + */ + public static final int SHOW_WITH_ASSIST = 1<<0; + + /** + * @hide + * Flag received in {@link #onShow}: originator requested that the session be started with + * a screen shot of the currently focused activity. + */ + public static final int SHOW_WITH_SCREENSHOT = 1<<1; + + /** + * Flag for use with {@link #onShow}: indicates that the session has been started from the + * system assist gesture. + */ + public static final int SHOW_SOURCE_ASSIST_GESTURE = 1<<2; + final Context mContext; final HandlerCaller mHandlerCaller; @@ -105,10 +123,12 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, @Override public IVoiceInteractorRequest startConfirmation(String callingPackage, IVoiceInteractorCallback callback, CharSequence prompt, Bundle extras) { - Request request = newRequest(callback); - mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOO(MSG_START_CONFIRMATION, - new Caller(callingPackage, Binder.getCallingUid()), request, - prompt, extras)); + ConfirmationRequest request = new ConfirmationRequest(callingPackage, + Binder.getCallingUid(), callback, VoiceInteractionSession.this, + prompt, extras); + addRequest(request); + mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_CONFIRMATION, + request)); return request.mInterface; } @@ -116,47 +136,54 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, public IVoiceInteractorRequest startPickOption(String callingPackage, IVoiceInteractorCallback callback, CharSequence prompt, VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) { - Request request = newRequest(callback); - mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOOO(MSG_START_PICK_OPTION, - new Caller(callingPackage, Binder.getCallingUid()), request, - prompt, options, extras)); + PickOptionRequest request = new PickOptionRequest(callingPackage, + Binder.getCallingUid(), callback, VoiceInteractionSession.this, + prompt, options, extras); + addRequest(request); + mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_PICK_OPTION, + request)); return request.mInterface; } @Override public IVoiceInteractorRequest startCompleteVoice(String callingPackage, IVoiceInteractorCallback callback, CharSequence message, Bundle extras) { - Request request = newRequest(callback); - mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOO(MSG_START_COMPLETE_VOICE, - new Caller(callingPackage, Binder.getCallingUid()), request, - message, extras)); + CompleteVoiceRequest request = new CompleteVoiceRequest(callingPackage, + Binder.getCallingUid(), callback, VoiceInteractionSession.this, + message, extras); + addRequest(request); + mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMPLETE_VOICE, + request)); return request.mInterface; } @Override public IVoiceInteractorRequest startAbortVoice(String callingPackage, IVoiceInteractorCallback callback, CharSequence message, Bundle extras) { - Request request = newRequest(callback); - mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOO(MSG_START_ABORT_VOICE, - new Caller(callingPackage, Binder.getCallingUid()), request, - message, extras)); + AbortVoiceRequest request = new AbortVoiceRequest(callingPackage, + Binder.getCallingUid(), callback, VoiceInteractionSession.this, + message, extras); + addRequest(request); + mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_ABORT_VOICE, + request)); return request.mInterface; } @Override public IVoiceInteractorRequest startCommand(String callingPackage, IVoiceInteractorCallback callback, String command, Bundle extras) { - Request request = newRequest(callback); - mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageOOOO(MSG_START_COMMAND, - new Caller(callingPackage, Binder.getCallingUid()), request, - command, extras)); + CommandRequest request = new CommandRequest(callingPackage, + Binder.getCallingUid(), callback, VoiceInteractionSession.this, + command, extras); + mHandlerCaller.sendMessage(mHandlerCaller.obtainMessageO(MSG_START_COMMAND, + request)); return request.mInterface; } @Override public boolean[] supportsCommands(String callingPackage, String[] commands) { Message msg = mHandlerCaller.obtainMessageIOO(MSG_SUPPORTS_COMMANDS, - 0, new Caller(callingPackage, Binder.getCallingUid()), commands); + 0, commands, null); SomeArgs args = mHandlerCaller.sendMessageAndWait(msg); if (args != null) { boolean[] res = (boolean[])args.arg1; @@ -222,7 +249,16 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } }; - public static class Request { + /** @hide */ + public static class Caller { + } + + /** + * Base class representing a request from a voice-driver app to perform a particular + * voice operation with the user. See related subclasses for the types of requests + * that are possible. + */ + public static class Request extends Caller { final IVoiceInteractorRequest mInterface = new IVoiceInteractorRequest.Stub() { @Override public void cancel() throws RemoteException { @@ -233,12 +269,40 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } }; + final String mCallingPackage; + final int mCallingUid; final IVoiceInteractorCallback mCallback; final WeakReference<VoiceInteractionSession> mSession; + final Bundle mExtras; - Request(IVoiceInteractorCallback callback, VoiceInteractionSession session) { + Request(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, Bundle extras) { + mCallingPackage = packageName; + mCallingUid = uid; mCallback = callback; mSession = session.mWeakRef; + mExtras = extras; + } + + /** + * Return the uid of the application that initiated the request. + */ + public int getCallingUid() { + return mCallingUid; + } + + /** + * Return the package name of the application that initiated the request. + */ + public String getCallingPackage() { + return mCallingPackage; + } + + /** + * Return any additional extra information that was supplied as part of the request. + */ + public Bundle getExtras() { + return mExtras; } void finishRequest() { @@ -255,6 +319,7 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendConfirmResult(boolean confirmed, Bundle result) { try { if (DEBUG) Log.d(TAG, "sendConfirmResult: req=" + mInterface @@ -265,6 +330,7 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendPickOptionResult(boolean finished, VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { try { @@ -279,6 +345,7 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendCompleteVoiceResult(Bundle result) { try { if (DEBUG) Log.d(TAG, "sendCompleteVoiceResult: req=" + mInterface @@ -289,6 +356,7 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendAbortVoiceResult(Bundle result) { try { if (DEBUG) Log.d(TAG, "sendConfirmResult: req=" + mInterface @@ -299,6 +367,7 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendCommandResult(boolean finished, Bundle result) { try { if (DEBUG) Log.d(TAG, "sendCommandResult: req=" + mInterface @@ -311,7 +380,15 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** @hide */ public void sendCancelResult() { + cancel(); + } + + /** + * ASk the app to cancel this current request. + */ + public void cancel() { try { if (DEBUG) Log.d(TAG, "sendCancelResult: req=" + mInterface); finishRequest(); @@ -321,13 +398,200 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } - public static class Caller { - final String packageName; - final int uid; + /** + * A request for confirmation from the user of an operation, as per + * {@link android.app.VoiceInteractor.ConfirmationRequest + * VoiceInteractor.ConfirmationRequest}. + */ + public static final class ConfirmationRequest extends Request { + final CharSequence mPrompt; + + ConfirmationRequest(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, CharSequence prompt, Bundle extras) { + super(packageName, uid, callback, session, extras); + mPrompt = prompt; + } + + /** + * Return the prompt informing the user of what will happen, as per + * {@link android.app.VoiceInteractor.ConfirmationRequest + * VoiceInteractor.ConfirmationRequest}. + */ + public CharSequence getPrompt() { + return mPrompt; + } - Caller(String _packageName, int _uid) { - packageName = _packageName; - uid = _uid; + /** + * Report that the voice interactor has confirmed the operation with the user, resulting + * in a call to + * {@link android.app.VoiceInteractor.ConfirmationRequest#onConfirmationResult + * VoiceInteractor.ConfirmationRequest.onConfirmationResult}. + */ + public void sendConfirmationResult(boolean confirmed, Bundle result) { + sendConfirmResult(confirmed, result); + } + } + + /** + * A request for the user to pick from a set of option, as per + * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. + */ + public static final class PickOptionRequest extends Request { + final CharSequence mPrompt; + final VoiceInteractor.PickOptionRequest.Option[] mOptions; + + PickOptionRequest(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, CharSequence prompt, + VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) { + super(packageName, uid, callback, session, extras); + mPrompt = prompt; + mOptions = options; + } + + /** + * Return the prompt informing the user of what they are picking, as per + * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. + */ + public CharSequence getPrompt() { + return mPrompt; + } + + /** + * Return the set of options the user is picking from, as per + * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. + */ + public VoiceInteractor.PickOptionRequest.Option[] getOptions() { + return mOptions; + } + + /** + * Report an intermediate option selection from the request, without completing it (the + * request is still active and the app is waiting for the final option selection), + * resulting in a call to + * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult + * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished. + */ + public void sendIntermediatePickOptionResult( + VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { + sendPickOptionResult(false, selections, result); + } + + /** + * Report the final option selection for the request, completing the request + * and resulting in a call to + * {@link android.app.VoiceInteractor.PickOptionRequest#onPickOptionResult + * VoiceInteractor.PickOptionRequest.onPickOptionResult} with false for finished. + */ + public void sendPickOptionResult( + VoiceInteractor.PickOptionRequest.Option[] selections, Bundle result) { + sendPickOptionResult(true, selections, result); + } + } + + /** + * A request to simply inform the user that the voice operation has completed, as per + * {@link android.app.VoiceInteractor.CompleteVoiceRequest + * VoiceInteractor.CompleteVoiceRequest}. + */ + public static final class CompleteVoiceRequest extends Request { + final CharSequence mMessage; + + CompleteVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, CharSequence message, Bundle extras) { + super(packageName, uid, callback, session, extras); + mMessage = message; + } + + /** + * Return the message informing the user of the completion, as per + * {@link android.app.VoiceInteractor.CompleteVoiceRequest + * VoiceInteractor.CompleteVoiceRequest}. + */ + public CharSequence getMessage() { + return mMessage; + } + + /** + * Report that the voice interactor has finished completing the voice operation, resulting + * in a call to + * {@link android.app.VoiceInteractor.CompleteVoiceRequest#onCompleteResult + * VoiceInteractor.CompleteVoiceRequest.onCompleteResult}. + */ + public void sendCompleteResult(Bundle result) { + sendCompleteVoiceResult(result); + } + } + + /** + * A request to report that the current user interaction can not be completed with voice, as per + * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. + */ + public static final class AbortVoiceRequest extends Request { + final CharSequence mMessage; + + AbortVoiceRequest(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, CharSequence message, Bundle extras) { + super(packageName, uid, callback, session, extras); + mMessage = message; + } + + /** + * Return the message informing the user of the problem, as per + * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. + */ + public CharSequence getMessage() { + return mMessage; + } + + /** + * Report that the voice interactor has finished aborting the voice operation, resulting + * in a call to + * {@link android.app.VoiceInteractor.AbortVoiceRequest#onAbortResult + * VoiceInteractor.AbortVoiceRequest.onAbortResult}. + */ + public void sendAbortResult(Bundle result) { + sendAbortVoiceResult(result); + } + } + + /** + * A generic vendor-specific request, as per + * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. + */ + public static final class CommandRequest extends Request { + final String mCommand; + + CommandRequest(String packageName, int uid, IVoiceInteractorCallback callback, + VoiceInteractionSession session, String command, Bundle extras) { + super(packageName, uid, callback, session, extras); + mCommand = command; + } + + /** + * Return the command that is being executed, as per + * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. + */ + public String getCommand() { + return mCommand; + } + + /** + * Report an intermediate result of the request, without completing it (the request + * is still active and the app is waiting for the final result), resulting in a call to + * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult + * VoiceInteractor.CommandRequest.onCommandResult} with false for isCompleted. + */ + public void sendIntermediateResult(Bundle result) { + sendCommandResult(false, result); + } + + /** + * Report the final result of the request, completing the request and resulting in a call to + * {@link android.app.VoiceInteractor.CommandRequest#onCommandResult + * VoiceInteractor.CommandRequest.onCommandResult} with true for isCompleted. + */ + public void sendResult(Bundle result) { + sendCommandResult(true, result); } } @@ -354,50 +618,33 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, SomeArgs args; switch (msg.what) { case MSG_START_CONFIRMATION: - args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onConfirm: req=" + ((Request) args.arg2).mInterface - + " prompt=" + args.arg3 + " extras=" + args.arg4); - onConfirm((Caller)args.arg1, (Request)args.arg2, (CharSequence)args.arg3, - (Bundle)args.arg4); + if (DEBUG) Log.d(TAG, "onConfirm: req=" + msg.obj); + onRequestConfirmation((ConfirmationRequest) msg.obj); break; case MSG_START_PICK_OPTION: - args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onPickOption: req=" + ((Request) args.arg2).mInterface - + " prompt=" + args.arg3 + " options=" + args.arg4 - + " extras=" + args.arg5); - onPickOption((Caller)args.arg1, (Request)args.arg2, (CharSequence)args.arg3, - (VoiceInteractor.PickOptionRequest.Option[])args.arg4, - (Bundle)args.arg5); + if (DEBUG) Log.d(TAG, "onPickOption: req=" + msg.obj); + onRequestPickOption((PickOptionRequest) msg.obj); break; case MSG_START_COMPLETE_VOICE: - args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onCompleteVoice: req=" + ((Request) args.arg2).mInterface - + " message=" + args.arg3 + " extras=" + args.arg4); - onCompleteVoice((Caller) args.arg1, (Request) args.arg2, - (CharSequence) args.arg3, (Bundle) args.arg4); + if (DEBUG) Log.d(TAG, "onCompleteVoice: req=" + msg.obj); + onRequestCompleteVoice((CompleteVoiceRequest) msg.obj); break; case MSG_START_ABORT_VOICE: - args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onAbortVoice: req=" + ((Request) args.arg2).mInterface - + " message=" + args.arg3 + " extras=" + args.arg4); - onAbortVoice((Caller) args.arg1, (Request) args.arg2, (CharSequence) args.arg3, - (Bundle) args.arg4); + if (DEBUG) Log.d(TAG, "onAbortVoice: req=" + msg.obj); + onRequestAbortVoice((AbortVoiceRequest) msg.obj); break; case MSG_START_COMMAND: - args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onCommand: req=" + ((Request) args.arg2).mInterface - + " command=" + args.arg3 + " extras=" + args.arg4); - onCommand((Caller) args.arg1, (Request) args.arg2, (String) args.arg3, - (Bundle) args.arg4); + if (DEBUG) Log.d(TAG, "onCommand: req=" + msg.obj); + onRequestCommand((CommandRequest) msg.obj); break; case MSG_SUPPORTS_COMMANDS: args = (SomeArgs)msg.obj; - if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg2); - args.arg1 = onGetSupportedCommands((Caller) args.arg1, (String[]) args.arg2); + if (DEBUG) Log.d(TAG, "onGetSupportedCommands: cmds=" + args.arg1); + args.arg1 = onGetSupportedCommands((String[]) args.arg1); break; case MSG_CANCEL: if (DEBUG) Log.d(TAG, "onCancel: req=" + ((Request)msg.obj)); - onCancel((Request)msg.obj); + onCancelRequest((Request) msg.obj); break; case MSG_TASK_STARTED: if (DEBUG) Log.d(TAG, "onTaskStarted: intent=" + msg.obj @@ -526,12 +773,8 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, return mContext; } - Request newRequest(IVoiceInteractorCallback callback) { - synchronized (this) { - Request req = new Request(callback, this); - mActiveRequests.put(req.mInterface.asBinder(), req); - return req; - } + void addRequest(Request req) { + mActiveRequests.put(req.mInterface.asBinder(), req); } Request removeRequest(IBinder reqInterface) { @@ -630,7 +873,12 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, mContentFrame = (FrameLayout)mRootView.findViewById(android.R.id.content); } + /** @hide */ public void show() { + show(null, 0); + } + + public void show(Bundle args, int showFlags) { try { mSystemService.showSessionFromSession(mToken, null, 0); } catch (RemoteException e) { @@ -644,11 +892,11 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } - /** TODO: remove */ + /** @hide */ public void showWindow() { } - /** TODO: remove */ + /** @hide */ public void hideWindow() { } @@ -677,7 +925,9 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, * <p>As the voice activity runs, it can retrieve a {@link android.app.VoiceInteractor} * through which it can perform voice interactions through your session. These requests * for voice interactions will appear as callbacks on {@link #onGetSupportedCommands}, - * {@link #onConfirm}, {@link #onCommand}, and {@link #onCancel}. + * {@link #onRequestConfirmation}, {@link #onRequestPickOption}, + * {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice}, + * or {@link #onRequestCommand} * * <p>You will receive a call to {@link #onTaskStarted} when the task starts up * and {@link #onTaskFinished} when the last activity has finished. @@ -748,8 +998,25 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } } + /** + * Initiatize a new session. At this point you don't know exactly what this + * session will be used for; you will find that out in {@link #onShow}. + */ + public void onCreate() { + doOnCreate(); + } + /** @hide */ public void onCreate(Bundle args) { + doOnCreate(); + } + + /** @hide */ + public void onCreate(Bundle args, int showFlags) { + doOnCreate(); + } + + private void doOnCreate() { mTheme = mTheme != 0 ? mTheme : com.android.internal.R.style.Theme_DeviceDefault_VoiceInteractionSession; mInflater = (LayoutInflater)mContext.getSystemService( @@ -766,15 +1033,6 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, } /** - * Initiatize a new session. The given args and showFlags are the initial values - * passed to {@link VoiceInteractionService#showSession VoiceInteractionService.showSession}, - * if possible. Normally you should handle these in {@link #onShow}. - */ - public void onCreate(Bundle args, int showFlags) { - onCreate(args); - } - - /** * Called when the session UI is going to be shown. This is called after * {@link #onCreateContentView} (if the session's content UI needed to be created) and * immediately prior to the window being shown. This may be called while the window @@ -928,18 +1186,45 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, hide(); } + /** @hide */ + public boolean[] onGetSupportedCommands(Caller caller, String[] commands) { + return new boolean[commands.length]; + } + /** @hide */ + public void onConfirm(Caller caller, Request request, CharSequence prompt, + Bundle extras) { + } + /** @hide */ + public void onPickOption(Caller caller, Request request, CharSequence prompt, + VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras) { + } + /** @hide */ + public void onCompleteVoice(Caller caller, Request request, CharSequence message, + Bundle extras) { + request.sendCompleteVoiceResult(null); + } + /** @hide */ + public void onAbortVoice(Caller caller, Request request, CharSequence message, Bundle extras) { + request.sendAbortVoiceResult(null); + } + /** @hide */ + public void onCommand(Caller caller, Request request, String command, Bundle extras) { + } + /** @hide */ + public void onCancel(Request request) { + } + /** * Request to query for what extended commands the session supports. * - * @param caller Who is making the request. * @param commands An array of commands that are being queried. * @return Return an array of booleans indicating which of each entry in the * command array is supported. A true entry in the array indicates the command * is supported; false indicates it is not. The default implementation returns * an array of all false entries. */ - public boolean[] onGetSupportedCommands(Caller caller, String[] commands) { - return new boolean[commands.length]; + public boolean[] onGetSupportedCommands(String[] commands) { + return onGetSupportedCommands(new Caller(), commands); } /** @@ -947,31 +1232,22 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, * corresponding to a {@link android.app.VoiceInteractor.ConfirmationRequest * VoiceInteractor.ConfirmationRequest}. * - * @param caller Who is making the request. * @param request The active request. - * @param prompt The prompt informing the user of what will happen, as per - * {@link android.app.VoiceInteractor.ConfirmationRequest VoiceInteractor.ConfirmationRequest}. - * @param extras Any additional information, as per - * {@link android.app.VoiceInteractor.ConfirmationRequest VoiceInteractor.ConfirmationRequest}. */ - public abstract void onConfirm(Caller caller, Request request, CharSequence prompt, - Bundle extras); + public void onRequestConfirmation(ConfirmationRequest request) { + onConfirm(request, request, request.getPrompt(), request.getExtras()); + } /** * Request for the user to pick one of N options, corresponding to a * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. * - * @param caller Who is making the request. * @param request The active request. - * @param prompt The prompt informing the user of what they are picking, as per - * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. - * @param options The set of options the user is picking from, as per - * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. - * @param extras Any additional information, as per - * {@link android.app.VoiceInteractor.PickOptionRequest VoiceInteractor.PickOptionRequest}. */ - public abstract void onPickOption(Caller caller, Request request, CharSequence prompt, - VoiceInteractor.PickOptionRequest.Option[] options, Bundle extras); + public void onRequestPickOption(PickOptionRequest request) { + onPickOption(request, request, request.getPrompt(), request.getOptions(), + request.getExtras()); + } /** * Request to complete the voice interaction session because the voice activity successfully @@ -980,18 +1256,10 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, * VoiceInteractor.CompleteVoiceRequest}. The default implementation just sends an empty * confirmation back to allow the activity to exit. * - * @param caller Who is making the request. * @param request The active request. - * @param message The message informing the user of the problem, as per - * {@link android.app.VoiceInteractor.CompleteVoiceRequest - * VoiceInteractor.CompleteVoiceRequest}. - * @param extras Any additional information, as per - * {@link android.app.VoiceInteractor.CompleteVoiceRequest - * VoiceInteractor.CompleteVoiceRequest}. */ - public void onCompleteVoice(Caller caller, Request request, CharSequence message, - Bundle extras) { - request.sendCompleteVoiceResult(null); + public void onRequestCompleteVoice(CompleteVoiceRequest request) { + onCompleteVoice(request, request, request.getMessage(), request.getExtras()); } /** @@ -1001,15 +1269,10 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, * VoiceInteractor.AbortVoiceRequest}. The default implementation just sends an empty * confirmation back to allow the activity to exit. * - * @param caller Who is making the request. * @param request The active request. - * @param message The message informing the user of the problem, as per - * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. - * @param extras Any additional information, as per - * {@link android.app.VoiceInteractor.AbortVoiceRequest VoiceInteractor.AbortVoiceRequest}. */ - public void onAbortVoice(Caller caller, Request request, CharSequence message, Bundle extras) { - request.sendAbortVoiceResult(null); + public void onRequestAbortVoice(AbortVoiceRequest request) { + onAbortVoice(request, request, request.getMessage(), request.getExtras()); } /** @@ -1017,20 +1280,21 @@ public abstract class VoiceInteractionSession implements KeyEvent.Callback, * corresponding to a {@link android.app.VoiceInteractor.CommandRequest * VoiceInteractor.CommandRequest}. * - * @param caller Who is making the request. * @param request The active request. - * @param command The command that is being executed, as per - * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. - * @param extras Any additional information, as per - * {@link android.app.VoiceInteractor.CommandRequest VoiceInteractor.CommandRequest}. */ - public abstract void onCommand(Caller caller, Request request, String command, Bundle extras); + public void onRequestCommand(CommandRequest request) { + onCommand(request, request, request.getCommand(), request.getExtras()); + } /** * Called when the {@link android.app.VoiceInteractor} has asked to cancel a {@link Request} - * that was previously delivered to {@link #onConfirm} or {@link #onCommand}. + * that was previously delivered to {@link #onRequestConfirmation}, + * {@link #onRequestPickOption}, {@link #onRequestCompleteVoice}, {@link #onRequestAbortVoice}, + * or {@link #onRequestCommand}. * * @param request The request that is being canceled. */ - public abstract void onCancel(Request request); + public void onCancelRequest(Request request) { + onCancel(request); + } } diff --git a/core/java/android/text/Hyphenator.java b/core/java/android/text/Hyphenator.java index a99bdf5..67c36e3 100644 --- a/core/java/android/text/Hyphenator.java +++ b/core/java/android/text/Hyphenator.java @@ -16,6 +16,9 @@ package android.text; +import com.android.internal.annotations.GuardedBy; + +import android.annotation.Nullable; import android.util.Log; import java.io.File; @@ -36,6 +39,9 @@ public class Hyphenator { private static String TAG = "Hyphenator"; + private final static Object sLock = new Object(); + + @GuardedBy("sLock") static HashMap<Locale, Hyphenator> sMap = new HashMap<Locale, Hyphenator>(); private long mNativePtr; @@ -44,35 +50,94 @@ public class Hyphenator { mNativePtr = nativePtr; } - public static long get(Locale locale) { - Hyphenator result = sMap.get(locale); - return result == null ? 0 : result.mNativePtr; - } + public static long get(@Nullable Locale locale) { + synchronized (sLock) { + if (sMap.containsKey(locale)) { + Hyphenator result = sMap.get(locale); + return (result == null) ? 0 : result.mNativePtr; + } + + // TODO: Convert this a proper locale-fallback system - private static Hyphenator loadHyphenator(Locale locale) { - // TODO: find pattern dictionary (from system location) that best matches locale - if (Locale.US.equals(locale)) { - File f = new File(getSystemHyphenatorLocation(), "hyph-en-us.pat.txt"); - try { - RandomAccessFile rf = new RandomAccessFile(f, "r"); - byte[] buf = new byte[(int)rf.length()]; - rf.read(buf); - rf.close(); - String patternData = new String(buf); - long nativePtr = StaticLayout.nLoadHyphenator(patternData); - return new Hyphenator(nativePtr); - } catch (IOException e) { - Log.e(TAG, "error loading hyphenation " + f, e); + // Fall back to language-only, if available + Locale languageOnlyLocale = new Locale(locale.getLanguage()); + if (sMap.containsKey(languageOnlyLocale)) { + Hyphenator result = sMap.get(languageOnlyLocale); + sMap.put(locale, result); + return (result == null) ? 0 : result.mNativePtr; } + + // Fall back to script-only, if available + String script = locale.getScript(); + if (!script.equals("")) { + Locale scriptOnlyLocale = new Locale.Builder() + .setLanguage("und") + .setScript(script) + .build(); + if (sMap.containsKey(scriptOnlyLocale)) { + Hyphenator result = sMap.get(scriptOnlyLocale); + sMap.put(locale, result); + return (result == null) ? 0 : result.mNativePtr; + } + } + + sMap.put(locale, null); // To remember we found nothing. + } + return 0; + } + + private static Hyphenator loadHyphenator(String languageTag) { + String patternFilename = "hyph-"+languageTag.toLowerCase(Locale.US)+".pat.txt"; + File patternFile = new File(getSystemHyphenatorLocation(), patternFilename); + try { + RandomAccessFile rf = new RandomAccessFile(patternFile, "r"); + byte[] buf = new byte[(int)rf.length()]; + rf.read(buf); + rf.close(); + String patternData = new String(buf); + long nativePtr = StaticLayout.nLoadHyphenator(patternData); + return new Hyphenator(nativePtr); + } catch (IOException e) { + Log.e(TAG, "error loading hyphenation " + patternFile, e); } return null; } private static File getSystemHyphenatorLocation() { - // TODO: move to a sensible location under system return new File("/system/usr/hyphen-data"); } + // This array holds pairs of language tags that are used to prefill the map from locale to + // hyphenation data: The hyphenation data for the first field will be prefilled from the + // hyphenation data for the second field. + // + // The aliases that are computable by the get() method above are not included. + private static final String[][] LOCALE_FALLBACK_DATA = { + // English locales that fall back to en-US. The data is + // from CLDR. It's all English locales, minus the locales whose + // parent is en-001 (from supplementalData.xml, under <parentLocales>). + // TODO: Figure out how to get this from ICU. + {"en-AS", "en-US"}, // English (American Samoa) + {"en-GU", "en-US"}, // English (Guam) + {"en-MH", "en-US"}, // English (Marshall Islands) + {"en-MP", "en-US"}, // English (Northern Mariana Islands) + {"en-PR", "en-US"}, // English (Puerto Rico) + {"en-UM", "en-US"}, // English (United States Minor Outlying Islands) + {"en-VI", "en-US"}, // English (Virgin Islands) + + // Norwegian is very probably Norwegian Bokmål. + {"no", "nb"}, + + // Fall back to Ethiopic script for languages likely to be written in Ethiopic. + // Data is from CLDR's likelySubtags.xml. + // TODO: Convert this to a mechanism using ICU4J's ULocale#addLikelySubtags(). + {"am", "und-Ethi"}, // Amharic + {"byn", "und-Ethi"}, // Blin + {"gez", "und-Ethi"}, // Geʻez + {"ti", "und-Ethi"}, // Tigrinya + {"wal", "und-Ethi"}, // Wolaytta + }; + /** * Load hyphenation patterns at initialization time. We want to have patterns * for all locales loaded and ready to use so we don't have to do any file IO @@ -81,7 +146,22 @@ public class Hyphenator { * @hide */ public static void init() { - Locale l = Locale.US; - sMap.put(l, loadHyphenator(l)); + sMap.put(null, null); + + // TODO: replace this with a discovery-based method that looks into /system/usr/hyphen-data + String[] availableLanguages = {"en-US", "eu", "hu", "hy", "nb", "nn", "sa", "und-Ethi"}; + for (int i = 0; i < availableLanguages.length; i++) { + String languageTag = availableLanguages[i]; + Hyphenator h = loadHyphenator(languageTag); + if (h != null) { + sMap.put(Locale.forLanguageTag(languageTag), h); + } + } + + for (int i = 0; i < LOCALE_FALLBACK_DATA.length; i++) { + String language = LOCALE_FALLBACK_DATA[i][0]; + String fallback = LOCALE_FALLBACK_DATA[i][1]; + sMap.put(Locale.forLanguageTag(language), sMap.get(Locale.forLanguageTag(fallback))); + } } } diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java index 3e621b1..37c8100 100644 --- a/core/java/android/view/View.java +++ b/core/java/android/view/View.java @@ -1661,8 +1661,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback, /** {@hide} */ static final int PFLAG_SKIP_DRAW = 0x00000080; /** {@hide} */ - static final int PFLAG_ONLY_DRAWS_BACKGROUND = 0x00000100; - /** {@hide} */ static final int PFLAG_REQUEST_TRANSPARENT_REGIONS = 0x00000200; /** {@hide} */ static final int PFLAG_DRAWABLE_STATE_DIRTY = 0x00000400; @@ -4510,7 +4508,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, } attributes[i] = resourceName; - attributes[i + 1] = t.getString(index, false); + attributes[i + 1] = t.getString(index); i += 2; } @@ -6351,7 +6349,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, } View next = rootView.findViewInsideOutShouldExist(this, mAccessibilityTraversalBeforeId); - if (next != null) { + if (next != null && next.includeForAccessibility()) { info.setTraversalBefore(next); } } @@ -6363,7 +6361,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback, } View next = rootView.findViewInsideOutShouldExist(this, mAccessibilityTraversalAfterId); - if (next != null) { + if (next != null && next.includeForAccessibility()) { info.setTraversalAfter(next); } } @@ -10619,9 +10617,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback, if ((changed & DRAW_MASK) != 0) { if ((mViewFlags & WILL_NOT_DRAW) != 0) { - if (mBackground != null) { + if (mBackground != null + || (mForegroundInfo != null && mForegroundInfo.mDrawable != null)) { mPrivateFlags &= ~PFLAG_SKIP_DRAW; - mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; } else { mPrivateFlags |= PFLAG_SKIP_DRAW; } @@ -17260,20 +17258,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback, if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { mPrivateFlags &= ~PFLAG_SKIP_DRAW; - mPrivateFlags |= PFLAG_ONLY_DRAWS_BACKGROUND; requestLayout = true; } } else { /* Remove the background */ mBackground = null; - - if ((mPrivateFlags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0) { - /* - * This view ONLY drew the background before and we're removing - * the background, so now it won't draw anything - * (hence we SKIP_DRAW) - */ - mPrivateFlags &= ~PFLAG_ONLY_DRAWS_BACKGROUND; + if ((mViewFlags & WILL_NOT_DRAW) != 0 + && (mForegroundInfo == null || mForegroundInfo.mDrawable == null)) { mPrivateFlags |= PFLAG_SKIP_DRAW; } @@ -17447,13 +17438,17 @@ public class View implements Drawable.Callback, KeyEvent.Callback, mForegroundInfo.mDrawable = foreground; mForegroundInfo.mBoundsChanged = true; if (foreground != null) { - setWillNotDraw(false); + if ((mPrivateFlags & PFLAG_SKIP_DRAW) != 0) { + mPrivateFlags &= ~PFLAG_SKIP_DRAW; + } foreground.setCallback(this); foreground.setLayoutDirection(getLayoutDirection()); if (foreground.isStateful()) { foreground.setState(getDrawableState()); } applyForegroundTint(); + } else if ((mViewFlags & WILL_NOT_DRAW) != 0 && mBackground == null) { + mPrivateFlags |= PFLAG_SKIP_DRAW; } requestLayout(); invalidate(); @@ -19181,16 +19176,17 @@ public class View implements Drawable.Callback, KeyEvent.Callback, getLocationInWindow(location); region.op(location[0], location[1], location[0] + mRight - mLeft, location[1] + mBottom - mTop, Region.Op.DIFFERENCE); - } else if ((pflags & PFLAG_ONLY_DRAWS_BACKGROUND) != 0 && mBackground != null && - mBackground.getOpacity() != PixelFormat.TRANSPARENT) { - // The ONLY_DRAWS_BACKGROUND flag IS set and the background drawable - // exists, so we remove the background drawable's non-transparent - // parts from this transparent region. - applyDrawableToTransparentRegion(mBackground, region); - } - final Drawable foreground = mForegroundInfo != null ? mForegroundInfo.mDrawable : null; - if (foreground != null) { - applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); + } else { + if (mBackground != null && mBackground.getOpacity() != PixelFormat.TRANSPARENT) { + // The SKIP_DRAW flag IS set and the background drawable exists, we remove + // the background drawable's non-transparent parts from this transparent region. + applyDrawableToTransparentRegion(mBackground, region); + } + if (mForegroundInfo != null && mForegroundInfo.mDrawable != null + && mForegroundInfo.mDrawable.getOpacity() != PixelFormat.TRANSPARENT) { + // Similarly, we remove the foreground drawable's non-transparent parts. + applyDrawableToTransparentRegion(mForegroundInfo.mDrawable, region); + } } } return true; diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java index aa9fd9b..e015c04 100644 --- a/core/java/android/view/ViewGroup.java +++ b/core/java/android/view/ViewGroup.java @@ -793,7 +793,8 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager @Override public ActionMode startActionModeForChild( View originalView, ActionMode.Callback callback, int type) { - if ((mGroupFlags & FLAG_START_ACTION_MODE_FOR_CHILD_IS_NOT_TYPED) == 0) { + if ((mGroupFlags & FLAG_START_ACTION_MODE_FOR_CHILD_IS_NOT_TYPED) == 0 + && type == ActionMode.TYPE_PRIMARY) { ActionMode mode; try { mGroupFlags |= FLAG_START_ACTION_MODE_FOR_CHILD_IS_TYPED; @@ -1913,6 +1914,9 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager @Override public void addChildrenForAccessibility(ArrayList<View> childrenForAccessibility) { + if (getAccessibilityNodeProvider() != null) { + return; + } ChildListForAccessibility children = ChildListForAccessibility.obtain(this, true); try { final int childrenCount = children.getChildCount(); diff --git a/core/java/android/view/WindowManager.java b/core/java/android/view/WindowManager.java index f0c86e5..45bc1df 100644 --- a/core/java/android/view/WindowManager.java +++ b/core/java/android/view/WindowManager.java @@ -309,6 +309,7 @@ public interface WindowManager extends ViewManager { * Window type: a above sub-panel on top of an application window and it's * sub-panel windows. These windows are displayed on top of their attached window * and any {@link #TYPE_APPLICATION_SUB_PANEL} panels. + * @hide */ public static final int TYPE_APPLICATION_ABOVE_SUB_PANEL = FIRST_SUB_WINDOW + 5; diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java index 901a32d..b454d1c 100644 --- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java +++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java @@ -2737,10 +2737,10 @@ public class AccessibilityNodeInfo implements Parcelable { if (mCollectionItemInfo != null) { parcel.writeInt(1); - parcel.writeInt(mCollectionItemInfo.getColumnIndex()); - parcel.writeInt(mCollectionItemInfo.getColumnSpan()); parcel.writeInt(mCollectionItemInfo.getRowIndex()); parcel.writeInt(mCollectionItemInfo.getRowSpan()); + parcel.writeInt(mCollectionItemInfo.getColumnIndex()); + parcel.writeInt(mCollectionItemInfo.getColumnSpan()); parcel.writeInt(mCollectionItemInfo.isHeading() ? 1 : 0); parcel.writeInt(mCollectionItemInfo.isSelected() ? 1 : 0); } else { diff --git a/core/java/android/view/inputmethod/InputMethodManager.java b/core/java/android/view/inputmethod/InputMethodManager.java index 5537b3e..053b35c 100644 --- a/core/java/android/view/inputmethod/InputMethodManager.java +++ b/core/java/android/view/inputmethod/InputMethodManager.java @@ -24,6 +24,7 @@ import com.android.internal.view.IInputMethodManager; import com.android.internal.view.IInputMethodSession; import com.android.internal.view.InputBindResult; +import android.annotation.RequiresPermission; import android.content.Context; import android.graphics.Matrix; import android.graphics.Rect; @@ -60,6 +61,8 @@ import java.util.Objects; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; +import static android.Manifest.permission.WRITE_SECURE_SETTINGS; + /** * Central system API to the overall input method framework (IMF) architecture, * which arbitrates interaction between applications and the current input method. @@ -1976,6 +1979,7 @@ public final class InputMethodManager { * @return true if the current subtype was successfully switched. When the specified subtype is * null, this method returns false. */ + @RequiresPermission(WRITE_SECURE_SETTINGS) public boolean setCurrentInputMethodSubtype(InputMethodSubtype subtype) { synchronized (mH) { try { diff --git a/core/java/android/view/textservice/SpellCheckerSession.java b/core/java/android/view/textservice/SpellCheckerSession.java index 84f395a..195a335 100644 --- a/core/java/android/view/textservice/SpellCheckerSession.java +++ b/core/java/android/view/textservice/SpellCheckerSession.java @@ -98,11 +98,11 @@ public class SpellCheckerSession { private final InternalListener mInternalListener; private final ITextServicesManager mTextServicesManager; private final SpellCheckerInfo mSpellCheckerInfo; + private final SpellCheckerSessionListener mSpellCheckerSessionListener; private final SpellCheckerSessionListenerImpl mSpellCheckerSessionListenerImpl; private final SpellCheckerSubtype mSubtype; private boolean mIsUsed; - private SpellCheckerSessionListener mSpellCheckerSessionListener; /** Handler that will execute the main tasks */ private final Handler mHandler = new Handler() { diff --git a/core/java/android/webkit/ViewAssistStructure.java b/core/java/android/webkit/ViewAssistStructure.java deleted file mode 100644 index afa5ab8..0000000 --- a/core/java/android/webkit/ViewAssistStructure.java +++ /dev/null @@ -1,203 +0,0 @@ -/* - * Copyright (C) 2015 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.webkit; - -import android.graphics.Rect; -import android.os.Bundle; -import android.text.TextPaint; -import android.view.ViewStructure; - - -/** - * TODO This class is temporary. It will be deleted once we update Webview APK to use the - * new ViewStructure method. - * @hide - */ -public class ViewAssistStructure extends android.view.ViewAssistStructure { - - private ViewStructure mV; - - public ViewAssistStructure(ViewStructure v) { - mV = v; - } - - @Override - public void setId(int id, String packageName, String typeName, String entryName) { - mV.setId(id, packageName, typeName, entryName); - } - - @Override - public void setDimens(int left, int top, int scrollX, int scrollY, int width, - int height) { - mV.setDimens(left, top, scrollX, scrollY, width, height); - } - - @Override - public void setVisibility(int visibility) { - mV.setVisibility(visibility); - } - - @Override - public void setAssistBlocked(boolean state) { - mV.setAssistBlocked(state); - } - - @Override - public void setEnabled(boolean state) { - mV.setEnabled(state); - } - - @Override - public void setClickable(boolean state) { - mV.setClickable(state); - } - - @Override - public void setLongClickable(boolean state) { - mV.setLongClickable(state); - } - - @Override - public void setStylusButtonPressable(boolean state) { - mV.setStylusButtonPressable(state); - } - - @Override - public void setFocusable(boolean state) { - mV.setFocusable(state); - } - - @Override - public void setFocused(boolean state) { - mV.setFocused(state); - } - - @Override - public void setAccessibilityFocused(boolean state) { - mV.setAccessibilityFocused(state); - } - - @Override - public void setCheckable(boolean state) { - mV.setCheckable(state); - } - - @Override - public void setChecked(boolean state) { - mV.setChecked(state); - } - - @Override - public void setSelected(boolean state) { - mV.setSelected(state); - } - - @Override - public void setActivated(boolean state) { - mV.setActivated(state); - } - - @Override - public void setClassName(String className) { - mV.setClassName(className); - } - - @Override - public void setContentDescription(CharSequence contentDescription) { - mV.setContentDescription(contentDescription); - } - - @Override - public void setText(CharSequence text) { - mV.setText(text); - } - - @Override - public void setText(CharSequence text, int selectionStart, int selectionEnd) { - mV.setText(text, selectionStart, selectionEnd); - } - - @Override - public void setTextStyle(float size, int fgColor, int bgColor, int style) { - mV.setTextStyle(size, fgColor, bgColor, style); - } - - @Override - public void setHint(CharSequence hint) { - mV.setHint(hint); - } - - @Override - public CharSequence getText() { - return mV.getText(); - } - - @Override - public int getTextSelectionStart() { - return mV.getTextSelectionStart(); - } - - @Override - public int getTextSelectionEnd() { - return mV.getTextSelectionEnd(); - } - - @Override - public CharSequence getHint() { - return mV.getHint(); - } - - @Override - public Bundle getExtras() { - return mV.getExtras(); - } - - @Override - public boolean hasExtras() { - return mV.hasExtras(); - } - - @Override - public void setChildCount(int num) { - mV.setChildCount(num); - } - - @Override - public int getChildCount() { - return mV.getChildCount(); - } - - @Override - public android.view.ViewAssistStructure newChild(int index) { - return mV.newChild(index); - } - - @Override - public android.view.ViewAssistStructure asyncNewChild(int index) { - return mV.asyncNewChild(index); - } - - @Override - public void asyncCommit() { - mV.asyncCommit(); - } - - @Override - public Rect getTempRect() { - return mV.getTempRect(); - } -} diff --git a/core/java/android/webkit/WebView.java b/core/java/android/webkit/WebView.java index ccb98b4..5080fcc 100644 --- a/core/java/android/webkit/WebView.java +++ b/core/java/android/webkit/WebView.java @@ -2436,8 +2436,7 @@ public class WebView extends AbsoluteLayout @Override public void onProvideVirtualStructure(ViewStructure structure) { - ViewAssistStructure s = new ViewAssistStructure(structure); - mProvider.getViewDelegate().onProvideVirtualAssistStructure(s); + mProvider.getViewDelegate().onProvideVirtualStructure(structure); } /** @hide */ diff --git a/core/java/android/webkit/WebViewProvider.java b/core/java/android/webkit/WebViewProvider.java index 00aba2a..09afcf1 100644 --- a/core/java/android/webkit/WebViewProvider.java +++ b/core/java/android/webkit/WebViewProvider.java @@ -298,7 +298,7 @@ public interface WebViewProvider { interface ViewDelegate { public boolean shouldDelayChildPressedState(); - public void onProvideVirtualAssistStructure(android.view.ViewAssistStructure structure); + public void onProvideVirtualStructure(android.view.ViewStructure structure); public AccessibilityNodeProvider getAccessibilityNodeProvider(); diff --git a/core/java/android/widget/AbsListView.java b/core/java/android/widget/AbsListView.java index e963f53..a3332fa 100644 --- a/core/java/android/widget/AbsListView.java +++ b/core/java/android/widget/AbsListView.java @@ -820,44 +820,36 @@ public abstract class AbsListView extends AdapterView<ListAdapter> implements Te mOwnerThread = Thread.currentThread(); final TypedArray a = context.obtainStyledAttributes( - attrs, com.android.internal.R.styleable.AbsListView, defStyleAttr, defStyleRes); + attrs, R.styleable.AbsListView, defStyleAttr, defStyleRes); - Drawable d = a.getDrawable(com.android.internal.R.styleable.AbsListView_listSelector); - if (d != null) { - setSelector(d); - } - - mDrawSelectorOnTop = a.getBoolean( - com.android.internal.R.styleable.AbsListView_drawSelectorOnTop, false); - - boolean stackFromBottom = a.getBoolean(R.styleable.AbsListView_stackFromBottom, false); - setStackFromBottom(stackFromBottom); - - boolean scrollingCacheEnabled = a.getBoolean(R.styleable.AbsListView_scrollingCache, true); - setScrollingCacheEnabled(scrollingCacheEnabled); - - boolean useTextFilter = a.getBoolean(R.styleable.AbsListView_textFilterEnabled, false); - setTextFilterEnabled(useTextFilter); - - int transcriptMode = a.getInt(R.styleable.AbsListView_transcriptMode, - TRANSCRIPT_MODE_DISABLED); - setTranscriptMode(transcriptMode); - - int color = a.getColor(R.styleable.AbsListView_cacheColorHint, 0); - setCacheColorHint(color); - - boolean enableFastScroll = a.getBoolean(R.styleable.AbsListView_fastScrollEnabled, false); - setFastScrollEnabled(enableFastScroll); - - int fastScrollStyle = a.getResourceId(R.styleable.AbsListView_fastScrollStyle, 0); - setFastScrollStyle(fastScrollStyle); - - boolean smoothScrollbar = a.getBoolean(R.styleable.AbsListView_smoothScrollbar, true); - setSmoothScrollbarEnabled(smoothScrollbar); - - setChoiceMode(a.getInt(R.styleable.AbsListView_choiceMode, CHOICE_MODE_NONE)); - setFastScrollAlwaysVisible( - a.getBoolean(R.styleable.AbsListView_fastScrollAlwaysVisible, false)); + final Drawable selector = a.getDrawable(R.styleable.AbsListView_listSelector); + if (selector != null) { + setSelector(selector); + } + + mDrawSelectorOnTop = a.getBoolean(R.styleable.AbsListView_drawSelectorOnTop, false); + + setStackFromBottom(a.getBoolean( + R.styleable.AbsListView_stackFromBottom, false)); + setScrollingCacheEnabled(a.getBoolean( + R.styleable.AbsListView_scrollingCache, true)); + setTextFilterEnabled(a.getBoolean( + R.styleable.AbsListView_textFilterEnabled, false)); + setTranscriptMode(a.getInt( + R.styleable.AbsListView_transcriptMode, TRANSCRIPT_MODE_DISABLED)); + setCacheColorHint(a.getColor( + R.styleable.AbsListView_cacheColorHint, 0)); + setSmoothScrollbarEnabled(a.getBoolean( + R.styleable.AbsListView_smoothScrollbar, true)); + setChoiceMode(a.getInt( + R.styleable.AbsListView_choiceMode, CHOICE_MODE_NONE)); + + setFastScrollEnabled(a.getBoolean( + R.styleable.AbsListView_fastScrollEnabled, false)); + setFastScrollStyle(a.getResourceId( + R.styleable.AbsListView_fastScrollStyle, 0)); + setFastScrollAlwaysVisible(a.getBoolean( + R.styleable.AbsListView_fastScrollAlwaysVisible, false)); a.recycle(); } diff --git a/core/java/android/widget/AdapterView.java b/core/java/android/widget/AdapterView.java index 54e3996..6962711 100644 --- a/core/java/android/widget/AdapterView.java +++ b/core/java/android/widget/AdapterView.java @@ -304,16 +304,19 @@ public abstract class AdapterView<T extends Adapter> extends ViewGroup { * called, false otherwise is returned. */ public boolean performItemClick(View view, int position, long id) { + final boolean result; if (mOnItemClickListener != null) { playSoundEffect(SoundEffectConstants.CLICK); mOnItemClickListener.onItemClick(this, view, position, id); - if (view != null) { - view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); - } - return true; + result = true; + } else { + result = false; } - return false; + if (view != null) { + view.sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_CLICKED); + } + return result; } /** diff --git a/core/java/android/widget/ArrayAdapter.java b/core/java/android/widget/ArrayAdapter.java index ae94a10..260854f 100644 --- a/core/java/android/widget/ArrayAdapter.java +++ b/core/java/android/widget/ArrayAdapter.java @@ -50,8 +50,7 @@ import java.util.List; * or to have some of data besides toString() results fill the views, * override {@link #getView(int, View, ViewGroup)} to return the type of view you want. */ -public class ArrayAdapter<T> extends BaseAdapter implements Filterable, - Spinner.ThemedSpinnerAdapter { +public class ArrayAdapter<T> extends BaseAdapter implements Filterable, ThemedSpinnerAdapter { /** * Contains the list of objects that represent the data of this ArrayAdapter. * The content of this list is referred to as "the array" in the documentation. diff --git a/core/java/android/widget/CursorAdapter.java b/core/java/android/widget/CursorAdapter.java index d8ce60c..9fb98db 100644 --- a/core/java/android/widget/CursorAdapter.java +++ b/core/java/android/widget/CursorAdapter.java @@ -38,7 +38,7 @@ import android.view.ViewGroup; * columns. */ public abstract class CursorAdapter extends BaseAdapter implements Filterable, - CursorFilter.CursorFilterClient, Spinner.ThemedSpinnerAdapter { + CursorFilter.CursorFilterClient, ThemedSpinnerAdapter { /** * This field should be made private, so it is hidden from the SDK. * {@hide} diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java index 6cd35f9..0cac529 100644 --- a/core/java/android/widget/Editor.java +++ b/core/java/android/widget/Editor.java @@ -390,6 +390,7 @@ public class Editor { mPreserveDetachedSelection = true; hideControllers(); + stopSelectionActionMode(); mPreserveDetachedSelection = false; mTemporaryDetach = false; } @@ -624,7 +625,6 @@ public class Editor { mSuggestionsPopupWindow.hide(); } hideInsertionPointCursorController(); - stopSelectionActionMode(); } /** @@ -1101,10 +1101,12 @@ public class Editor { final int selStart = mTextView.getSelectionStart(); final int selEnd = mTextView.getSelectionEnd(); hideControllers(); + stopSelectionActionMode(); Selection.setSelection((Spannable) mTextView.getText(), selStart, selEnd); } else { if (mTemporaryDetach) mPreserveDetachedSelection = true; hideControllers(); + stopSelectionActionMode(); if (mTemporaryDetach) mPreserveDetachedSelection = false; downgradeEasyCorrectionSpans(); } @@ -1147,6 +1149,7 @@ public class Editor { // We do not hide the span controllers, since they can be added when a new text is // inserted into the text view (voice IME). hideCursorControllers(); + stopSelectionActionMode(); } private int getLastTapPosition() { @@ -1878,6 +1881,7 @@ public class Editor { void onTouchUpEvent(MotionEvent event) { boolean selectAllGotFocus = mSelectAllOnFocus && mTextView.didTouchFocusSelect(); hideControllers(); + stopSelectionActionMode(); CharSequence text = mTextView.getText(); if (!selectAllGotFocus && text.length() > 0) { // Move cursor @@ -1998,6 +2002,7 @@ public class Editor { mSuggestionsPopupWindow = new SuggestionsPopupWindow(); } hideControllers(); + stopSelectionActionMode(); mSuggestionsPopupWindow.show(); } @@ -3115,35 +3120,30 @@ public class Editor { if (mTextView.canCut()) { menu.add(0, TextView.ID_CUT, 0, com.android.internal.R.string.cut). setAlphabeticShortcut('x'). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } if (mTextView.canCopy()) { menu.add(0, TextView.ID_COPY, 0, com.android.internal.R.string.copy). setAlphabeticShortcut('c'). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } if (mTextView.canPaste()) { menu.add(0, TextView.ID_PASTE, 0, com.android.internal.R.string.paste). setAlphabeticShortcut('v'). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS); } if (mTextView.canShare()) { menu.add(0, TextView.ID_SHARE, 0, com.android.internal.R.string.share). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } if (mTextView.canSelectAllText()) { menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll). setAlphabeticShortcut('a'). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } updateReplaceItem(menu); @@ -3157,8 +3157,7 @@ public class Editor { for (ResolveInfo info : supportedActivities) { menu.add(info.loadLabel(packageManager)) .setIntent(createProcessTextIntentForResolveInfo(info)) - .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM - | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } } } @@ -3190,8 +3189,7 @@ public class Editor { boolean replaceItemExists = menu.findItem(TextView.ID_REPLACE) != null; if (canReplace && !replaceItemExists) { menu.add(0, TextView.ID_REPLACE, 0, com.android.internal.R.string.replace). - setShowAsAction( - MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT); + setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM); } else if (!canReplace && replaceItemExists) { menu.removeItem(TextView.ID_REPLACE); } diff --git a/core/java/android/widget/ListView.java b/core/java/android/widget/ListView.java index 7dcaa1f..f8b965f 100644 --- a/core/java/android/widget/ListView.java +++ b/core/java/android/widget/ListView.java @@ -16,6 +16,7 @@ package android.widget; +import android.annotation.Nullable; import android.os.Bundle; import android.os.Trace; import com.android.internal.R; @@ -144,7 +145,7 @@ public class ListView extends AbsListView { } public ListView(Context context, AttributeSet attrs) { - this(context, attrs, com.android.internal.R.attr.listViewStyle); + this(context, attrs, R.attr.listViewStyle); } public ListView(Context context, AttributeSet attrs, int defStyleAttr) { @@ -155,38 +156,37 @@ public class ListView extends AbsListView { super(context, attrs, defStyleAttr, defStyleRes); final TypedArray a = context.obtainStyledAttributes( - attrs, com.android.internal.R.styleable.ListView, defStyleAttr, defStyleRes); + attrs, R.styleable.ListView, defStyleAttr, defStyleRes); - CharSequence[] entries = a.getTextArray( - com.android.internal.R.styleable.ListView_entries); + final CharSequence[] entries = a.getTextArray(R.styleable.ListView_entries); if (entries != null) { - setAdapter(new ArrayAdapter<CharSequence>(context, - com.android.internal.R.layout.simple_list_item_1, entries)); + setAdapter(new ArrayAdapter<>(context, R.layout.simple_list_item_1, entries)); } - final Drawable d = a.getDrawable(com.android.internal.R.styleable.ListView_divider); + final Drawable d = a.getDrawable(R.styleable.ListView_divider); if (d != null) { - // If a divider is specified use its intrinsic height for divider height + // Use an implicit divider height which may be explicitly + // overridden by android:dividerHeight further down. setDivider(d); } - - final Drawable osHeader = a.getDrawable( - com.android.internal.R.styleable.ListView_overScrollHeader); + + final Drawable osHeader = a.getDrawable(R.styleable.ListView_overScrollHeader); if (osHeader != null) { setOverscrollHeader(osHeader); } - final Drawable osFooter = a.getDrawable( - com.android.internal.R.styleable.ListView_overScrollFooter); + final Drawable osFooter = a.getDrawable(R.styleable.ListView_overScrollFooter); if (osFooter != null) { setOverscrollFooter(osFooter); } - // Use the height specified, zero being the default - final int dividerHeight = a.getDimensionPixelSize( - com.android.internal.R.styleable.ListView_dividerHeight, 0); - if (dividerHeight != 0) { - setDividerHeight(dividerHeight); + // Use an explicit divider height, if specified. + if (a.hasValueOrEmpty(R.styleable.ListView_dividerHeight)) { + final int dividerHeight = a.getDimensionPixelSize( + R.styleable.ListView_dividerHeight, 0); + if (dividerHeight != 0) { + setDividerHeight(dividerHeight); + } } mHeaderDividersEnabled = a.getBoolean(R.styleable.ListView_headerDividersEnabled, true); @@ -3434,18 +3434,23 @@ public class ListView extends AbsListView { * Returns the drawable that will be drawn between each item in the list. * * @return the current drawable drawn between list elements + * @attr ref R.styleable#ListView_divider */ + @Nullable public Drawable getDivider() { return mDivider; } /** - * Sets the drawable that will be drawn between each item in the list. If the drawable does - * not have an intrinsic height, you should also call {@link #setDividerHeight(int)} + * Sets the drawable that will be drawn between each item in the list. + * <p> + * <strong>Note:</strong> If the drawable does not have an intrinsic + * height, you should also call {@link #setDividerHeight(int)}. * - * @param divider The drawable to use. + * @param divider the drawable to use + * @attr ref R.styleable#ListView_divider */ - public void setDivider(Drawable divider) { + public void setDivider(@Nullable Drawable divider) { if (divider != null) { mDividerHeight = divider.getIntrinsicHeight(); } else { diff --git a/core/java/android/widget/RemoteViews.java b/core/java/android/widget/RemoteViews.java index dc75fd0..74843ee 100644 --- a/core/java/android/widget/RemoteViews.java +++ b/core/java/android/widget/RemoteViews.java @@ -867,13 +867,13 @@ public class RemoteViews implements Parcelable, Filter { if (targetDrawable != null) { // Perform modifications only if values are set correctly if (alpha != -1) { - targetDrawable.setAlpha(alpha); + targetDrawable.mutate().setAlpha(alpha); } if (filterMode != null) { - targetDrawable.setColorFilter(colorFilter, filterMode); + targetDrawable.mutate().setColorFilter(colorFilter, filterMode); } if (level != -1) { - targetDrawable.setLevel(level); + targetDrawable.mutate().setLevel(level); } } } diff --git a/core/java/android/widget/SimpleAdapter.java b/core/java/android/widget/SimpleAdapter.java index 2008ba8..e7760ee 100644 --- a/core/java/android/widget/SimpleAdapter.java +++ b/core/java/android/widget/SimpleAdapter.java @@ -51,7 +51,7 @@ import java.util.Map; * </ul> * If no appropriate binding can be found, an {@link IllegalStateException} is thrown. */ -public class SimpleAdapter extends BaseAdapter implements Filterable, Spinner.ThemedSpinnerAdapter { +public class SimpleAdapter extends BaseAdapter implements Filterable, ThemedSpinnerAdapter { private int[] mTo; private String[] mFrom; private ViewBinder mViewBinder; diff --git a/core/java/android/widget/Spinner.java b/core/java/android/widget/Spinner.java index 095cc44..6fe34dd 100644 --- a/core/java/android/widget/Spinner.java +++ b/core/java/android/widget/Spinner.java @@ -26,6 +26,7 @@ import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.res.Resources; +import android.content.res.Resources.Theme; import android.content.res.TypedArray; import android.database.DataSetObserver; import android.graphics.Rect; @@ -217,24 +218,24 @@ public class Spinner extends AbsSpinner implements OnClickListener { * Can be 0 to not look for defaults. * @param mode Constant describing how the user will select choices from * the spinner. - * @param popupContext The context against which the dialog or dropdown - * popup will be inflated. Can be null to use the view - * context. If set, this will override any value - * specified by - * {@link android.R.styleable#Spinner_popupTheme}. + * @param popupTheme The theme against which the dialog or dropdown popup + * should be inflated. May be {@code null} to use the + * view theme. If set, this will override any value + * specified by + * {@link android.R.styleable#Spinner_popupTheme}. * * @see #MODE_DIALOG * @see #MODE_DROPDOWN */ public Spinner(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes, int mode, - Context popupContext) { + Theme popupTheme) { super(context, attrs, defStyleAttr, defStyleRes); final TypedArray a = context.obtainStyledAttributes( attrs, R.styleable.Spinner, defStyleAttr, defStyleRes); - if (popupContext != null) { - mPopupContext = popupContext; + if (popupTheme != null) { + mPopupContext = new ContextThemeWrapper(context, popupTheme); } else { final int popupThemeResId = a.getResourceId(R.styleable.Spinner_popupTheme, 0); if (popupThemeResId != 0) { @@ -932,9 +933,8 @@ public class Spinner extends AbsSpinner implements OnClickListener { mListAdapter = (ListAdapter) adapter; } - if (dropDownTheme != null && adapter instanceof Spinner.ThemedSpinnerAdapter) { - final Spinner.ThemedSpinnerAdapter themedAdapter = - (Spinner.ThemedSpinnerAdapter) adapter; + if (dropDownTheme != null && adapter instanceof ThemedSpinnerAdapter) { + final ThemedSpinnerAdapter themedAdapter = (ThemedSpinnerAdapter) adapter; if (themedAdapter.getDropDownViewTheme() == null) { themedAdapter.setDropDownViewTheme(dropDownTheme); } @@ -1263,20 +1263,4 @@ public class Spinner extends AbsSpinner implements OnClickListener { } } - public interface ThemedSpinnerAdapter { - /** - * Sets the {@link Resources.Theme} against which drop-down views are - * inflated. - * - * @param theme the context against which to inflate drop-down views - * @see SpinnerAdapter#getDropDownView(int, View, ViewGroup) - */ - public void setDropDownViewTheme(Resources.Theme theme); - - /** - * @return The {@link Resources.Theme} against which drop-down views are - * inflated. - */ - public Resources.Theme getDropDownViewTheme(); - } } diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java index 15d796c..e14e39c 100644 --- a/core/java/android/widget/TextView.java +++ b/core/java/android/widget/TextView.java @@ -6423,6 +6423,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener // extracted mode will start. Some text is selected though, and will trigger an action mode // in the extracted view. mEditor.hideControllers(); + stopSelectionActionMode(); } /** @@ -8257,6 +8258,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener super.onVisibilityChanged(changedView, visibility); if (mEditor != null && visibility != VISIBLE) { mEditor.hideControllers(); + stopSelectionActionMode(); } } diff --git a/core/java/android/widget/ThemedSpinnerAdapter.java b/core/java/android/widget/ThemedSpinnerAdapter.java new file mode 100644 index 0000000..6d92620 --- /dev/null +++ b/core/java/android/widget/ThemedSpinnerAdapter.java @@ -0,0 +1,53 @@ +/* + * Copyright (C) 2015 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.widget; + +import android.annotation.Nullable; +import android.content.res.Resources; +import android.content.res.Resources.Theme; +import android.view.View; +import android.view.ViewGroup; + +/** + * An extension of SpinnerAdapter that is capable of inflating drop-down views + * against a different theme than normal views. + * <p> + * Classes that implement this interface should use the theme provided to + * {@link #setDropDownViewTheme(Theme)} when creating views in + * {@link SpinnerAdapter#getDropDownView(int, View, ViewGroup)}. + */ +public interface ThemedSpinnerAdapter extends SpinnerAdapter { + /** + * Sets the {@link Resources.Theme} against which drop-down views are + * inflated. + * + * @param theme the context against which to inflate drop-down views, or + * {@code null} to use the default theme + * @see SpinnerAdapter#getDropDownView(int, View, ViewGroup) + */ + void setDropDownViewTheme(@Nullable Resources.Theme theme); + + /** + * Returns the value previously set by a call to + * {@link #setDropDownViewTheme(Theme)}. + * + * @return the {@link Resources.Theme} against which drop-down views are + * inflated, or {@code null} if one has not been explicitly set + */ + @Nullable + Resources.Theme getDropDownViewTheme(); +} |