summaryrefslogtreecommitdiffstats
path: root/core/java/android
diff options
context:
space:
mode:
Diffstat (limited to 'core/java/android')
-rw-r--r--core/java/android/accounts/AccountManager.java11
-rw-r--r--core/java/android/app/Activity.java215
-rw-r--r--core/java/android/app/ActivityThread.java3
-rw-r--r--core/java/android/app/AlarmManager.java43
-rw-r--r--core/java/android/app/AppOpsManager.java141
-rw-r--r--core/java/android/app/ApplicationPackageManager.java40
-rw-r--r--core/java/android/app/AssistStructure.java11
-rw-r--r--core/java/android/app/BackStackRecord.java12
-rw-r--r--core/java/android/app/DialogFragment.java2
-rw-r--r--core/java/android/app/Fragment.java137
-rw-r--r--core/java/android/app/FragmentContainer.java38
-rw-r--r--core/java/android/app/FragmentController.java384
-rw-r--r--core/java/android/app/FragmentHostCallback.java315
-rw-r--r--core/java/android/app/FragmentManager.java100
-rw-r--r--core/java/android/app/KeyguardManager.java20
-rw-r--r--core/java/android/app/LoaderManager.java40
-rw-r--r--core/java/android/app/StatusBarManager.java12
-rw-r--r--core/java/android/app/admin/DevicePolicyManager.java78
-rw-r--r--core/java/android/app/admin/IDevicePolicyManager.aidl5
-rw-r--r--core/java/android/bluetooth/BluetoothAdapter.java33
-rw-r--r--core/java/android/bluetooth/IBluetoothManager.aidl2
-rw-r--r--core/java/android/bluetooth/le/ScanSettings.java4
-rw-r--r--core/java/android/content/ContentProviderNative.java3
-rw-r--r--core/java/android/content/Context.java29
-rw-r--r--core/java/android/content/pm/IPackageManager.aidl1
-rw-r--r--core/java/android/content/pm/IPackageMoveObserver.aidl4
-rw-r--r--core/java/android/content/pm/PackageManager.java15
-rw-r--r--core/java/android/content/pm/PackageParser.java3
-rw-r--r--core/java/android/content/res/ColorStateList.java27
-rw-r--r--core/java/android/content/res/Resources.java13
-rw-r--r--core/java/android/hardware/camera2/CameraCaptureSession.java5
-rw-r--r--core/java/android/hardware/camera2/CameraCharacteristics.java161
-rw-r--r--core/java/android/hardware/camera2/CameraDevice.java22
-rw-r--r--core/java/android/hardware/camera2/CameraMetadata.java86
-rw-r--r--core/java/android/hardware/camera2/CaptureRequest.java35
-rw-r--r--core/java/android/hardware/camera2/CaptureResult.java46
-rw-r--r--core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java14
-rw-r--r--core/java/android/hardware/display/DisplayManagerInternal.java7
-rw-r--r--core/java/android/hardware/fingerprint/FingerprintManager.java47
-rw-r--r--core/java/android/hardware/fingerprint/IFingerprintService.aidl12
-rw-r--r--core/java/android/hardware/usb/UsbDevice.java19
-rw-r--r--core/java/android/net/ConnectivityManager.java145
-rw-r--r--core/java/android/net/INetworkPolicyManager.aidl2
-rw-r--r--core/java/android/net/NetworkCapabilities.java19
-rw-r--r--core/java/android/net/NetworkPolicyManager.java20
-rw-r--r--core/java/android/net/Uri.java2
-rw-r--r--core/java/android/os/Environment.java13
-rw-r--r--core/java/android/os/FileUtils.java2
-rw-r--r--core/java/android/os/IDeviceIdleController.aidl26
-rw-r--r--core/java/android/os/INetworkManagementService.aidl2
-rw-r--r--core/java/android/os/IPermissionController.aidl1
-rw-r--r--core/java/android/os/PowerManager.java8
-rw-r--r--core/java/android/os/Process.java3
-rw-r--r--core/java/android/os/storage/IMountService.java84
-rw-r--r--core/java/android/os/storage/IMountServiceListener.java44
-rw-r--r--core/java/android/os/storage/StorageEventListener.java5
-rw-r--r--core/java/android/os/storage/StorageManager.java158
-rw-r--r--core/java/android/os/storage/VolumeInfo.java42
-rw-r--r--core/java/android/os/storage/VolumeRecord.java139
-rw-r--r--core/java/android/provider/Settings.java9
-rw-r--r--core/java/android/security/keymaster/KeyCharacteristics.java30
-rw-r--r--core/java/android/security/keymaster/KeymasterDefs.java5
-rw-r--r--core/java/android/service/notification/ZenModeConfig.java152
-rw-r--r--core/java/android/speech/RecognizerIntent.java8
-rw-r--r--core/java/android/transition/TransitionInflater.java2
-rw-r--r--core/java/android/util/EventLog.java18
-rw-r--r--core/java/android/view/DisplayListCanvas.java18
-rw-r--r--core/java/android/view/HapticFeedbackConstants.java5
-rw-r--r--core/java/android/view/LayoutInflater.java28
-rw-r--r--core/java/android/view/MotionEvent.java12
-rw-r--r--core/java/android/view/PhoneWindow.java2
-rw-r--r--core/java/android/view/TextureView.java8
-rw-r--r--core/java/android/view/ThreadedRenderer.java4
-rw-r--r--core/java/android/view/View.java293
-rw-r--r--core/java/android/view/ViewAssistStructure.java2
-rw-r--r--core/java/android/view/ViewGroup.java3
-rw-r--r--core/java/android/view/accessibility/AccessibilityEvent.java14
-rw-r--r--core/java/android/view/accessibility/AccessibilityNodeInfo.java34
-rw-r--r--core/java/android/widget/DayPickerPagerAdapter.java6
-rw-r--r--core/java/android/widget/DayPickerView.java20
-rw-r--r--core/java/android/widget/Editor.java100
-rw-r--r--core/java/android/widget/SearchView.java69
-rw-r--r--core/java/android/widget/SimpleMonthView.java49
-rw-r--r--core/java/android/widget/Switch.java2
-rw-r--r--core/java/android/widget/TextView.java12
85 files changed, 2838 insertions, 977 deletions
diff --git a/core/java/android/accounts/AccountManager.java b/core/java/android/accounts/AccountManager.java
index 480d171..ffa36d6 100644
--- a/core/java/android/accounts/AccountManager.java
+++ b/core/java/android/accounts/AccountManager.java
@@ -207,8 +207,7 @@ public class AccountManager {
* were authenticated successfully. Time is specified in milliseconds since
* epoch.
*/
- public static final String KEY_LAST_AUTHENTICATE_TIME_MILLIS_EPOCH =
- "lastAuthenticatedTimeMillisEpoch";
+ public static final String KEY_LAST_AUTHENTICATED_TIME = "lastAuthenticatedTime";
/**
* Authenticators using 'customTokens' option will also get the UID of the
@@ -671,8 +670,8 @@ public class AccountManager {
}
/**
- * Informs the system that the account has been authenticated recently. This
- * recency may be used by other applications to verify the account. This
+ * Notifies the system that the account has just been authenticated. This
+ * information may be used by other applications to verify the account. This
* should be called only when the user has entered correct credentials for
* the account.
* <p>
@@ -685,7 +684,7 @@ public class AccountManager {
*
* @param account The {@link Account} to be updated.
*/
- public boolean accountAuthenticated(Account account) {
+ public boolean notifyAccountAuthenticated(Account account) {
if (account == null)
throw new IllegalArgumentException("account is null");
try {
@@ -1587,7 +1586,7 @@ public class AccountManager {
* password prompt.
*
* <p>Also the returning Bundle may contain {@link
- * #KEY_LAST_AUTHENTICATE_TIME_MILLIS_EPOCH} indicating the last time the
+ * #KEY_LAST_AUTHENTICATED_TIME} indicating the last time the
* credential was validated/created.
*
* If an error occurred,{@link AccountManagerFuture#getResult()} throws:
diff --git a/core/java/android/app/Activity.java b/core/java/android/app/Activity.java
index 69cba78..e79e20c 100644
--- a/core/java/android/app/Activity.java
+++ b/core/java/android/app/Activity.java
@@ -108,6 +108,7 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.util.ArrayList;
import java.util.HashMap;
+import java.util.List;
/**
* An activity is a single, focused thing that the user can do. Almost all
@@ -706,8 +707,6 @@ public class Activity extends ContextThemeWrapper
/*package*/ ActivityThread mMainThread;
Activity mParent;
boolean mCalled;
- boolean mCheckedForLoaderManager;
- boolean mLoadersStarted;
/*package*/ boolean mResumed;
private boolean mStopped;
boolean mFinished;
@@ -726,8 +725,8 @@ public class Activity extends ContextThemeWrapper
static final class NonConfigurationInstances {
Object activity;
HashMap<String, Object> children;
- ArrayList<Fragment> fragments;
- ArrayMap<String, LoaderManagerImpl> loaders;
+ List<Fragment> fragments;
+ ArrayMap<String, LoaderManager> loaders;
VoiceInteractor voiceInteractor;
}
/* package */ NonConfigurationInstances mLastNonConfigurationInstances;
@@ -747,26 +746,13 @@ public class Activity extends ContextThemeWrapper
private CharSequence mTitle;
private int mTitleColor = 0;
- final FragmentManagerImpl mFragments = new FragmentManagerImpl();
- final FragmentContainer mContainer = new FragmentContainer() {
- @Override
- @Nullable
- public View findViewById(int id) {
- return Activity.this.findViewById(id);
- }
- @Override
- public boolean hasView() {
- Window window = Activity.this.getWindow();
- return (window != null && window.peekDecorView() != null);
- }
- };
+ // we must have a handler before the FragmentController is constructed
+ final Handler mHandler = new Handler();
+ final FragmentController mFragments = FragmentController.createController(new HostCallbacks());
// Most recent call to requestVisibleBehind().
boolean mVisibleBehind;
- ArrayMap<String, LoaderManagerImpl> mAllLoaderManagers;
- LoaderManagerImpl mLoaderManager;
-
private static final class ManagedCursor {
ManagedCursor(Cursor cursor) {
mCursor = cursor;
@@ -802,7 +788,6 @@ public class Activity extends ContextThemeWrapper
private final Object mInstanceTracker = StrictMode.trackActivity(this);
private Thread mUiThread;
- final Handler mHandler = new Handler();
ActivityTransitionState mActivityTransitionState = new ActivityTransitionState();
SharedElementCallback mEnterTransitionListener = SharedElementCallback.NULL_CALLBACK;
@@ -863,28 +848,7 @@ public class Activity extends ContextThemeWrapper
* Return the LoaderManager for this activity, creating it if needed.
*/
public LoaderManager getLoaderManager() {
- if (mLoaderManager != null) {
- return mLoaderManager;
- }
- mCheckedForLoaderManager = true;
- mLoaderManager = getLoaderManager("(root)", mLoadersStarted, true);
- return mLoaderManager;
- }
-
- LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
- if (mAllLoaderManagers == null) {
- mAllLoaderManagers = new ArrayMap<String, LoaderManagerImpl>();
- }
- LoaderManagerImpl lm = mAllLoaderManagers.get(who);
- if (lm == null) {
- if (create) {
- lm = new LoaderManagerImpl(who, this, started);
- mAllLoaderManagers.put(who, lm);
- }
- } else {
- lm.updateActivity(this);
- }
- return lm;
+ return mFragments.getLoaderManager();
}
/**
@@ -931,7 +895,7 @@ public class Activity extends ContextThemeWrapper
protected void onCreate(@Nullable Bundle savedInstanceState) {
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onCreate " + this + ": " + savedInstanceState);
if (mLastNonConfigurationInstances != null) {
- mAllLoaderManagers = mLastNonConfigurationInstances.loaders;
+ mFragments.restoreLoaderNonConfig(mLastNonConfigurationInstances.loaders);
}
if (mActivityInfo.parentActivityName != null) {
if (mActionBar == null) {
@@ -1172,15 +1136,7 @@ public class Activity extends ContextThemeWrapper
if (DEBUG_LIFECYCLE) Slog.v(TAG, "onStart " + this);
mCalled = true;
- if (!mLoadersStarted) {
- mLoadersStarted = true;
- if (mLoaderManager != null) {
- mLoaderManager.doStart();
- } else if (!mCheckedForLoaderManager) {
- mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
- }
- mCheckedForLoaderManager = true;
- }
+ mFragments.doLoaderStart();
getApplication().dispatchActivityStarted(this);
}
@@ -1873,27 +1829,9 @@ public class Activity extends ContextThemeWrapper
NonConfigurationInstances retainNonConfigurationInstances() {
Object activity = onRetainNonConfigurationInstance();
HashMap<String, Object> children = onRetainNonConfigurationChildInstances();
- ArrayList<Fragment> fragments = mFragments.retainNonConfig();
- boolean retainLoaders = false;
- if (mAllLoaderManagers != null) {
- // prune out any loader managers that were already stopped and so
- // have nothing useful to retain.
- final int N = mAllLoaderManagers.size();
- LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
- for (int i=N-1; i>=0; i--) {
- loaders[i] = mAllLoaderManagers.valueAt(i);
- }
- for (int i=0; i<N; i++) {
- LoaderManagerImpl lm = loaders[i];
- if (lm.mRetaining) {
- retainLoaders = true;
- } else {
- lm.doDestroy();
- mAllLoaderManagers.remove(lm.mWho);
- }
- }
- }
- if (activity == null && children == null && fragments == null && !retainLoaders
+ List<Fragment> fragments = mFragments.retainNonConfig();
+ ArrayMap<String, LoaderManager> loaders = mFragments.retainLoaderNonConfig();
+ if (activity == null && children == null && fragments == null && loaders == null
&& mVoiceInteractor == null) {
return null;
}
@@ -1902,7 +1840,7 @@ public class Activity extends ContextThemeWrapper
nci.activity = activity;
nci.children = children;
nci.fragments = fragments;
- nci.loaders = mAllLoaderManagers;
+ nci.loaders = loaders;
nci.voiceInteractor = mVoiceInteractor;
return nci;
}
@@ -1924,18 +1862,7 @@ public class Activity extends ContextThemeWrapper
* with this activity.
*/
public FragmentManager getFragmentManager() {
- return mFragments;
- }
-
- void invalidateFragment(String who) {
- //Log.v(TAG, "invalidateFragmentIndex: index=" + index);
- if (mAllLoaderManagers != null) {
- LoaderManagerImpl lm = mAllLoaderManagers.get(who);
- if (lm != null && !lm.mRetaining) {
- lm.doDestroy();
- mAllLoaderManagers.remove(who);
- }
- }
+ return mFragments.getFragmentManager();
}
/**
@@ -2518,7 +2445,7 @@ public class Activity extends ContextThemeWrapper
return;
}
- if (!mFragments.popBackStackImmediate()) {
+ if (!mFragments.getFragmentManager().popBackStackImmediate()) {
finishAfterTransition();
}
}
@@ -5518,21 +5445,13 @@ public class Activity extends ContextThemeWrapper
writer.print(mResumed); writer.print(" mStopped=");
writer.print(mStopped); writer.print(" mFinished=");
writer.println(mFinished);
- writer.print(innerPrefix); writer.print("mLoadersStarted=");
- writer.println(mLoadersStarted);
writer.print(innerPrefix); writer.print("mChangingConfigurations=");
writer.println(mChangingConfigurations);
writer.print(innerPrefix); writer.print("mCurrentConfig=");
writer.println(mCurrentConfig);
- if (mLoaderManager != null) {
- writer.print(prefix); writer.print("Loader Manager ");
- writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
- writer.println(":");
- mLoaderManager.dump(prefix + " ", fd, writer, args);
- }
-
- mFragments.dump(prefix, fd, writer, args);
+ mFragments.dumpLoaders(innerPrefix, fd, writer, args);
+ mFragments.getFragmentManager().dump(innerPrefix, fd, writer, args);
if (getWindow() != null &&
getWindow().peekDecorView() != null &&
@@ -6128,7 +6047,7 @@ public class Activity extends ContextThemeWrapper
Configuration config, String referrer, IVoiceInteractor voiceInteractor) {
attachBaseContext(context);
- mFragments.attachActivity(this, mContainer, null);
+ mFragments.attachHost(null /*parent*/);
mWindow = new PhoneWindow(this);
mWindow.setCallback(this);
@@ -6211,18 +6130,7 @@ public class Activity extends ContextThemeWrapper
" did not call through to super.onStart()");
}
mFragments.dispatchStart();
- if (mAllLoaderManagers != null) {
- final int N = mAllLoaderManagers.size();
- LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
- for (int i=N-1; i>=0; i--) {
- loaders[i] = mAllLoaderManagers.valueAt(i);
- }
- for (int i=0; i<N; i++) {
- LoaderManagerImpl lm = loaders[i];
- lm.finishRetain();
- lm.doReportStart();
- }
- }
+ mFragments.reportLoaderStart();
mActivityTransitionState.enterReady(this);
}
@@ -6328,16 +6236,7 @@ public class Activity extends ContextThemeWrapper
final void performStop() {
mDoReportFullyDrawn = false;
- if (mLoadersStarted) {
- mLoadersStarted = false;
- if (mLoaderManager != null) {
- if (!mChangingConfigurations) {
- mLoaderManager.doStop();
- } else {
- mLoaderManager.doRetain();
- }
- }
- }
+ mFragments.doLoaderStop(mChangingConfigurations /*retain*/);
if (!mStopped) {
if (mWindow != null) {
@@ -6379,9 +6278,7 @@ public class Activity extends ContextThemeWrapper
mWindow.destroy();
mFragments.dispatchDestroy();
onDestroy();
- if (mLoaderManager != null) {
- mLoaderManager.doDestroy();
- }
+ mFragments.doLoaderDestroy();
if (mVoiceInteractor != null) {
mVoiceInteractor.detachActivity();
}
@@ -6541,4 +6438,74 @@ public class Activity extends ContextThemeWrapper
return intent != null
&& PackageManager.ACTION_REQUEST_PERMISSIONS.equals(intent.getAction());
}
+
+ class HostCallbacks extends FragmentHostCallback<Activity> {
+ public HostCallbacks() {
+ super(Activity.this /*activity*/);
+ }
+
+ @Override
+ public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
+ Activity.this.dump(prefix, fd, writer, args);
+ }
+
+ @Override
+ public boolean onShouldSaveFragmentState(Fragment fragment) {
+ return !isFinishing();
+ }
+
+ @Override
+ public LayoutInflater onGetLayoutInflater() {
+ final LayoutInflater result = Activity.this.getLayoutInflater();
+ if (onUseFragmentManagerInflaterFactory()) {
+ return result.cloneInContext(Activity.this);
+ }
+ return result;
+ }
+
+ @Override
+ public boolean onUseFragmentManagerInflaterFactory() {
+ // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
+ return getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP;
+ }
+
+ @Override
+ public Activity onGetHost() {
+ return Activity.this;
+ }
+
+ @Override
+ public void onInvalidateOptionsMenu() {
+ Activity.this.invalidateOptionsMenu();
+ }
+
+ @Override
+ public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
+ Bundle options) {
+ Activity.this.startActivityFromFragment(fragment, intent, requestCode, options);
+ }
+
+ @Override
+ public boolean onHasWindowAnimations() {
+ return getWindow() != null;
+ }
+
+ @Override
+ public int onGetWindowAnimations() {
+ final Window w = getWindow();
+ return (w == null) ? 0 : w.getAttributes().windowAnimations;
+ }
+
+ @Nullable
+ @Override
+ public View onFindViewById(int id) {
+ return Activity.this.findViewById(id);
+ }
+
+ @Override
+ public boolean onHasView() {
+ final Window w = getWindow();
+ return (w != null && w.peekDecorView() != null);
+ }
+ }
}
diff --git a/core/java/android/app/ActivityThread.java b/core/java/android/app/ActivityThread.java
index 9bad9bb..2e45b79 100644
--- a/core/java/android/app/ActivityThread.java
+++ b/core/java/android/app/ActivityThread.java
@@ -114,7 +114,6 @@ import java.io.IOException;
import java.io.PrintWriter;
import java.lang.ref.WeakReference;
import java.net.InetAddress;
-import java.security.Security;
import java.text.DateFormat;
import java.util.ArrayList;
import java.util.List;
@@ -5338,7 +5337,7 @@ public final class ActivityThread {
// Set the reporter for event logging in libcore
EventLogger.setReporter(new EventLoggingReporter());
- Security.addProvider(new AndroidKeyStoreProvider());
+ AndroidKeyStoreProvider.install();
// Make sure TrustedCertificateStore looks in the right place for CA certificates
final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId());
diff --git a/core/java/android/app/AlarmManager.java b/core/java/android/app/AlarmManager.java
index 9d1d312..b0fda9c 100644
--- a/core/java/android/app/AlarmManager.java
+++ b/core/java/android/app/AlarmManager.java
@@ -26,6 +26,10 @@ import android.os.Parcelable;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.WorkSource;
+import android.text.TextUtils;
+import libcore.util.ZoneInfoDB;
+
+import java.io.IOException;
/**
* This class provides access to the system alarm services. These allow you
@@ -151,6 +155,7 @@ public class AlarmManager
private final IAlarmManager mService;
private final boolean mAlwaysExact;
+ private final int mTargetSdkVersion;
/**
@@ -159,8 +164,8 @@ public class AlarmManager
AlarmManager(IAlarmManager service, Context ctx) {
mService = service;
- final int sdkVersion = ctx.getApplicationInfo().targetSdkVersion;
- mAlwaysExact = (sdkVersion < Build.VERSION_CODES.KITKAT);
+ mTargetSdkVersion = ctx.getApplicationInfo().targetSdkVersion;
+ mAlwaysExact = (mTargetSdkVersion < Build.VERSION_CODES.KITKAT);
}
private long legacyExactLength() {
@@ -585,12 +590,38 @@ public class AlarmManager
}
/**
- * Set the system default time zone.
- * Requires the permission android.permission.SET_TIME_ZONE.
- *
- * @param timeZone in the format understood by {@link java.util.TimeZone}
+ * Sets the system's persistent default time zone. This is the time zone for all apps, even
+ * after a reboot. Use {@link java.util.TimeZone#setDefault} if you just want to change the
+ * time zone within your app, and even then prefer to pass an explicit
+ * {@link java.util.TimeZone} to APIs that require it rather than changing the time zone for
+ * all threads.
+ *
+ * <p> On android M and above, it is an error to pass in a non-Olson timezone to this
+ * function. Note that this is a bad idea on all Android releases because POSIX and
+ * the {@code TimeZone} class have opposite interpretations of {@code '+'} and {@code '-'}
+ * in the same non-Olson ID.
+ *
+ * @param timeZone one of the Olson ids from the list returned by
+ * {@link java.util.TimeZone#getAvailableIDs}
*/
public void setTimeZone(String timeZone) {
+ if (TextUtils.isEmpty(timeZone)) {
+ return;
+ }
+
+ // Reject this timezone if it isn't an Olson zone we recognize.
+ if (mTargetSdkVersion >= Build.VERSION_CODES.MNC) {
+ boolean hasTimeZone = false;
+ try {
+ hasTimeZone = ZoneInfoDB.getInstance().hasTimeZone(timeZone);
+ } catch (IOException ignored) {
+ }
+
+ if (!hasTimeZone) {
+ throw new IllegalArgumentException("Timezone: " + timeZone + " is not an Olson ID");
+ }
+ }
+
try {
mService.setTimeZone(timeZone);
} catch (RemoteException ex) {
diff --git a/core/java/android/app/AppOpsManager.java b/core/java/android/app/AppOpsManager.java
index 223d528..8a3c9c8 100644
--- a/core/java/android/app/AppOpsManager.java
+++ b/core/java/android/app/AppOpsManager.java
@@ -217,12 +217,17 @@ public class AppOpsManager {
public static final int OP_READ_PHONE_STATE = 51;
/** @hide Add voicemail messages to the voicemail content provider. */
public static final int OP_ADD_VOICEMAIL = 52;
+ /** @hide Access APIs for SIP calling over VOIP or WiFi. */
+ public static final int OP_USE_SIP = 53;
+ /** @hide Intercept outgoing calls. */
+ public static final int OP_PROCESS_OUTGOING_CALLS = 54;
+ /** @hide User the fingerprint API. */
+ public static final int OP_USE_FINGERPRINT = 55;
/** @hide */
- public static final int _NUM_OP = 53;
+ public static final int _NUM_OP = 56;
/** Access to coarse location information. */
- public static final String OPSTR_COARSE_LOCATION =
- "android:coarse_location";
+ public static final String OPSTR_COARSE_LOCATION = "android:coarse_location";
/** Access to fine location information. */
public static final String OPSTR_FINE_LOCATION =
"android:fine_location";
@@ -237,7 +242,59 @@ public class AppOpsManager {
= "android:get_usage_stats";
/** Activate a VPN connection without user intervention. @hide */
@SystemApi
- public static final String OPSTR_ACTIVATE_VPN = "android:activate_vpn";
+ public static final String OPSTR_ACTIVATE_VPN
+ = "android:activate_vpn";
+ /** @hide Allows an application to read the user's contacts data. */
+ public static final String OPSTR_READ_CONTACTS
+ = "android:read_contacts";
+ /** @hide Allows an application to write to the user's contacts data. */
+ public static final String OPSTR_WRITE_CONTACTS
+ = "android:write_contacts";
+ /** @hide Allows an application to read the user's call log. */
+ public static final String OPSTR_READ_CALL_LOG
+ = "android:read_call_log";
+ /** @hide Allows an application to write to the user's call log. */
+ public static final String OPSTR_WRITE_CALL_LOG
+ = "android:write_call_log";
+ /** @hide Allows an application to read the user's calendar data. */
+ public static final String OPSTR_READ_CALENDAR
+ = "android:read_calendar";
+ /** @hide Allows an application to write to the user's calendar data. */
+ public static final String OPSTR_WRITE_CALENDAR
+ = "android:write_calendar";
+ /** @hide Allows an application to initiate a phone call. */
+ public static final String OPSTR_CALL_PHONE
+ = "android:call_phone";
+ /** @hide Allows an application to read SMS messages. */
+ public static final String OPSTR_READ_SMS
+ = "android:read_sms";
+ /** @hide Allows an application to receive SMS messages. */
+ public static final String OPSTR_RECEIVE_SMS
+ = "android:receive_sms";
+ /** @hide Allows an application to receive MMS messages. */
+ public static final String OPSTR_RECEIVE_MMS
+ = "android:receive_mms";
+ /** @hide Allows an application to receive WAP push messages. */
+ public static final String OPSTR_RECEIVE_WAP_PUSH
+ = "android:receive_wap_push";
+ /** @hide Allows an application to send SMS messages. */
+ public static final String OPSTR_SEND_SMS
+ = "android:send_sms";
+ /** @hide Allows an application to add system alert windows. */
+ public static final String OPSTR_SYSTEM_ALERT_WINDOW
+ = "android:system_alert_window";
+ /** @hide Required to be able to access the camera device. */
+ public static final String OPSTR_CAMERA
+ = "android:camera";
+ /** @hide Required to be able to access the microphone device. */
+ public static final String OPSTR_RECORD_AUDIO
+ = "android:record_audio";
+ /** @hide Required to access phone state related information. */
+ public static final String OPSTR_READ_PHONE_STATE
+ = "android:read_phone_state";
+ /** @hide Required to access phone state related information. */
+ public static final String OPSTR_ADD_VOICEMAIL
+ = "android:add_voicemail";
/**
* This maps each operation to the operation that serves as the
@@ -300,7 +357,10 @@ public class AppOpsManager {
OP_ASSIST_STRUCTURE,
OP_ASSIST_SCREENSHOT,
OP_READ_PHONE_STATE,
- OP_ADD_VOICEMAIL
+ OP_ADD_VOICEMAIL,
+ OP_USE_SIP,
+ OP_PROCESS_OUTGOING_CALLS,
+ OP_USE_FINGERPRINT
};
/**
@@ -360,6 +420,9 @@ public class AppOpsManager {
null,
null,
null,
+ null,
+ null,
+ null,
null
};
@@ -420,7 +483,10 @@ public class AppOpsManager {
"ASSIST_STRUCTURE",
"ASSIST_SCREENSHOT",
"OP_READ_PHONE_STATE",
- "ADD_VOICEMAIL"
+ "ADD_VOICEMAIL",
+ "USE_SIP",
+ "PROCESS_OUTGOING_CALLS",
+ "USE_FINGERPRINT"
};
/**
@@ -480,7 +546,10 @@ public class AppOpsManager {
null, // no permission for receiving assist structure
null, // no permission for receiving assist screenshot
Manifest.permission.READ_PHONE_STATE,
- Manifest.permission.ADD_VOICEMAIL
+ Manifest.permission.ADD_VOICEMAIL,
+ Manifest.permission.USE_SIP,
+ Manifest.permission.PROCESS_OUTGOING_CALLS,
+ Manifest.permission.USE_FINGERPRINT
};
/**
@@ -541,7 +610,10 @@ public class AppOpsManager {
null, // ASSIST_STRUCTURE
null, // ASSIST_SCREENSHOT
null, // READ_PHONE_STATE
- null // ADD_VOICEMAIL
+ null, // ADD_VOICEMAIL
+ null, // USE_SIP
+ null, // PROCESS_OUTGOING_CALLS
+ null // USE_FINGERPRINT
};
/**
@@ -601,7 +673,10 @@ public class AppOpsManager {
false, //ASSIST_STRUCTURE
false, //ASSIST_SCREENSHOT
false, //READ_PHONE_STATE
- false //ADD_VOICEMAIL
+ false, //ADD_VOICEMAIL
+ false, // USE_SIP
+ false, // PROCESS_OUTGOING_CALLS
+ false // USE_FINGERPRINT
};
/**
@@ -660,6 +735,9 @@ public class AppOpsManager {
AppOpsManager.MODE_ALLOWED,
AppOpsManager.MODE_ALLOWED,
AppOpsManager.MODE_ALLOWED,
+ AppOpsManager.MODE_ALLOWED,
+ AppOpsManager.MODE_ALLOWED,
+ AppOpsManager.MODE_ALLOWED,
AppOpsManager.MODE_ALLOWED
};
@@ -723,9 +801,39 @@ public class AppOpsManager {
false,
false,
false,
+ false,
+ false,
+ false,
false
};
+ /**
+ * This is a mapping from a permission name to public app op name.
+ */
+ private static final ArrayMap<String, String> sPermToOp = new ArrayMap<>();
+ static {
+ sPermToOp.put(Manifest.permission.ACCESS_COARSE_LOCATION, OPSTR_COARSE_LOCATION);
+ sPermToOp.put(Manifest.permission.ACCESS_FINE_LOCATION, OPSTR_FINE_LOCATION);
+ sPermToOp.put(Manifest.permission.PACKAGE_USAGE_STATS, OPSTR_GET_USAGE_STATS);
+ sPermToOp.put(Manifest.permission.READ_CONTACTS, OPSTR_READ_CONTACTS);
+ sPermToOp.put(Manifest.permission.WRITE_CONTACTS, OPSTR_WRITE_CONTACTS);
+ sPermToOp.put(Manifest.permission.READ_CALL_LOG, OPSTR_READ_CALL_LOG);
+ sPermToOp.put(Manifest.permission.WRITE_CALL_LOG, OPSTR_WRITE_CALL_LOG);
+ sPermToOp.put(Manifest.permission.READ_CALENDAR, OPSTR_READ_CALENDAR);
+ sPermToOp.put(Manifest.permission.WRITE_CALENDAR, OPSTR_WRITE_CALENDAR);
+ sPermToOp.put(Manifest.permission.CALL_PHONE, OPSTR_CALL_PHONE);
+ sPermToOp.put(Manifest.permission.READ_SMS, OPSTR_READ_SMS);
+ sPermToOp.put(Manifest.permission.RECEIVE_SMS, OPSTR_RECEIVE_SMS);
+ sPermToOp.put(Manifest.permission.RECEIVE_MMS, OPSTR_RECEIVE_MMS);
+ sPermToOp.put(Manifest.permission.RECEIVE_WAP_PUSH, OPSTR_RECEIVE_WAP_PUSH);
+ sPermToOp.put(Manifest.permission.SEND_SMS, OPSTR_SEND_SMS);
+ sPermToOp.put(Manifest.permission.SYSTEM_ALERT_WINDOW, OPSTR_SYSTEM_ALERT_WINDOW);
+ sPermToOp.put(Manifest.permission.CAMERA, OPSTR_CAMERA);
+ sPermToOp.put(Manifest.permission.RECORD_AUDIO, OPSTR_RECORD_AUDIO);
+ sPermToOp.put(Manifest.permission.READ_PHONE_STATE, OPSTR_READ_PHONE_STATE);
+ sPermToOp.put(Manifest.permission.ADD_VOICEMAIL, OPSTR_ADD_VOICEMAIL);
+ }
+
private static HashMap<String, Integer> sOpStrToOp = new HashMap<String, Integer>();
static {
@@ -1066,6 +1174,21 @@ public class AppOpsManager {
}
/**
+ * Gets the app op name associated with a given permission.
+ * The app op name is one of the public constants defined
+ * in this class such as {@link #OPSTR_COARSE_LOCATION}.
+ *
+ * @param permission The permission.
+ * @return The app op associated with the permission or null.
+ *
+ * @hide
+ */
+ @SystemApi
+ public static String permissionToOp(String permission) {
+ return sPermToOp.get(permission);
+ }
+
+ /**
* Monitor for changes to the operating mode for the given op in the given app package.
* @param op The operation to monitor, one of OPSTR_*.
* @param packageName The name of the application to monitor.
diff --git a/core/java/android/app/ApplicationPackageManager.java b/core/java/android/app/ApplicationPackageManager.java
index 16a2430..90293a4 100644
--- a/core/java/android/app/ApplicationPackageManager.java
+++ b/core/java/android/app/ApplicationPackageManager.java
@@ -62,6 +62,7 @@ import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
+import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
@@ -79,6 +80,7 @@ import android.view.Display;
import dalvik.system.VMRuntime;
import com.android.internal.annotations.GuardedBy;
+import com.android.internal.os.SomeArgs;
import com.android.internal.util.Preconditions;
import com.android.internal.util.UserIcons;
@@ -1560,13 +1562,7 @@ final class ApplicationPackageManager extends PackageManager {
public @Nullable VolumeInfo getPrimaryStorageCurrentVolume() {
final StorageManager storage = mContext.getSystemService(StorageManager.class);
final String volumeUuid = storage.getPrimaryStorageUuid();
- if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
- return storage.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
- } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
- return storage.getPrimaryPhysicalVolume();
- } else {
- return storage.findVolumeByUuid(volumeUuid);
- }
+ return storage.findVolumeByQualifiedUuid(volumeUuid);
}
@Override
@@ -2054,7 +2050,7 @@ final class ApplicationPackageManager extends PackageManager {
/** {@hide} */
private static class MoveCallbackDelegate extends IPackageMoveObserver.Stub implements
Handler.Callback {
- private static final int MSG_STARTED = 1;
+ private static final int MSG_CREATED = 1;
private static final int MSG_STATUS_CHANGED = 2;
final MoveCallback mCallback;
@@ -2067,26 +2063,38 @@ final class ApplicationPackageManager extends PackageManager {
@Override
public boolean handleMessage(Message msg) {
- final int moveId = msg.arg1;
switch (msg.what) {
- case MSG_STARTED:
- mCallback.onStarted(moveId, (String) msg.obj);
+ case MSG_CREATED: {
+ final SomeArgs args = (SomeArgs) msg.obj;
+ mCallback.onCreated(args.argi1, (Bundle) args.arg2);
+ args.recycle();
return true;
- case MSG_STATUS_CHANGED:
- mCallback.onStatusChanged(moveId, msg.arg2, (long) msg.obj);
+ }
+ case MSG_STATUS_CHANGED: {
+ final SomeArgs args = (SomeArgs) msg.obj;
+ mCallback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
+ args.recycle();
return true;
+ }
}
return false;
}
@Override
- public void onStarted(int moveId, String title) {
- mHandler.obtainMessage(MSG_STARTED, moveId, 0, title).sendToTarget();
+ public void onCreated(int moveId, Bundle extras) {
+ final SomeArgs args = SomeArgs.obtain();
+ args.argi1 = moveId;
+ args.arg2 = extras;
+ mHandler.obtainMessage(MSG_CREATED, args).sendToTarget();
}
@Override
public void onStatusChanged(int moveId, int status, long estMillis) {
- mHandler.obtainMessage(MSG_STATUS_CHANGED, moveId, status, estMillis).sendToTarget();
+ final SomeArgs args = SomeArgs.obtain();
+ args.argi1 = moveId;
+ args.argi2 = status;
+ args.arg3 = estMillis;
+ mHandler.obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
}
}
diff --git a/core/java/android/app/AssistStructure.java b/core/java/android/app/AssistStructure.java
index 9946d79..3abbb5b 100644
--- a/core/java/android/app/AssistStructure.java
+++ b/core/java/android/app/AssistStructure.java
@@ -224,6 +224,7 @@ final public class AssistStructure implements Parcelable {
static final int FLAGS_CHECKED = 0x00000200;
static final int FLAGS_CLICKABLE = 0x00004000;
static final int FLAGS_LONG_CLICKABLE = 0x00200000;
+ static final int FLAGS_STYLUS_BUTTON_PRESSABLE = 0x00400000;
int mFlags;
@@ -401,6 +402,10 @@ final public class AssistStructure implements Parcelable {
return (mFlags&ViewNode.FLAGS_LONG_CLICKABLE) != 0;
}
+ public boolean isStylusButtonPressable() {
+ return (mFlags&ViewNode.FLAGS_STYLUS_BUTTON_PRESSABLE) != 0;
+ }
+
public String getClassName() {
return mClassName;
}
@@ -513,6 +518,12 @@ final public class AssistStructure implements Parcelable {
}
@Override
+ public void setStylusButtonPressable(boolean state) {
+ mNode.mFlags = (mNode.mFlags&~ViewNode.FLAGS_STYLUS_BUTTON_PRESSABLE)
+ | (state ? ViewNode.FLAGS_STYLUS_BUTTON_PRESSABLE : 0);
+ }
+
+ @Override
public void setFocusable(boolean state) {
mNode.mFlags = (mNode.mFlags&~ViewNode.FLAGS_FOCUSABLE)
| (state ? ViewNode.FLAGS_FOCUSABLE : 0);
diff --git a/core/java/android/app/BackStackRecord.java b/core/java/android/app/BackStackRecord.java
index 8fb048b..49644a7 100644
--- a/core/java/android/app/BackStackRecord.java
+++ b/core/java/android/app/BackStackRecord.java
@@ -416,14 +416,14 @@ final class BackStackRecord extends FragmentTransaction implements
public CharSequence getBreadCrumbTitle() {
if (mBreadCrumbTitleRes != 0) {
- return mManager.mActivity.getText(mBreadCrumbTitleRes);
+ return mManager.mHost.getContext().getText(mBreadCrumbTitleRes);
}
return mBreadCrumbTitleText;
}
public CharSequence getBreadCrumbShortTitle() {
if (mBreadCrumbShortTitleRes != 0) {
- return mManager.mActivity.getText(mBreadCrumbShortTitleRes);
+ return mManager.mHost.getContext().getText(mBreadCrumbShortTitleRes);
}
return mBreadCrumbShortTitleText;
}
@@ -868,7 +868,7 @@ final class BackStackRecord extends FragmentTransaction implements
*/
private void calculateFragments(SparseArray<Fragment> firstOutFragments,
SparseArray<Fragment> lastInFragments) {
- if (!mManager.mContainer.hasView()) {
+ if (!mManager.mContainer.onHasView()) {
return; // nothing to see, so no transitions
}
Op op = mHead;
@@ -926,7 +926,7 @@ final class BackStackRecord extends FragmentTransaction implements
*/
public void calculateBackFragments(SparseArray<Fragment> firstOutFragments,
SparseArray<Fragment> lastInFragments) {
- if (!mManager.mContainer.hasView()) {
+ if (!mManager.mContainer.onHasView()) {
return; // nothing to see, so no transitions
}
Op op = mHead;
@@ -1002,7 +1002,7 @@ final class BackStackRecord extends FragmentTransaction implements
// Adding a non-existent target view makes sure that the transitions don't target
// any views by default. They'll only target the views we tell add. If we don't
// add any, then no views will be targeted.
- state.nonExistentView = new View(mManager.mActivity);
+ state.nonExistentView = new View(mManager.mHost.getContext());
// Go over all leaving fragments.
for (int i = 0; i < firstOutFragments.size(); i++) {
@@ -1275,7 +1275,7 @@ final class BackStackRecord extends FragmentTransaction implements
*/
private void configureTransitions(int containerId, TransitionState state, boolean isBack,
SparseArray<Fragment> firstOutFragments, SparseArray<Fragment> lastInFragments) {
- ViewGroup sceneRoot = (ViewGroup) mManager.mContainer.findViewById(containerId);
+ ViewGroup sceneRoot = (ViewGroup) mManager.mContainer.onFindViewById(containerId);
if (sceneRoot != null) {
Fragment inFragment = lastInFragments.get(containerId);
Fragment outFragment = firstOutFragments.get(containerId);
diff --git a/core/java/android/app/DialogFragment.java b/core/java/android/app/DialogFragment.java
index bde5a61..2fb8cc2 100644
--- a/core/java/android/app/DialogFragment.java
+++ b/core/java/android/app/DialogFragment.java
@@ -410,7 +410,7 @@ public class DialogFragment extends Fragment
return (LayoutInflater)mDialog.getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
- return (LayoutInflater)mActivity.getSystemService(
+ return (LayoutInflater) mHost.getContext().getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
}
diff --git a/core/java/android/app/Fragment.java b/core/java/android/app/Fragment.java
index 4fdae7f..91d810e 100644
--- a/core/java/android/app/Fragment.java
+++ b/core/java/android/app/Fragment.java
@@ -26,7 +26,6 @@ import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.content.res.TypedArray;
-import android.os.Build;
import android.os.Bundle;
import android.os.Parcel;
import android.os.Parcelable;
@@ -94,19 +93,20 @@ final class FragmentState implements Parcelable {
mSavedFragmentState = in.readBundle();
}
- public Fragment instantiate(Activity activity, Fragment parent) {
+ public Fragment instantiate(FragmentHostCallback host, Fragment parent) {
if (mInstance != null) {
return mInstance;
}
+ final Context context = host.getContext();
if (mArguments != null) {
- mArguments.setClassLoader(activity.getClassLoader());
+ mArguments.setClassLoader(context.getClassLoader());
}
- mInstance = Fragment.instantiate(activity, mClassName, mArguments);
+ mInstance = Fragment.instantiate(context, mClassName, mArguments);
if (mSavedFragmentState != null) {
- mSavedFragmentState.setClassLoader(activity.getClassLoader());
+ mSavedFragmentState.setClassLoader(context.getClassLoader());
mInstance.mSavedFragmentState = mSavedFragmentState;
}
mInstance.setIndex(mIndex, parent);
@@ -117,7 +117,7 @@ final class FragmentState implements Parcelable {
mInstance.mTag = mTag;
mInstance.mRetainInstance = mRetainInstance;
mInstance.mDetached = mDetached;
- mInstance.mFragmentManager = activity.mFragments;
+ mInstance.mFragmentManager = host.mFragmentManager;
if (FragmentManagerImpl.DEBUG) Log.v(FragmentManagerImpl.TAG,
"Instantiated fragment " + mInstance);
@@ -425,7 +425,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
FragmentManagerImpl mFragmentManager;
// Activity this fragment is attached to.
- Activity mActivity;
+ FragmentHostCallback mHost;
// Private fragment manager for child fragments inside of this one.
FragmentManagerImpl mChildFragmentManager;
@@ -775,20 +775,36 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
}
/**
+ * Return the {@link Context} this fragment is currently associated with.
+ */
+ public Context getContext() {
+ return mHost == null ? null : mHost.getContext();
+ }
+
+ /**
* Return the Activity this fragment is currently associated with.
*/
final public Activity getActivity() {
- return mActivity;
+ return mHost == null ? null : mHost.getActivity();
+ }
+
+ /**
+ * Return the host object of this fragment. May return {@code null} if the fragment
+ * isn't currently being hosted.
+ */
+ @Nullable
+ final public Object getHost() {
+ return mHost == null ? null : mHost.onGetHost();
}
/**
* Return <code>getActivity().getResources()</code>.
*/
final public Resources getResources() {
- if (mActivity == null) {
+ if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
- return mActivity.getResources();
+ return mHost.getContext().getResources();
}
/**
@@ -870,7 +886,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* Return true if the fragment is currently added to its activity.
*/
final public boolean isAdded() {
- return mActivity != null && mAdded;
+ return mHost != null && mAdded;
}
/**
@@ -1037,11 +1053,11 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
if (mLoaderManager != null) {
return mLoaderManager;
}
- if (mActivity == null) {
+ if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
mCheckedForLoaderManager = true;
- mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, true);
+ mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, true);
return mLoaderManager;
}
@@ -1065,15 +1081,15 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* Context.startActivity(Intent, Bundle)} for more details.
*/
public void startActivity(Intent intent, Bundle options) {
- if (mActivity == null) {
+ if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
if (options != null) {
- mActivity.startActivityFromFragment(this, intent, -1, options);
+ mHost.onStartActivityFromFragment(this, intent, -1, options);
} else {
// Note we want to go through this call for compatibility with
// applications that may have overridden the method.
- mActivity.startActivityFromFragment(this, intent, -1);
+ mHost.onStartActivityFromFragment(this, intent, -1, null /*options*/);
}
}
@@ -1090,10 +1106,10 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* containing Activity.
*/
public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
- if (mActivity == null) {
+ if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
- mActivity.startActivityFromFragment(this, intent, requestCode, options);
+ mHost.onStartActivityFromFragment(this, intent, requestCode, options);
}
/**
@@ -1181,11 +1197,12 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* @see android.content.Context#checkSelfPermission(String)
*/
public final void requestPermissions(@NonNull String[] permissions, int requestCode) {
- if (mActivity == null) {
+ if (mHost == null) {
throw new IllegalStateException("Fragment " + this + " not attached to Activity");
}
- Intent intent = mActivity.getPackageManager().buildRequestPermissionsIntent(permissions);
- mActivity.startActivityFromFragment(this, intent, requestCode, null);
+ Intent intent =
+ mHost.getContext().getPackageManager().buildRequestPermissionsIntent(permissions);
+ mHost.onStartActivityFromFragment(this, intent, requestCode, null);
}
/**
@@ -1211,19 +1228,16 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* inflation. Maybe this should become a public API. Note sure.
*/
public LayoutInflater getLayoutInflater(Bundle savedInstanceState) {
- // Newer platform versions use the child fragment manager's LayoutInflaterFactory.
- if (mActivity.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.LOLLIPOP) {
- LayoutInflater result = mActivity.getLayoutInflater().cloneInContext(mActivity);
+ final LayoutInflater result = mHost.onGetLayoutInflater();
+ if (mHost.onUseFragmentManagerInflaterFactory()) {
getChildFragmentManager(); // Init if needed; use raw implementation below.
result.setPrivateFactory(mChildFragmentManager.getLayoutInflaterFactory());
- return result;
- } else {
- return mActivity.getLayoutInflater();
}
+ return result;
}
/**
- * @deprecated Use {@link #onInflate(Activity, AttributeSet, Bundle)} instead.
+ * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
*/
@Deprecated
public void onInflate(AttributeSet attrs, Bundle savedInstanceState) {
@@ -1266,29 +1280,29 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
* {@sample development/samples/ApiDemos/src/com/example/android/apis/app/FragmentArguments.java
* create}
*
- * @param activity The Activity that is inflating this fragment.
+ * @param context The Context that is inflating this fragment.
* @param attrs The attributes at the tag where the fragment is
* being created.
* @param savedInstanceState If the fragment is being re-created from
* a previous saved state, this is the state.
*/
- public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
+ public void onInflate(Context context, AttributeSet attrs, Bundle savedInstanceState) {
onInflate(attrs, savedInstanceState);
mCalled = true;
- TypedArray a = activity.obtainStyledAttributes(attrs,
+ TypedArray a = context.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.Fragment);
- mEnterTransition = loadTransition(activity, a, mEnterTransition, null,
+ mEnterTransition = loadTransition(context, a, mEnterTransition, null,
com.android.internal.R.styleable.Fragment_fragmentEnterTransition);
- mReturnTransition = loadTransition(activity, a, mReturnTransition, USE_DEFAULT_TRANSITION,
+ mReturnTransition = loadTransition(context, a, mReturnTransition, USE_DEFAULT_TRANSITION,
com.android.internal.R.styleable.Fragment_fragmentReturnTransition);
- mExitTransition = loadTransition(activity, a, mExitTransition, null,
+ mExitTransition = loadTransition(context, a, mExitTransition, null,
com.android.internal.R.styleable.Fragment_fragmentExitTransition);
- mReenterTransition = loadTransition(activity, a, mReenterTransition, USE_DEFAULT_TRANSITION,
+ mReenterTransition = loadTransition(context, a, mReenterTransition, USE_DEFAULT_TRANSITION,
com.android.internal.R.styleable.Fragment_fragmentReenterTransition);
- mSharedElementEnterTransition = loadTransition(activity, a, mSharedElementEnterTransition,
+ mSharedElementEnterTransition = loadTransition(context, a, mSharedElementEnterTransition,
null, com.android.internal.R.styleable.Fragment_fragmentSharedElementEnterTransition);
- mSharedElementReturnTransition = loadTransition(activity, a, mSharedElementReturnTransition,
+ mSharedElementReturnTransition = loadTransition(context, a, mSharedElementReturnTransition,
USE_DEFAULT_TRANSITION,
com.android.internal.R.styleable.Fragment_fragmentSharedElementReturnTransition);
if (mAllowEnterTransitionOverlap == null) {
@@ -1303,9 +1317,30 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
}
/**
- * Called when a fragment is first attached to its activity.
+ * @deprecated Use {@link #onInflate(Context, AttributeSet, Bundle)} instead.
+ */
+ @Deprecated
+ public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
+ mCalled = true;
+ }
+
+ /**
+ * Called when a fragment is first attached to its context.
* {@link #onCreate(Bundle)} will be called after this.
*/
+ public void onAttach(Context context) {
+ mCalled = true;
+ final Activity hostActivity = mHost == null ? null : mHost.getActivity();
+ if (hostActivity != null) {
+ mCalled = false;
+ onAttach(hostActivity);
+ }
+ }
+
+ /**
+ * @deprecated Use {@link #onAttach(Context)} instead.
+ */
+ @Deprecated
public void onAttach(Activity activity) {
mCalled = true;
}
@@ -1428,7 +1463,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
mLoadersStarted = true;
if (!mCheckedForLoaderManager) {
mCheckedForLoaderManager = true;
- mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
+ mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
}
if (mLoaderManager != null) {
mLoaderManager.doStart();
@@ -1521,7 +1556,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
// + " mLoaderManager=" + mLoaderManager);
if (!mCheckedForLoaderManager) {
mCheckedForLoaderManager = true;
- mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
+ mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
}
if (mLoaderManager != null) {
mLoaderManager.doDestroy();
@@ -1546,7 +1581,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
mBackStackNesting = 0;
mFragmentManager = null;
mChildFragmentManager = null;
- mActivity = null;
+ mHost = null;
mFragmentId = 0;
mContainerId = 0;
mTag = null;
@@ -2034,9 +2069,9 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
writer.print(prefix); writer.print("mFragmentManager=");
writer.println(mFragmentManager);
}
- if (mActivity != null) {
- writer.print(prefix); writer.print("mActivity=");
- writer.println(mActivity);
+ if (mHost != null) {
+ writer.print(prefix); writer.print("mHost=");
+ writer.println(mHost);
}
if (mParentFragment != null) {
writer.print(prefix); writer.print("mParentFragment=");
@@ -2094,10 +2129,10 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
void instantiateChildFragmentManager() {
mChildFragmentManager = new FragmentManagerImpl();
- mChildFragmentManager.attachActivity(mActivity, new FragmentContainer() {
+ mChildFragmentManager.attachController(mHost, new FragmentContainer() {
@Override
@Nullable
- public View findViewById(int id) {
+ public View onFindViewById(int id) {
if (mView == null) {
throw new IllegalStateException("Fragment does not have a view");
}
@@ -2105,7 +2140,7 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
}
@Override
- public boolean hasView() {
+ public boolean onHasView() {
return (mView != null);
}
}, this);
@@ -2319,13 +2354,13 @@ public class Fragment implements ComponentCallbacks2, OnCreateContextMenuListene
mLoadersStarted = false;
if (!mCheckedForLoaderManager) {
mCheckedForLoaderManager = true;
- mLoaderManager = mActivity.getLoaderManager(mWho, mLoadersStarted, false);
+ mLoaderManager = mHost.getLoaderManager(mWho, mLoadersStarted, false);
}
if (mLoaderManager != null) {
- if (mActivity == null || !mActivity.mChangingConfigurations) {
- mLoaderManager.doStop();
- } else {
+ if (mRetaining) {
mLoaderManager.doRetain();
+ } else {
+ mLoaderManager.doStop();
}
}
}
diff --git a/core/java/android/app/FragmentContainer.java b/core/java/android/app/FragmentContainer.java
new file mode 100644
index 0000000..b2e0300
--- /dev/null
+++ b/core/java/android/app/FragmentContainer.java
@@ -0,0 +1,38 @@
+/*
+ * 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.app;
+
+import android.annotation.IdRes;
+import android.annotation.Nullable;
+import android.view.View;
+
+/**
+ * Callbacks to a {@link Fragment}'s container.
+ */
+public abstract class FragmentContainer {
+ /**
+ * Return the view with the given resource ID. May return {@code null} if the
+ * view is not a child of this container.
+ */
+ @Nullable
+ public abstract View onFindViewById(@IdRes int id);
+
+ /**
+ * Return {@code true} if the container holds any view.
+ */
+ public abstract boolean onHasView();
+}
diff --git a/core/java/android/app/FragmentController.java b/core/java/android/app/FragmentController.java
new file mode 100644
index 0000000..28dadfa
--- /dev/null
+++ b/core/java/android/app/FragmentController.java
@@ -0,0 +1,384 @@
+/*
+ * 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.app;
+
+import android.annotation.Nullable;
+import android.content.Context;
+import android.content.res.Configuration;
+import android.os.Bundle;
+import android.os.Parcelable;
+import android.util.ArrayMap;
+import android.util.AttributeSet;
+import android.view.Menu;
+import android.view.MenuInflater;
+import android.view.MenuItem;
+import android.view.View;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+import java.util.List;
+
+/**
+ * Provides integration points with a {@link FragmentManager} for a fragment host.
+ * <p>
+ * It is the responsibility of the host to take care of the Fragment's lifecycle.
+ * The methods provided by {@link FragmentController} are for that purpose.
+ */
+public class FragmentController {
+ private final FragmentHostCallback<?> mHost;
+
+ /**
+ * Returns a {@link FragmentController}.
+ */
+ public static final FragmentController createController(FragmentHostCallback<?> callbacks) {
+ return new FragmentController(callbacks);
+ }
+
+ private FragmentController(FragmentHostCallback<?> callbacks) {
+ mHost = callbacks;
+ }
+
+ /**
+ * Returns a {@link FragmentManager} for this controller.
+ */
+ public FragmentManager getFragmentManager() {
+ return mHost.getFragmentManagerImpl();
+ }
+
+ /**
+ * Returns a {@link LoaderManager}.
+ */
+ public LoaderManager getLoaderManager() {
+ return mHost.getLoaderManagerImpl();
+ }
+
+ /**
+ * Returns a fragment with the given identifier.
+ */
+ @Nullable
+ public Fragment findFragmentByWho(String who) {
+ return mHost.mFragmentManager.findFragmentByWho(who);
+ }
+
+ /**
+ * Attaches the host to the FragmentManager for this controller. The host must be
+ * attached before the FragmentManager can be used to manage Fragments.
+ * */
+ public void attachHost(Fragment parent) {
+ mHost.mFragmentManager.attachController(
+ mHost, mHost /*container*/, parent);
+ }
+
+ /**
+ * Instantiates a Fragment's view.
+ *
+ * @param parent The parent that the created view will be placed
+ * in; <em>note that this may be null</em>.
+ * @param name Tag name to be inflated.
+ * @param context The context the view is being created in.
+ * @param attrs Inflation attributes as specified in XML file.
+ *
+ * @return view the newly created view
+ */
+ public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
+ return mHost.mFragmentManager.onCreateView(parent, name, context, attrs);
+ }
+
+ /**
+ * Marks the fragment state as unsaved. This allows for "state loss" detection.
+ */
+ public void noteStateNotSaved() {
+ mHost.mFragmentManager.noteStateNotSaved();
+ }
+
+ /**
+ * Saves the state for all Fragments.
+ */
+ public Parcelable saveAllState() {
+ return mHost.mFragmentManager.saveAllState();
+ }
+
+ /**
+ * Restores the saved state for all Fragments. The given Fragment list are Fragment
+ * instances retained across configuration changes.
+ *
+ * @see #retainNonConfig()
+ */
+ public void restoreAllState(Parcelable state, List<Fragment> nonConfigList) {
+ mHost.mFragmentManager.restoreAllState(state, nonConfigList);
+ }
+
+ /**
+ * Returns a list of Fragments that have opted to retain their instance across
+ * configuration changes.
+ */
+ public List<Fragment> retainNonConfig() {
+ return mHost.mFragmentManager.retainNonConfig();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the create state.
+ * <p>Call when Fragments should be created.
+ *
+ * @see Fragment#onCreate(Bundle)
+ */
+ public void dispatchCreate() {
+ mHost.mFragmentManager.dispatchCreate();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the activity created state.
+ * <p>Call when Fragments should be informed their host has been created.
+ *
+ * @see Fragment#onActivityCreated(Bundle)
+ */
+ public void dispatchActivityCreated() {
+ mHost.mFragmentManager.dispatchActivityCreated();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the start state.
+ * <p>Call when Fragments should be started.
+ *
+ * @see Fragment#onStart()
+ */
+ public void dispatchStart() {
+ mHost.mFragmentManager.dispatchStart();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the resume state.
+ * <p>Call when Fragments should be resumed.
+ *
+ * @see Fragment#onResume()
+ */
+ public void dispatchResume() {
+ mHost.mFragmentManager.dispatchResume();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the pause state.
+ * <p>Call when Fragments should be paused.
+ *
+ * @see Fragment#onPause()
+ */
+ public void dispatchPause() {
+ mHost.mFragmentManager.dispatchPause();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the stop state.
+ * <p>Call when Fragments should be stopped.
+ *
+ * @see Fragment#onStop()
+ */
+ public void dispatchStop() {
+ mHost.mFragmentManager.dispatchStop();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the destroy view state.
+ * <p>Call when the Fragment's views should be destroyed.
+ *
+ * @see Fragment#onDestroyView()
+ */
+ public void dispatchDestroyView() {
+ mHost.mFragmentManager.dispatchDestroyView();
+ }
+
+ /**
+ * Moves all Fragments managed by the controller's FragmentManager
+ * into the destroy state.
+ * <p>Call when Fragments should be destroyed.
+ *
+ * @see Fragment#onDestroy()
+ */
+ public void dispatchDestroy() {
+ mHost.mFragmentManager.dispatchDestroy();
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know a configuration change occurred.
+ * <p>Call when there is a configuration change.
+ *
+ * @see Fragment#onConfigurationChanged(Configuration)
+ */
+ public void dispatchConfigurationChanged(Configuration newConfig) {
+ mHost.mFragmentManager.dispatchConfigurationChanged(newConfig);
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know the device is in a low memory condition.
+ * <p>Call when the device is low on memory and Fragment's should trim
+ * their memory usage.
+ *
+ * @see Fragment#onLowMemory()
+ */
+ public void dispatchLowMemory() {
+ mHost.mFragmentManager.dispatchLowMemory();
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know they should trim their memory usage.
+ * <p>Call when the Fragment can release allocated memory [such as if
+ * the Fragment is in the background].
+ *
+ * @see Fragment#onTrimMemory(int)
+ */
+ public void dispatchTrimMemory(int level) {
+ mHost.mFragmentManager.dispatchTrimMemory(level);
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know they should create an options menu.
+ * <p>Call when the Fragment should create an options menu.
+ *
+ * @return {@code true} if the options menu contains items to display
+ * @see Fragment#onCreateOptionsMenu(Menu, MenuInflater)
+ */
+ public boolean dispatchCreateOptionsMenu(Menu menu, MenuInflater inflater) {
+ return mHost.mFragmentManager.dispatchCreateOptionsMenu(menu, inflater);
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know they should prepare their options menu for display.
+ * <p>Call immediately before displaying the Fragment's options menu.
+ *
+ * @return {@code true} if the options menu contains items to display
+ * @see Fragment#onPrepareOptionsMenu(Menu)
+ */
+ public boolean dispatchPrepareOptionsMenu(Menu menu) {
+ return mHost.mFragmentManager.dispatchPrepareOptionsMenu(menu);
+ }
+
+ /**
+ * Sends an option item selection event to the Fragments managed by the
+ * controller's FragmentManager. Once the event has been consumed,
+ * no additional handling will be performed.
+ * <p>Call immediately after an options menu item has been selected
+ *
+ * @return {@code true} if the options menu selection event was consumed
+ * @see Fragment#onOptionsItemSelected(MenuItem)
+ */
+ public boolean dispatchOptionsItemSelected(MenuItem item) {
+ return mHost.mFragmentManager.dispatchOptionsItemSelected(item);
+ }
+
+ /**
+ * Sends a context item selection event to the Fragments managed by the
+ * controller's FragmentManager. Once the event has been consumed,
+ * no additional handling will be performed.
+ * <p>Call immediately after an options menu item has been selected
+ *
+ * @return {@code true} if the context menu selection event was consumed
+ * @see Fragment#onContextItemSelected(MenuItem)
+ */
+ public boolean dispatchContextItemSelected(MenuItem item) {
+ return mHost.mFragmentManager.dispatchContextItemSelected(item);
+ }
+
+ /**
+ * Lets all Fragments managed by the controller's FragmentManager
+ * know their options menu has closed.
+ * <p>Call immediately after closing the Fragment's options menu.
+ *
+ * @see Fragment#onOptionsMenuClosed(Menu)
+ */
+ public void dispatchOptionsMenuClosed(Menu menu) {
+ mHost.mFragmentManager.dispatchOptionsMenuClosed(menu);
+ }
+
+ /**
+ * Execute any pending actions for the Fragments managed by the
+ * controller's FragmentManager.
+ * <p>Call when queued actions can be performed [eg when the
+ * Fragment moves into a start or resume state].
+ * @return {@code true} if queued actions were performed
+ */
+ public boolean execPendingActions() {
+ return mHost.mFragmentManager.execPendingActions();
+ }
+
+ /**
+ * Starts the loaders.
+ */
+ public void doLoaderStart() {
+ mHost.doLoaderStart();
+ }
+
+ /**
+ * Stops the loaders, optionally retaining their state. This is useful for keeping the
+ * loader state across configuration changes.
+ *
+ * @param retain When {@code true}, the loaders aren't stopped, but, their instances
+ * are retained in a started state
+ */
+ public void doLoaderStop(boolean retain) {
+ mHost.doLoaderStop(retain);
+ }
+
+ /**
+ * Destroys the loaders and, if their state is not being retained, removes them.
+ */
+ public void doLoaderDestroy() {
+ mHost.doLoaderDestroy();
+ }
+
+ /**
+ * Lets the loaders know the host is ready to receive notifications.
+ */
+ public void reportLoaderStart() {
+ mHost.reportLoaderStart();
+ }
+
+ /**
+ * Returns a list of LoaderManagers that have opted to retain their instance across
+ * configuration changes.
+ */
+ public ArrayMap<String, LoaderManager> retainLoaderNonConfig() {
+ return mHost.retainLoaderNonConfig();
+ }
+
+ /**
+ * Restores the saved state for all LoaderManagers. The given LoaderManager list are
+ * LoaderManager instances retained across configuration changes.
+ *
+ * @see #retainLoaderNonConfig()
+ */
+ public void restoreLoaderNonConfig(ArrayMap<String, LoaderManager> loaderManagers) {
+ mHost.restoreLoaderNonConfig(loaderManagers);
+ }
+
+ /**
+ * Dumps the current state of the loaders.
+ */
+ public void dumpLoaders(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
+ mHost.dumpLoaders(prefix, fd, writer, args);
+ }
+}
diff --git a/core/java/android/app/FragmentHostCallback.java b/core/java/android/app/FragmentHostCallback.java
new file mode 100644
index 0000000..dad2c79
--- /dev/null
+++ b/core/java/android/app/FragmentHostCallback.java
@@ -0,0 +1,315 @@
+/*
+ * 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.app;
+
+import android.annotation.Nullable;
+import android.app.Activity;
+import android.content.Context;
+import android.content.Intent;
+import android.os.Bundle;
+import android.os.Handler;
+import android.util.ArrayMap;
+import android.util.AttributeSet;
+import android.view.LayoutInflater;
+import android.view.View;
+
+import java.io.FileDescriptor;
+import java.io.PrintWriter;
+
+/**
+ * Integration points with the Fragment host.
+ * <p>
+ * Fragments may be hosted by any object; such as an {@link Activity}. In order to
+ * host fragments, implement {@link FragmentHostCallback}, overriding the methods
+ * applicable to the host.
+ */
+public abstract class FragmentHostCallback<E> extends FragmentContainer {
+ private final Activity mActivity;
+ final Context mContext;
+ private final Handler mHandler;
+ final int mWindowAnimations;
+ final FragmentManagerImpl mFragmentManager = new FragmentManagerImpl();
+ private ArrayMap<String, LoaderManager> mAllLoaderManagers;
+ private LoaderManagerImpl mLoaderManager;
+ private boolean mCheckedForLoaderManager;
+ private boolean mLoadersStarted;
+
+ public FragmentHostCallback(Context context, Handler handler, int windowAnimations) {
+ this(null /*activity*/, context, handler, windowAnimations);
+ }
+
+ FragmentHostCallback(Activity activity) {
+ this(activity, activity /*context*/, activity.mHandler, 0 /*windowAnimations*/);
+ }
+
+ FragmentHostCallback(Activity activity, Context context, Handler handler,
+ int windowAnimations) {
+ mActivity = activity;
+ mContext = context;
+ mHandler = handler;
+ mWindowAnimations = windowAnimations;
+ }
+
+ /**
+ * Print internal state into the given stream.
+ *
+ * @param prefix Desired prefix to prepend at each line of output.
+ * @param fd The raw file descriptor that the dump is being sent to.
+ * @param writer The PrintWriter to which you should dump your state. This will be closed
+ * for you after you return.
+ * @param args additional arguments to the dump request.
+ */
+ public void onDump(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
+ }
+
+ /**
+ * Return {@code true} if the fragment's state needs to be saved.
+ */
+ public boolean onShouldSaveFragmentState(Fragment fragment) {
+ return true;
+ }
+
+ /**
+ * Return a {@link LayoutInflater}.
+ * See {@link Activity#getLayoutInflater()}.
+ */
+ public LayoutInflater onGetLayoutInflater() {
+ return (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
+ }
+
+ /**
+ * Return {@code true} if the FragmentManager's LayoutInflaterFactory should be used.
+ */
+ public boolean onUseFragmentManagerInflaterFactory() {
+ return false;
+ }
+
+ /**
+ * Return the object that's currently hosting the fragment. If a {@link Fragment}
+ * is hosted by a {@link Activity}, the object returned here should be the same
+ * object returned from {@link Fragment#getActivity()}.
+ */
+ @Nullable
+ public abstract E onGetHost();
+
+ /**
+ * Invalidates the activity's options menu.
+ * See {@link Activity#invalidateOptionsMenu()}
+ */
+ public void onInvalidateOptionsMenu() {
+ }
+
+ /**
+ * Starts a new {@link Activity} from the given fragment.
+ * See {@link Activity#startActivityForResult(Intent, int)}.
+ */
+ public void onStartActivityFromFragment(Fragment fragment, Intent intent, int requestCode,
+ Bundle options) {
+ if (requestCode != -1) {
+ throw new IllegalStateException(
+ "Starting activity with a requestCode requires a FragmentActivity host");
+ }
+ mContext.startActivity(intent);
+ }
+
+ /**
+ * Return {@code true} if there are window animations.
+ */
+ public boolean onHasWindowAnimations() {
+ return true;
+ }
+
+ /**
+ * Return the window animations.
+ */
+ public int onGetWindowAnimations() {
+ return mWindowAnimations;
+ }
+
+ @Nullable
+ @Override
+ public View onFindViewById(int id) {
+ return null;
+ }
+
+ @Override
+ public boolean onHasView() {
+ return true;
+ }
+
+ Activity getActivity() {
+ return mActivity;
+ }
+
+ Context getContext() {
+ return mContext;
+ }
+
+ Handler getHandler() {
+ return mHandler;
+ }
+
+ FragmentManagerImpl getFragmentManagerImpl() {
+ return mFragmentManager;
+ }
+
+ LoaderManagerImpl getLoaderManagerImpl() {
+ if (mLoaderManager != null) {
+ return mLoaderManager;
+ }
+ mCheckedForLoaderManager = true;
+ mLoaderManager = getLoaderManager("(root)", mLoadersStarted, true /*create*/);
+ return mLoaderManager;
+ }
+
+ void inactivateFragment(String who) {
+ //Log.v(TAG, "invalidateSupportFragment: who=" + who);
+ if (mAllLoaderManagers != null) {
+ LoaderManagerImpl lm = (LoaderManagerImpl) mAllLoaderManagers.get(who);
+ if (lm != null && !lm.mRetaining) {
+ lm.doDestroy();
+ mAllLoaderManagers.remove(who);
+ }
+ }
+ }
+
+ void onFragmentInflate(Fragment fragment, AttributeSet attrs, Bundle savedInstanceState) {
+ fragment.onInflate(mContext, attrs, savedInstanceState);
+ }
+
+ void onFragmentAttach(Fragment fragment) {
+ fragment.onAttach(mContext);
+ }
+
+ void doLoaderStart() {
+ if (mLoadersStarted) {
+ return;
+ }
+ mLoadersStarted = true;
+
+ if (mLoaderManager != null) {
+ mLoaderManager.doStart();
+ } else if (!mCheckedForLoaderManager) {
+ mLoaderManager = getLoaderManager("(root)", mLoadersStarted, false);
+ }
+ mCheckedForLoaderManager = true;
+ }
+
+ void doLoaderStop(boolean retain) {
+ if (mLoaderManager == null) {
+ return;
+ }
+
+ if (!mLoadersStarted) {
+ return;
+ }
+ mLoadersStarted = false;
+
+ if (retain) {
+ mLoaderManager.doRetain();
+ } else {
+ mLoaderManager.doStop();
+ }
+ }
+
+ void doLoaderRetain() {
+ if (mLoaderManager == null) {
+ return;
+ }
+ mLoaderManager.doRetain();
+ }
+
+ void doLoaderDestroy() {
+ if (mLoaderManager == null) {
+ return;
+ }
+ mLoaderManager.doDestroy();
+ }
+
+ void reportLoaderStart() {
+ if (mAllLoaderManagers != null) {
+ final int N = mAllLoaderManagers.size();
+ LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
+ for (int i=N-1; i>=0; i--) {
+ loaders[i] = (LoaderManagerImpl) mAllLoaderManagers.valueAt(i);
+ }
+ for (int i=0; i<N; i++) {
+ LoaderManagerImpl lm = loaders[i];
+ lm.finishRetain();
+ lm.doReportStart();
+ }
+ }
+ }
+
+ LoaderManagerImpl getLoaderManager(String who, boolean started, boolean create) {
+ if (mAllLoaderManagers == null) {
+ mAllLoaderManagers = new ArrayMap<String, LoaderManager>();
+ }
+ LoaderManagerImpl lm = (LoaderManagerImpl) mAllLoaderManagers.get(who);
+ if (lm == null) {
+ if (create) {
+ lm = new LoaderManagerImpl(who, this, started);
+ mAllLoaderManagers.put(who, lm);
+ }
+ } else {
+ lm.updateHostController(this);
+ }
+ return lm;
+ }
+
+ ArrayMap<String, LoaderManager> retainLoaderNonConfig() {
+ boolean retainLoaders = false;
+ if (mAllLoaderManagers != null) {
+ // prune out any loader managers that were already stopped and so
+ // have nothing useful to retain.
+ final int N = mAllLoaderManagers.size();
+ LoaderManagerImpl loaders[] = new LoaderManagerImpl[N];
+ for (int i=N-1; i>=0; i--) {
+ loaders[i] = (LoaderManagerImpl) mAllLoaderManagers.valueAt(i);
+ }
+ for (int i=0; i<N; i++) {
+ LoaderManagerImpl lm = loaders[i];
+ if (lm.mRetaining) {
+ retainLoaders = true;
+ } else {
+ lm.doDestroy();
+ mAllLoaderManagers.remove(lm.mWho);
+ }
+ }
+ }
+
+ if (retainLoaders) {
+ return mAllLoaderManagers;
+ }
+ return null;
+ }
+
+ void restoreLoaderNonConfig(ArrayMap<String, LoaderManager> loaderManagers) {
+ mAllLoaderManagers = loaderManagers;
+ }
+
+ void dumpLoaders(String prefix, FileDescriptor fd, PrintWriter writer, String[] args) {
+ writer.print(prefix); writer.print("mLoadersStarted=");
+ writer.println(mLoadersStarted);
+ if (mLoaderManager != null) {
+ writer.print(prefix); writer.print("Loader Manager ");
+ writer.print(Integer.toHexString(System.identityHashCode(mLoaderManager)));
+ writer.println(":");
+ mLoaderManager.dump(prefix + " ", fd, writer, args);
+ }
+ }
+}
diff --git a/core/java/android/app/FragmentManager.java b/core/java/android/app/FragmentManager.java
index 975b20d..62436e9 100644
--- a/core/java/android/app/FragmentManager.java
+++ b/core/java/android/app/FragmentManager.java
@@ -19,9 +19,7 @@ package android.app;
import android.animation.Animator;
import android.animation.AnimatorInflater;
import android.animation.AnimatorListenerAdapter;
-import android.annotation.Nullable;
import android.content.Context;
-import android.annotation.IdRes;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.os.Bundle;
@@ -48,6 +46,7 @@ import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.List;
/**
* Interface for interacting with {@link Fragment} objects inside of an
@@ -393,15 +392,6 @@ final class FragmentManagerState implements Parcelable {
}
/**
- * Callbacks from FragmentManagerImpl to its container.
- */
-interface FragmentContainer {
- @Nullable
- public View findViewById(@IdRes int id);
- public boolean hasView();
-}
-
-/**
* Container for fragments associated with an activity.
*/
final class FragmentManagerImpl extends FragmentManager implements LayoutInflater.Factory2 {
@@ -430,7 +420,8 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
ArrayList<OnBackStackChangedListener> mBackStackChangeListeners;
int mCurState = Fragment.INITIALIZING;
- Activity mActivity;
+ FragmentHostCallback<?> mHost;
+ FragmentController mController;
FragmentContainer mContainer;
Fragment mParent;
@@ -455,10 +446,10 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
Log.e(TAG, ex.getMessage());
LogWriter logw = new LogWriter(Log.ERROR, TAG);
PrintWriter pw = new FastPrintWriter(logw, false, 1024);
- if (mActivity != null) {
+ if (mHost != null) {
Log.e(TAG, "Activity state:");
try {
- mActivity.dump(" ", null, pw, new String[] { });
+ mHost.onDump(" ", null, pw, new String[] { });
} catch (Exception e) {
pw.flush();
Log.e(TAG, "Failed dumping state", e);
@@ -490,7 +481,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
public void popBackStack() {
enqueueAction(new Runnable() {
@Override public void run() {
- popBackStackState(mActivity.mHandler, null, -1, 0);
+ popBackStackState(mHost.getHandler(), null, -1, 0);
}
}, false);
}
@@ -499,14 +490,14 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
public boolean popBackStackImmediate() {
checkStateLoss();
executePendingTransactions();
- return popBackStackState(mActivity.mHandler, null, -1, 0);
+ return popBackStackState(mHost.getHandler(), null, -1, 0);
}
@Override
public void popBackStack(final String name, final int flags) {
enqueueAction(new Runnable() {
@Override public void run() {
- popBackStackState(mActivity.mHandler, name, -1, flags);
+ popBackStackState(mHost.getHandler(), name, -1, flags);
}
}, false);
}
@@ -515,7 +506,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
public boolean popBackStackImmediate(String name, int flags) {
checkStateLoss();
executePendingTransactions();
- return popBackStackState(mActivity.mHandler, name, -1, flags);
+ return popBackStackState(mHost.getHandler(), name, -1, flags);
}
@Override
@@ -525,7 +516,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
enqueueAction(new Runnable() {
@Override public void run() {
- popBackStackState(mActivity.mHandler, null, id, flags);
+ popBackStackState(mHost.getHandler(), null, id, flags);
}
}, false);
}
@@ -537,7 +528,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
if (id < 0) {
throw new IllegalArgumentException("Bad id: " + id);
}
- return popBackStackState(mActivity.mHandler, null, id, flags);
+ return popBackStackState(mHost.getHandler(), null, id, flags);
}
@Override
@@ -619,7 +610,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
if (mParent != null) {
DebugUtils.buildShortClassTag(mParent, sb);
} else {
- DebugUtils.buildShortClassTag(mActivity, sb);
+ DebugUtils.buildShortClassTag(mHost, sb);
}
sb.append("}}");
return sb.toString();
@@ -716,7 +707,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
writer.print(prefix); writer.println("FragmentManager misc state:");
- writer.print(prefix); writer.print(" mActivity="); writer.println(mActivity);
+ writer.print(prefix); writer.print(" mHost="); writer.println(mHost);
writer.print(prefix); writer.print(" mContainer="); writer.println(mContainer);
if (mParent != null) {
writer.print(prefix); writer.print(" mParent="); writer.println(mParent);
@@ -747,7 +738,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
if (fragment.mNextAnim != 0) {
- Animator anim = AnimatorInflater.loadAnimator(mActivity, fragment.mNextAnim);
+ Animator anim = AnimatorInflater.loadAnimator(mHost.getContext(), fragment.mNextAnim);
if (anim != null) {
return anim;
}
@@ -762,14 +753,14 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
return null;
}
- if (transitionStyle == 0 && mActivity.getWindow() != null) {
- transitionStyle = mActivity.getWindow().getAttributes().windowAnimations;
+ if (transitionStyle == 0 && mHost.onHasWindowAnimations()) {
+ transitionStyle = mHost.onGetWindowAnimations();
}
if (transitionStyle == 0) {
return null;
}
- TypedArray attrs = mActivity.obtainStyledAttributes(transitionStyle,
+ TypedArray attrs = mHost.getContext().obtainStyledAttributes(transitionStyle,
com.android.internal.R.styleable.FragmentAnimation);
int anim = attrs.getResourceId(styleIndex, 0);
attrs.recycle();
@@ -778,7 +769,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
return null;
}
- return AnimatorInflater.loadAnimator(mActivity, anim);
+ return AnimatorInflater.loadAnimator(mHost.getContext(), anim);
}
public void performPendingDeferredStart(Fragment f) {
@@ -848,18 +839,18 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
}
}
- f.mActivity = mActivity;
+ f.mHost = mHost;
f.mParentFragment = mParent;
f.mFragmentManager = mParent != null
- ? mParent.mChildFragmentManager : mActivity.mFragments;
+ ? mParent.mChildFragmentManager : mHost.getFragmentManagerImpl();
f.mCalled = false;
- f.onAttach(mActivity);
+ mHost.onFragmentAttach(f);
if (!f.mCalled) {
throw new SuperNotCalledException("Fragment " + f
+ " did not call through to super.onAttach()");
}
if (f.mParentFragment == null) {
- mActivity.onAttachFragment(f);
+ mHost.onFragmentAttach(f);
}
if (!f.mRetaining) {
@@ -884,7 +875,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
if (!f.mFromLayout) {
ViewGroup container = null;
if (f.mContainerId != 0) {
- container = (ViewGroup)mContainer.findViewById(f.mContainerId);
+ container = (ViewGroup)mContainer.onFindViewById(f.mContainerId);
if (container == null && !f.mRestored) {
throwException(new IllegalArgumentException(
"No view found for id 0x"
@@ -954,7 +945,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
if (f.mView != null) {
// Need to save the current view state if not
// done already.
- if (!mActivity.isFinishing() && f.mSavedViewState == null) {
+ if (!mHost.onShouldSaveFragmentState(f) && f.mSavedViewState == null) {
saveFragmentViewState(f);
}
}
@@ -1030,7 +1021,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
if (!f.mRetaining) {
makeInactive(f);
} else {
- f.mActivity = null;
+ f.mHost = null;
f.mParentFragment = null;
f.mFragmentManager = null;
f.mChildFragmentManager = null;
@@ -1053,7 +1044,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
void moveToState(int newState, int transit, int transitStyle, boolean always) {
- if (mActivity == null && newState != Fragment.INITIALIZING) {
+ if (mHost == null && newState != Fragment.INITIALIZING) {
throw new IllegalStateException("No activity");
}
@@ -1078,8 +1069,8 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
startPendingDeferredFragments();
}
- if (mNeedMenuInvalidate && mActivity != null && mCurState == Fragment.RESUMED) {
- mActivity.invalidateOptionsMenu();
+ if (mNeedMenuInvalidate && mHost != null && mCurState == Fragment.RESUMED) {
+ mHost.onInvalidateOptionsMenu();
mNeedMenuInvalidate = false;
}
}
@@ -1126,7 +1117,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
mAvailIndices = new ArrayList<Integer>();
}
mAvailIndices.add(f.mIndex);
- mActivity.invalidateFragment(f.mWho);
+ mHost.inactivateFragment(f.mWho);
f.initState();
}
@@ -1349,7 +1340,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
checkStateLoss();
}
synchronized (this) {
- if (mDestroyed || mActivity == null) {
+ if (mDestroyed || mHost == null) {
throw new IllegalStateException("Activity has been destroyed");
}
if (mPendingActions == null) {
@@ -1357,8 +1348,8 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
mPendingActions.add(action);
if (mPendingActions.size() == 1) {
- mActivity.mHandler.removeCallbacks(mExecCommit);
- mActivity.mHandler.post(mExecCommit);
+ mHost.getHandler().removeCallbacks(mExecCommit);
+ mHost.getHandler().post(mExecCommit);
}
}
}
@@ -1427,7 +1418,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
throw new IllegalStateException("Recursive entry to executePendingTransactions");
}
- if (Looper.myLooper() != mActivity.mHandler.getLooper()) {
+ if (Looper.myLooper() != mHost.getHandler().getLooper()) {
throw new IllegalStateException("Must be called from main thread of process");
}
@@ -1447,7 +1438,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
mPendingActions.toArray(mTmpActions);
mPendingActions.clear();
- mActivity.mHandler.removeCallbacks(mExecCommit);
+ mHost.getHandler().removeCallbacks(mExecCommit);
}
mExecutingActions = true;
@@ -1737,7 +1728,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
return fms;
}
- void restoreAllState(Parcelable state, ArrayList<Fragment> nonConfig) {
+ void restoreAllState(Parcelable state, List<Fragment> nonConfig) {
// If there is no saved state at all, then there can not be
// any nonConfig fragments either, so that is that.
if (state == null) return;
@@ -1758,7 +1749,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
f.mAdded = false;
f.mTarget = null;
if (fs.mSavedFragmentState != null) {
- fs.mSavedFragmentState.setClassLoader(mActivity.getClassLoader());
+ fs.mSavedFragmentState.setClassLoader(mHost.getContext().getClassLoader());
f.mSavedViewState = fs.mSavedFragmentState.getSparseParcelableArray(
FragmentManagerImpl.VIEW_STATE_TAG);
f.mSavedFragmentState = fs.mSavedFragmentState;
@@ -1775,7 +1766,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
for (int i=0; i<fms.mActive.length; i++) {
FragmentState fs = fms.mActive[i];
if (fs != null) {
- Fragment f = fs.instantiate(mActivity, mParent);
+ Fragment f = fs.instantiate(mHost, mParent);
if (DEBUG) Log.v(TAG, "restoreAllState: active #" + i + ": " + f);
mActive.add(f);
// Now that the fragment is instantiated (or came from being
@@ -1851,9 +1842,10 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
}
}
- public void attachActivity(Activity activity, FragmentContainer container, Fragment parent) {
- if (mActivity != null) throw new IllegalStateException("Already attached");
- mActivity = activity;
+ public void attachController(FragmentHostCallback<?> host, FragmentContainer container,
+ Fragment parent) {
+ if (mHost != null) throw new IllegalStateException("Already attached");
+ mHost = host;
mContainer = container;
mParent = parent;
}
@@ -1898,7 +1890,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
mDestroyed = true;
execPendingActions();
moveToState(Fragment.INITIALIZING, false);
- mActivity = null;
+ mHost = null;
mContainer = null;
mParent = null;
}
@@ -2024,8 +2016,8 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
@Override
public void invalidateOptionsMenu() {
- if (mActivity != null && mCurState == Fragment.RESUMED) {
- mActivity.invalidateOptionsMenu();
+ if (mHost != null && mCurState == Fragment.RESUMED) {
+ mHost.onInvalidateOptionsMenu();
} else {
mNeedMenuInvalidate = true;
}
@@ -2115,7 +2107,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
fragment.mTag = tag;
fragment.mInLayout = true;
fragment.mFragmentManager = this;
- fragment.onInflate(mActivity, attrs, fragment.mSavedFragmentState);
+ mHost.onFragmentInflate(fragment, attrs, fragment.mSavedFragmentState);
addFragment(fragment, true);
} else if (fragment.mInLayout) {
// A fragment already exists and it is not one we restored from
@@ -2132,7 +2124,7 @@ final class FragmentManagerImpl extends FragmentManager implements LayoutInflate
// from last saved state), then give it the attributes to
// initialize itself.
if (!fragment.mRetaining) {
- fragment.onInflate(mActivity, attrs, fragment.mSavedFragmentState);
+ mHost.onFragmentInflate(fragment, attrs, fragment.mSavedFragmentState);
}
}
diff --git a/core/java/android/app/KeyguardManager.java b/core/java/android/app/KeyguardManager.java
index ebb3c43..2c12317 100644
--- a/core/java/android/app/KeyguardManager.java
+++ b/core/java/android/app/KeyguardManager.java
@@ -199,9 +199,12 @@ public class KeyguardManager {
}
/**
- * Return whether the keyguard requires a password to unlock.
+ * Return whether the keyguard is secured by a PIN, pattern or password or a SIM card
+ * is currently locked.
*
- * @return true if keyguard is secure.
+ * <p>See also {@link #isDeviceSecure()} which ignores SIM locked states.
+ *
+ * @return true if a PIN, pattern or password is set or a SIM card is locked.
*/
public boolean isKeyguardSecure() {
try {
@@ -240,12 +243,8 @@ public class KeyguardManager {
}
/**
- * Returns whether the device is currently locked and requires a PIN, pattern or
- * password to unlock.
+ * Per-user version of {@link #isDeviceLocked()}.
*
- * @param userId the user for which the locked state should be reported.
- * @return true if unlocking the device currently requires a PIN, pattern or
- * password.
* @hide
*/
public boolean isDeviceLocked(int userId) {
@@ -260,6 +259,8 @@ public class KeyguardManager {
* Returns whether the device is secured with a PIN, pattern or
* password.
*
+ * <p>See also {@link #isKeyguardSecure} which treats SIM locked states as secure.
+ *
* @return true if a PIN, pattern or password was set.
*/
public boolean isDeviceSecure() {
@@ -267,11 +268,8 @@ public class KeyguardManager {
}
/**
- * Returns whether the device is secured with a PIN, pattern or
- * password.
+ * Per-user version of {@link #isDeviceSecure()}.
*
- * @param userId the user for which the secure state should be reported.
- * @return true if a PIN, pattern or password was set.
* @hide
*/
public boolean isDeviceSecure(int userId) {
diff --git a/core/java/android/app/LoaderManager.java b/core/java/android/app/LoaderManager.java
index b13b24a..f0e35c9 100644
--- a/core/java/android/app/LoaderManager.java
+++ b/core/java/android/app/LoaderManager.java
@@ -214,12 +214,12 @@ class LoaderManagerImpl extends LoaderManager {
final String mWho;
- Activity mActivity;
boolean mStarted;
boolean mRetaining;
boolean mRetainingStarted;
boolean mCreatingLoader;
+ private FragmentHostCallback mHost;
final class LoaderInfo implements Loader.OnLoadCompleteListener<Object>,
Loader.OnLoadCanceledListener<Object> {
@@ -356,15 +356,15 @@ class LoaderManagerImpl extends LoaderManager {
if (mCallbacks != null && mLoader != null && mHaveData && needReset) {
if (DEBUG) Log.v(TAG, " Reseting: " + this);
String lastBecause = null;
- if (mActivity != null) {
- lastBecause = mActivity.mFragments.mNoTransactionsBecause;
- mActivity.mFragments.mNoTransactionsBecause = "onLoaderReset";
+ if (mHost != null) {
+ lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
+ mHost.mFragmentManager.mNoTransactionsBecause = "onLoaderReset";
}
try {
mCallbacks.onLoaderReset(mLoader);
} finally {
- if (mActivity != null) {
- mActivity.mFragments.mNoTransactionsBecause = lastBecause;
+ if (mHost != null) {
+ mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
}
}
}
@@ -465,25 +465,25 @@ class LoaderManagerImpl extends LoaderManager {
mInactiveLoaders.remove(mId);
}
- if (mActivity != null && !hasRunningLoaders()) {
- mActivity.mFragments.startPendingDeferredFragments();
+ if (mHost != null && !hasRunningLoaders()) {
+ mHost.mFragmentManager.startPendingDeferredFragments();
}
}
void callOnLoadFinished(Loader<Object> loader, Object data) {
if (mCallbacks != null) {
String lastBecause = null;
- if (mActivity != null) {
- lastBecause = mActivity.mFragments.mNoTransactionsBecause;
- mActivity.mFragments.mNoTransactionsBecause = "onLoadFinished";
+ if (mHost != null) {
+ lastBecause = mHost.mFragmentManager.mNoTransactionsBecause;
+ mHost.mFragmentManager.mNoTransactionsBecause = "onLoadFinished";
}
try {
if (DEBUG) Log.v(TAG, " onLoadFinished in " + loader + ": "
+ loader.dataToString(data));
mCallbacks.onLoadFinished(loader, data);
} finally {
- if (mActivity != null) {
- mActivity.mFragments.mNoTransactionsBecause = lastBecause;
+ if (mHost != null) {
+ mHost.mFragmentManager.mNoTransactionsBecause = lastBecause;
}
}
mDeliveredData = true;
@@ -530,14 +530,14 @@ class LoaderManagerImpl extends LoaderManager {
}
}
- LoaderManagerImpl(String who, Activity activity, boolean started) {
+ LoaderManagerImpl(String who, FragmentHostCallback host, boolean started) {
mWho = who;
- mActivity = activity;
+ mHost = host;
mStarted = started;
}
- void updateActivity(Activity activity) {
- mActivity = activity;
+ void updateHostController(FragmentHostCallback host) {
+ mHost = host;
}
private LoaderInfo createLoader(int id, Bundle args,
@@ -730,8 +730,8 @@ class LoaderManagerImpl extends LoaderManager {
mInactiveLoaders.removeAt(idx);
info.destroy();
}
- if (mActivity != null && !hasRunningLoaders()) {
- mActivity.mFragments.startPendingDeferredFragments();
+ if (mHost != null && !hasRunningLoaders()) {
+ mHost.mFragmentManager.startPendingDeferredFragments();
}
}
@@ -849,7 +849,7 @@ class LoaderManagerImpl extends LoaderManager {
sb.append("LoaderManager{");
sb.append(Integer.toHexString(System.identityHashCode(this)));
sb.append(" in ");
- DebugUtils.buildShortClassTag(mActivity, sb);
+ DebugUtils.buildShortClassTag(mHost, sb);
sb.append("}}");
return sb.toString();
}
diff --git a/core/java/android/app/StatusBarManager.java b/core/java/android/app/StatusBarManager.java
index 207519c..31d1ab7 100644
--- a/core/java/android/app/StatusBarManager.java
+++ b/core/java/android/app/StatusBarManager.java
@@ -63,12 +63,20 @@ public class StatusBarManager {
| DISABLE_SYSTEM_INFO | DISABLE_RECENT | DISABLE_HOME | DISABLE_BACK | DISABLE_CLOCK
| DISABLE_SEARCH;
+ /**
+ * Flag to disable quick settings.
+ *
+ * Setting this flag disables quick settings completely, but does not disable expanding the
+ * notification shade.
+ */
+ public static final int DISABLE2_QUICK_SETTINGS = 0x00000001;
+
public static final int DISABLE2_NONE = 0x00000000;
- public static final int DISABLE2_MASK = 0x00000000;
+ public static final int DISABLE2_MASK = DISABLE2_QUICK_SETTINGS;
@IntDef(flag = true,
- value = {DISABLE2_NONE, DISABLE2_MASK})
+ value = {DISABLE2_NONE, DISABLE2_MASK, DISABLE2_QUICK_SETTINGS})
@Retention(RetentionPolicy.SOURCE)
public @interface Disable2Flags {}
diff --git a/core/java/android/app/admin/DevicePolicyManager.java b/core/java/android/app/admin/DevicePolicyManager.java
index ed814c3..9f71ea5 100644
--- a/core/java/android/app/admin/DevicePolicyManager.java
+++ b/core/java/android/app/admin/DevicePolicyManager.java
@@ -807,6 +807,24 @@ public class DevicePolicyManager {
public static final String ACTION_SYSTEM_UPDATE_POLICY_CHANGED
= "android.app.action.SYSTEM_UPDATE_POLICY_CHANGED";
+ /**
+ * Permission policy to prompt user for new permission requests for runtime permissions.
+ * Already granted or denied permissions are not affected by this.
+ */
+ public static final int PERMISSION_POLICY_PROMPT = 0;
+
+ /**
+ * Permission policy to always grant new permission requests for runtime permissions.
+ * Already granted or denied permissions are not affected by this.
+ */
+ public static final int PERMISSION_POLICY_AUTO_GRANT = 1;
+
+ /**
+ * Permission policy to always deny new permission requests for runtime permissions.
+ * Already granted or denied permissions are not affected by this.
+ */
+ public static final int PERMISSION_POLICY_AUTO_DENY = 2;
+
/**
* Return true if the given administrator component is currently
@@ -2908,7 +2926,7 @@ public class DevicePolicyManager {
* the user has already been set up.
*/
@SystemApi
- public boolean setActiveProfileOwner(ComponentName admin, String ownerName)
+ public boolean setActiveProfileOwner(ComponentName admin, @Deprecated String ownerName)
throws IllegalArgumentException {
if (mService != null) {
try {
@@ -2974,8 +2992,8 @@ 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, String ownerName, int userHandle)
- throws IllegalArgumentException {
+ public boolean setProfileOwner(ComponentName admin, @Deprecated String ownerName,
+ int userHandle) throws IllegalArgumentException {
if (admin == null) {
throw new NullPointerException("admin cannot be null");
}
@@ -4342,4 +4360,58 @@ public class DevicePolicyManager {
Log.w(TAG, "Failed talking with device policy service", re);
}
}
+
+ /**
+ * Called by profile or device owners to set the default response for future runtime permission
+ * requests by applications. The policy can allow for normal operation which prompts the
+ * user to grant a permission, or can allow automatic granting or denying of runtime
+ * permission requests by an application. This also applies to new permissions declared by app
+ * updates.
+ * @param admin Which profile or device owner this request is associated with.
+ * @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) {
+ try {
+ mService.setPermissionPolicy(admin, policy);
+ } catch (RemoteException re) {
+ Log.w(TAG, "Failed talking with device policy service", re);
+ }
+ }
+
+ /**
+ * Returns the current runtime permission policy set by the device or profile owner. The
+ * default is {@link #PERMISSION_POLICY_PROMPT}.
+ * @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) {
+ try {
+ return mService.getPermissionPolicy(admin);
+ } catch (RemoteException re) {
+ return PERMISSION_POLICY_PROMPT;
+ }
+ }
+
+ /**
+ * Grants or revokes a runtime permission to a specific application so that the user
+ * does not have to be prompted. This might affect all permissions in a group that the
+ * runtime permission belongs to. This method can only be called by a profile or device
+ * owner.
+ * @param admin Which profile or device owner this request is associated with.
+ * @param packageName The application to grant or revoke a permission to.
+ * @param permission The permission to grant or revoke.
+ * @param granted Whether or not to grant the permission. If false, all permissions in the
+ * associated permission group will be denied.
+ * @return whether the permission was successfully granted or revoked
+ */
+ public boolean setPermissionGranted(ComponentName admin, String packageName,
+ String permission, boolean granted) {
+ try {
+ return mService.setPermissionGranted(admin, packageName, permission, granted);
+ } catch (RemoteException re) {
+ Log.w(TAG, "Failed talking with device policy service", re);
+ return false;
+ }
+ }
}
diff --git a/core/java/android/app/admin/IDevicePolicyManager.aidl b/core/java/android/app/admin/IDevicePolicyManager.aidl
index a678c51..833bc00 100644
--- a/core/java/android/app/admin/IDevicePolicyManager.aidl
+++ b/core/java/android/app/admin/IDevicePolicyManager.aidl
@@ -229,4 +229,9 @@ interface IDevicePolicyManager {
boolean getDoNotAskCredentialsOnBoot();
void notifyPendingSystemUpdate(in long updateReceivedTime);
+
+ void setPermissionPolicy(in ComponentName admin, int policy);
+ int getPermissionPolicy(in ComponentName admin);
+ boolean setPermissionGranted(in ComponentName admin, String packageName, String permission,
+ boolean granted);
}
diff --git a/core/java/android/bluetooth/BluetoothAdapter.java b/core/java/android/bluetooth/BluetoothAdapter.java
index 3044a94..9b4dcc6 100644
--- a/core/java/android/bluetooth/BluetoothAdapter.java
+++ b/core/java/android/bluetooth/BluetoothAdapter.java
@@ -34,6 +34,7 @@ import android.os.RemoteException;
import android.os.ServiceManager;
import android.app.ActivityThread;
import android.os.SystemProperties;
+import android.provider.Settings;
import android.os.Binder;
import android.util.Log;
import android.util.Pair;
@@ -389,7 +390,7 @@ public final class BluetoothAdapter {
* @hide
*/
public static final String ACTION_BLE_STATE_CHANGED =
- "anrdoid.bluetooth.adapter.action.BLE_STATE_CHANGED";
+ "android.bluetooth.adapter.action.BLE_STATE_CHANGED";
/**
* Broadcast Action: The notifys Bluetooth ACL connected event. This will be
@@ -632,24 +633,6 @@ public final class BluetoothAdapter {
}
/**
- * Returns true if LE only mode is enabled, that is apps
- * have authorization to turn only BT ON and the calling
- * app has privilage to do so
- */
- private boolean isLEAlwaysOnEnabled() {
- boolean ret = false;
- if (SystemProperties.getBoolean("ro.bluetooth.blealwayson", true) == true) {
- Log.v(TAG, "LE always on mode is enabled");
- // TODO: System API authorization check
- ret = true;
- } else {
- Log.v(TAG, "LE always on mode is disabled");
- ret = false;
- }
- return ret;
- }
-
- /**
* Turns off Bluetooth LE which was earlier turned on by calling EnableBLE().
*
* <p> If the internal Adapter state is STATE_BLE_ON, this would trigger the transition
@@ -676,7 +659,7 @@ public final class BluetoothAdapter {
* @hide
*/
public boolean disableBLE() {
- if (isLEAlwaysOnEnabled() != true) return false;
+ if (!isBleScanAlwaysAvailable()) return false;
int state = getLeState();
if (state == BluetoothAdapter.STATE_ON) {
@@ -738,7 +721,7 @@ public final class BluetoothAdapter {
* @hide
*/
public boolean enableBLE() {
- if (isLEAlwaysOnEnabled() != true) return false;
+ if (!isBleScanAlwaysAvailable()) return false;
if (isLeEnabled() == true) {
if (DBG) Log.d(TAG, "enableBLE(): BT is already enabled..!");
@@ -1243,8 +1226,12 @@ public final class BluetoothAdapter {
*/
@SystemApi
public boolean isBleScanAlwaysAvailable() {
- // TODO: implement after Settings UI change.
- return false;
+ try {
+ return mManagerService.isBleScanAlwaysAvailable();
+ } catch (RemoteException e) {
+ Log.e(TAG, "remote expection when calling isBleScanAlwaysAvailable", e);
+ return false;
+ }
}
/**
diff --git a/core/java/android/bluetooth/IBluetoothManager.aidl b/core/java/android/bluetooth/IBluetoothManager.aidl
index 8d1ce99..0b81ee8 100644
--- a/core/java/android/bluetooth/IBluetoothManager.aidl
+++ b/core/java/android/bluetooth/IBluetoothManager.aidl
@@ -44,6 +44,8 @@ interface IBluetoothManager
String getAddress();
String getName();
+
+ boolean isBleScanAlwaysAvailable();
int updateBleAppCount(IBinder b, boolean enable);
boolean isBleAppPresent();
}
diff --git a/core/java/android/bluetooth/le/ScanSettings.java b/core/java/android/bluetooth/le/ScanSettings.java
index f103cae..dad486d 100644
--- a/core/java/android/bluetooth/le/ScanSettings.java
+++ b/core/java/android/bluetooth/le/ScanSettings.java
@@ -187,7 +187,7 @@ public final class ScanSettings implements Parcelable {
mScanResultType = scanResultType;
mReportDelayMillis = reportDelayMillis;
mNumOfMatchesPerFilter = numOfMatchesPerFilter;
- mMatchMode = numOfMatchesPerFilter;
+ mMatchMode = matchMode;
}
private ScanSettings(Parcel in) {
@@ -236,7 +236,7 @@ public final class ScanSettings implements Parcelable {
private int mScanResultType = SCAN_RESULT_TYPE_FULL;
private long mReportDelayMillis = 0;
private int mMatchMode = MATCH_MODE_AGGRESSIVE;
- private int mNumOfMatchesPerFilter = MATCH_NUM_ONE_ADVERTISEMENT;
+ private int mNumOfMatchesPerFilter = MATCH_NUM_MAX_ADVERTISEMENT;
/**
* Set scan mode for Bluetooth LE scan.
*
diff --git a/core/java/android/content/ContentProviderNative.java b/core/java/android/content/ContentProviderNative.java
index f2e7fc4..4769bd0 100644
--- a/core/java/android/content/ContentProviderNative.java
+++ b/core/java/android/content/ContentProviderNative.java
@@ -593,7 +593,8 @@ final class ContentProviderProxy implements IContentProvider
DatabaseUtils.readExceptionWithFileNotFoundExceptionFromParcel(reply);
int has = reply.readInt();
- ParcelFileDescriptor fd = has != 0 ? reply.readFileDescriptor() : null;
+ ParcelFileDescriptor fd = has != 0 ? ParcelFileDescriptor.CREATOR
+ .createFromParcel(reply) : null;
return fd;
} finally {
data.recycle();
diff --git a/core/java/android/content/Context.java b/core/java/android/content/Context.java
index 5eacce3..8687c6b 100644
--- a/core/java/android/content/Context.java
+++ b/core/java/android/content/Context.java
@@ -252,6 +252,21 @@ public abstract class Context {
public static final int BIND_ADJUST_WITH_ACTIVITY = 0x0080;
/**
+ * @hide Flag for {@link #bindService}: Like {@link #BIND_FOREGROUND_SERVICE},
+ * but only applies while the device is awake.
+ */
+ public static final int BIND_FOREGROUND_SERVICE_WHILE_AWAKE = 0x02000000;
+
+ /**
+ * @hide Flag for {@link #bindService}: For only the case where the binding
+ * is coming from the system, set the process state to FOREGROUND_SERVICE
+ * instead of the normal maximum of IMPORTANT_FOREGROUND. That is, this is
+ * saying that the process shouldn't participate in the normal power reduction
+ * modes (removing network access etc).
+ */
+ public static final int BIND_FOREGROUND_SERVICE = 0x04000000;
+
+ /**
* @hide Flag for {@link #bindService}: Treat the binding as hosting
* an activity, an unbinding as the activity going in the background.
* That is, when unbinding, the process when empty will go on the activity
@@ -374,24 +389,30 @@ public abstract class Context {
}
/**
- * Return a localized string from the application's package's
+ * Returns a localized string from the application's package's
* default string table.
*
* @param resId Resource id for the string
+ * @return The string data associated with the resource, stripped of styled
+ * text information.
*/
+ @NonNull
public final String getString(@StringRes int resId) {
return getResources().getString(resId);
}
/**
- * Return a localized formatted string from the application's package's
+ * Returns a localized formatted string from the application's package's
* default string table, substituting the format arguments as defined in
* {@link java.util.Formatter} and {@link java.lang.String#format}.
*
* @param resId Resource id for the format string
- * @param formatArgs The format arguments that will be used for substitution.
+ * @param formatArgs The format arguments that will be used for
+ * substitution.
+ * @return The string data associated with the resource, formatted and
+ * stripped of styled text information.
*/
-
+ @NonNull
public final String getString(@StringRes int resId, Object... formatArgs) {
return getResources().getString(resId, formatArgs);
}
diff --git a/core/java/android/content/pm/IPackageManager.aidl b/core/java/android/content/pm/IPackageManager.aidl
index ae59bfc..0b24594 100644
--- a/core/java/android/content/pm/IPackageManager.aidl
+++ b/core/java/android/content/pm/IPackageManager.aidl
@@ -58,6 +58,7 @@ import android.content.IntentSender;
* {@hide}
*/
interface IPackageManager {
+ boolean isPackageFrozen(String packageName);
boolean isPackageAvailable(String packageName, int userId);
PackageInfo getPackageInfo(String packageName, int flags, int userId);
int getPackageUid(String packageName, int userId);
diff --git a/core/java/android/content/pm/IPackageMoveObserver.aidl b/core/java/android/content/pm/IPackageMoveObserver.aidl
index 50ab3b5..86189fc 100644
--- a/core/java/android/content/pm/IPackageMoveObserver.aidl
+++ b/core/java/android/content/pm/IPackageMoveObserver.aidl
@@ -17,11 +17,13 @@
package android.content.pm;
+import android.os.Bundle;
+
/**
* Callback for moving package resources from the Package Manager.
* @hide
*/
oneway interface IPackageMoveObserver {
- void onStarted(int moveId, String title);
+ void onCreated(int moveId, in Bundle extras);
void onStatusChanged(int moveId, int status, long estMillis);
}
diff --git a/core/java/android/content/pm/PackageManager.java b/core/java/android/content/pm/PackageManager.java
index e1c271d..7ff6ec3 100644
--- a/core/java/android/content/pm/PackageManager.java
+++ b/core/java/android/content/pm/PackageManager.java
@@ -209,7 +209,14 @@ public abstract class PackageManager {
* matching. This is a synonym for including the CATEGORY_DEFAULT in your
* supplied Intent.
*/
- public static final int MATCH_DEFAULT_ONLY = 0x00010000;
+ public static final int MATCH_DEFAULT_ONLY = 0x00010000;
+
+ /**
+ * Querying flag: if set and if the platform is doing any filtering of the results, then
+ * the filtering will not happen. This is a synonym for saying that all results should
+ * be returned.
+ */
+ public static final int MATCH_ALL = 0x00020000;
/**
* Flag for {@link addCrossProfileIntentFilter}: if this flag is set:
@@ -2637,6 +2644,8 @@ public abstract class PackageManager {
* {@link #MATCH_DEFAULT_ONLY}, to limit the resolution to only
* those activities that support the {@link android.content.Intent#CATEGORY_DEFAULT}.
*
+ * You can also set {@link #MATCH_ALL} for preventing the filtering of the results.
+ *
* @return A List&lt;ResolveInfo&gt; containing one entry for each matching
* Activity. These are ordered from best to worst match -- that
* is, the first item in the list is what is returned by
@@ -2658,6 +2667,8 @@ public abstract class PackageManager {
* {@link #MATCH_DEFAULT_ONLY}, to limit the resolution to only
* those activities that support the {@link android.content.Intent#CATEGORY_DEFAULT}.
*
+ * You can also set {@link #MATCH_ALL} for preventing the filtering of the results.
+ *
* @return A List&lt;ResolveInfo&gt; containing one entry for each matching
* Activity. These are ordered from best to worst match -- that
* is, the first item in the list is what is returned by
@@ -4201,7 +4212,7 @@ public abstract class PackageManager {
/** {@hide} */
public static abstract class MoveCallback {
- public abstract void onStarted(int moveId, String title);
+ public void onCreated(int moveId, Bundle extras) {}
public abstract void onStatusChanged(int moveId, int status, long estMillis);
}
diff --git a/core/java/android/content/pm/PackageParser.java b/core/java/android/content/pm/PackageParser.java
index fed9261..9596c42 100644
--- a/core/java/android/content/pm/PackageParser.java
+++ b/core/java/android/content/pm/PackageParser.java
@@ -4315,9 +4315,6 @@ public class PackageParser {
// Additional data supplied by callers.
public Object mExtras;
- // Whether an operation is currently pending on this package
- public boolean mOperationPending;
-
// Applications hardware preferences
public ArrayList<ConfigurationInfo> configPreferences = null;
diff --git a/core/java/android/content/res/ColorStateList.java b/core/java/android/content/res/ColorStateList.java
index fdafb04..14bfac5 100644
--- a/core/java/android/content/res/ColorStateList.java
+++ b/core/java/android/content/res/ColorStateList.java
@@ -271,7 +271,7 @@ public class ColorStateList implements Parcelable {
final TypedArray a = Resources.obtainAttributes(r, theme, attrs,
R.styleable.ColorStateListItem);
final int[] themeAttrs = a.extractThemeAttrs();
- final int baseColor = a.getColor(R.styleable.ColorStateListItem_color, 0);
+ final int baseColor = a.getColor(R.styleable.ColorStateListItem_color, Color.MAGENTA);
final float alphaMod = a.getFloat(R.styleable.ColorStateListItem_alpha, 1.0f);
changingConfigurations |= a.getChangingConfigurations();
@@ -296,7 +296,9 @@ public class ColorStateList implements Parcelable {
}
stateSpec = StateSet.trimStateSet(stateSpec, j);
- // Apply alpha modulation.
+ // Apply alpha modulation. If we couldn't resolve the color or
+ // alpha yet, the default values leave us enough information to
+ // modulate again during applyTheme().
final int color = modulateColorAlpha(baseColor, alphaMod);
if (listSize == 0 || stateSpec.length == 0) {
defaultColor = color;
@@ -365,14 +367,31 @@ public class ColorStateList implements Parcelable {
if (themeAttrsList[i] != null) {
final TypedArray a = t.resolveAttributes(themeAttrsList[i],
R.styleable.ColorStateListItem);
+
+ final float defaultAlphaMod;
+ if (themeAttrsList[i][R.styleable.ColorStateListItem_color] != 0) {
+ // If the base color hasn't been resolved yet, the current
+ // color's alpha channel is either full-opacity (if we
+ // haven't resolved the alpha modulation yet) or
+ // pre-modulated. Either is okay as a default value.
+ defaultAlphaMod = Color.alpha(mColors[i]) / 255.0f;
+ } else {
+ // Otherwise, the only correct default value is 1. Even if
+ // nothing is resolved during this call, we can apply this
+ // multiple times without losing of information.
+ defaultAlphaMod = 1.0f;
+ }
+
final int baseColor = a.getColor(
R.styleable.ColorStateListItem_color, mColors[i]);
final float alphaMod = a.getFloat(
- R.styleable.ColorStateListItem_alpha, 1.0f);
-
+ R.styleable.ColorStateListItem_alpha, defaultAlphaMod);
mColors[i] = modulateColorAlpha(baseColor, alphaMod);
+
+ // 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;
diff --git a/core/java/android/content/res/Resources.java b/core/java/android/content/res/Resources.java
index 334d180..6e77e33 100644
--- a/core/java/android/content/res/Resources.java
+++ b/core/java/android/content/res/Resources.java
@@ -393,10 +393,11 @@ public class Resources {
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @return String The string data associated with the resource,
- * stripped of styled text information.
+ * stripped of styled text information.
*/
+ @NonNull
public String getString(@StringRes int id) throws NotFoundException {
- CharSequence res = getText(id);
+ final CharSequence res = getText(id);
if (res != null) {
return res.toString();
}
@@ -421,11 +422,11 @@ public class Resources {
* @throws NotFoundException Throws NotFoundException if the given ID does not exist.
*
* @return String The string data associated with the resource,
- * stripped of styled text information.
+ * stripped of styled text information.
*/
- public String getString(@StringRes int id, Object... formatArgs)
- throws NotFoundException {
- String raw = getString(id);
+ @NonNull
+ public String getString(@StringRes int id, Object... formatArgs) throws NotFoundException {
+ final String raw = getString(id);
return String.format(mConfiguration.locale, raw, formatArgs);
}
diff --git a/core/java/android/hardware/camera2/CameraCaptureSession.java b/core/java/android/hardware/camera2/CameraCaptureSession.java
index 0cf8df1..aeddf03 100644
--- a/core/java/android/hardware/camera2/CameraCaptureSession.java
+++ b/core/java/android/hardware/camera2/CameraCaptureSession.java
@@ -114,6 +114,11 @@ public abstract class CameraCaptureSession implements AutoCloseable {
* the Surface provided to prepare must not be used as a target of a CaptureRequest submitted
* to this session.</p>
*
+ * <p>{@link android.hardware.camera2.CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY LEGACY}
+ * devices cannot pre-allocate output buffers; for those devices,
+ * {@link StateCallback#onSurfacePrepared} will be immediately called, and no preallocation is
+ * done.</p>
+ *
* @param surface the output Surface for which buffers should be pre-allocated. Must be one of
* the output Surfaces used to create this session.
*
diff --git a/core/java/android/hardware/camera2/CameraCharacteristics.java b/core/java/android/hardware/camera2/CameraCharacteristics.java
index 87a1ca9..19e821c 100644
--- a/core/java/android/hardware/camera2/CameraCharacteristics.java
+++ b/core/java/android/hardware/camera2/CameraCharacteristics.java
@@ -603,10 +603,9 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>List of available high speed video size and fps range configurations
* supported by the camera device, in the format of (width, height, fps_min, fps_max).</p>
- * <p>When HIGH_SPEED_VIDEO is supported in {@link CameraCharacteristics#CONTROL_AVAILABLE_SCENE_MODES android.control.availableSceneModes},
- * this metadata will list the supported high speed video size and fps range
- * configurations. All the sizes listed in this configuration will be a subset
- * of the sizes reported by StreamConfigurationMap#getOutputSizes for processed
+ * <p>When HIGH_SPEED_VIDEO is supported in {@link CameraCharacteristics#CONTROL_AVAILABLE_SCENE_MODES android.control.availableSceneModes}, this metadata
+ * will list the supported high speed video size and fps range configurations. All the sizes
+ * listed in this configuration will be a subset of the sizes reported by {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputSizes } for processed
* non-stalling formats.</p>
* <p>For the high speed video use case, where the application will set
* {@link CaptureRequest#CONTROL_SCENE_MODE android.control.sceneMode} to HIGH_SPEED_VIDEO in capture requests, the application must
@@ -1116,11 +1115,12 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* into the 3 stream types as below:</p>
* <ul>
* <li>Processed (but stalling): any non-RAW format with a stallDurations &gt; 0.
- * Typically JPEG format (ImageFormat#JPEG).</li>
- * <li>Raw formats: ImageFormat#RAW_SENSOR, ImageFormat#RAW10, ImageFormat#RAW12,
- * and ImageFormat#RAW_OPAQUE.</li>
+ * Typically {@link android.graphics.ImageFormat#JPEG JPEG format}.</li>
+ * <li>Raw formats: {@link android.graphics.ImageFormat#RAW_SENSOR RAW_SENSOR}, {@link android.graphics.ImageFormat#RAW10 RAW10}, or {@link android.graphics.ImageFormat#RAW12 RAW12}.</li>
* <li>Processed (but not-stalling): any non-RAW format without a stall duration.
- * Typically ImageFormat#YUV_420_888, ImageFormat#NV21, ImageFormat#YV12.</li>
+ * Typically {@link android.graphics.ImageFormat#YUV_420_888 YUV_420_888},
+ * {@link android.graphics.ImageFormat#NV21 NV21}, or
+ * {@link android.graphics.ImageFormat#YV12 YV12}.</li>
* </ul>
* <p><b>Range of valid values:</b><br></p>
* <p>For processed (and stalling) format streams, &gt;= 1.</p>
@@ -1148,10 +1148,9 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* be any <code>RAW</code> and supported format provided by {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap}.</p>
* <p>In particular, a <code>RAW</code> format is typically one of:</p>
* <ul>
- * <li>ImageFormat#RAW_SENSOR</li>
- * <li>ImageFormat#RAW10</li>
- * <li>ImageFormat#RAW12</li>
- * <li>Opaque <code>RAW</code></li>
+ * <li>{@link android.graphics.ImageFormat#RAW_SENSOR RAW_SENSOR}</li>
+ * <li>{@link android.graphics.ImageFormat#RAW10 RAW10}</li>
+ * <li>{@link android.graphics.ImageFormat#RAW12 RAW12}</li>
* </ul>
* <p>LEGACY mode devices ({@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} <code>==</code> LEGACY)
* never support raw streams.</p>
@@ -1180,13 +1179,13 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>Processed (but not-stalling) is defined as any non-RAW format without a stall duration.
* Typically:</p>
* <ul>
- * <li>ImageFormat#YUV_420_888</li>
- * <li>ImageFormat#NV21</li>
- * <li>ImageFormat#YV12</li>
- * <li>Implementation-defined formats, i.e. StreamConfiguration#isOutputSupportedFor(Class)</li>
+ * <li>{@link android.graphics.ImageFormat#YUV_420_888 YUV_420_888}</li>
+ * <li>{@link android.graphics.ImageFormat#NV21 NV21}</li>
+ * <li>{@link android.graphics.ImageFormat#YV12 YV12}</li>
+ * <li>Implementation-defined formats, i.e. {@link android.hardware.camera2.params.StreamConfigurationMap#isOutputSupportedFor(Class) }</li>
* </ul>
- * <p>For full guarantees, query StreamConfigurationMap#getOutputStallDuration with
- * a processed format -- it will return 0 for a non-stalling stream.</p>
+ * <p>For full guarantees, query {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration } with a
+ * processed format -- it will return 0 for a non-stalling stream.</p>
* <p>LEGACY devices will support at least 2 processing/non-stalling streams.</p>
* <p><b>Range of valid values:</b><br></p>
* <p>&gt;= 3
@@ -1212,10 +1211,11 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* the camera device. Using more streams simultaneously may require more hardware and
* CPU resources that will consume more power. The image format for this kind of an output stream can
* be any non-<code>RAW</code> and supported format provided by {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap}.</p>
- * <p>A processed and stalling format is defined as any non-RAW format with a stallDurations &gt; 0.
- * Typically only the <code>JPEG</code> format (ImageFormat#JPEG) is a stalling format.</p>
- * <p>For full guarantees, query StreamConfigurationMap#getOutputStallDuration with
- * a processed format -- it will return a non-0 value for a stalling stream.</p>
+ * <p>A processed and stalling format is defined as any non-RAW format with a stallDurations
+ * &gt; 0. Typically only the {@link android.graphics.ImageFormat#JPEG JPEG format} is a
+ * stalling format.</p>
+ * <p>For full guarantees, query {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration } with a
+ * processed format -- it will return a non-0 value for a stalling stream.</p>
* <p>LEGACY devices will support up to 1 processing/stalling stream.</p>
* <p><b>Range of valid values:</b><br></p>
* <p>&gt;= 1</p>
@@ -1232,10 +1232,9 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>The maximum numbers of any type of input streams
* that can be configured and used simultaneously by a camera device.</p>
* <p>When set to 0, it means no input stream is supported.</p>
- * <p>The image format for a input stream can be any supported
- * format returned by StreamConfigurationMap#getInputFormats. When using an
- * input stream, there must be at least one output stream
- * configured to to receive the reprocessed images.</p>
+ * <p>The image format for a input stream can be any supported format returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputFormats }. When using an
+ * input stream, there must be at least one output stream configured to to receive the
+ * reprocessed images.</p>
* <p>When an input stream and some output streams are used in a reprocessing request,
* only the input buffer will be used to produce these output stream buffers, and a
* new sensor image will not be captured.</p>
@@ -1352,7 +1351,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>A list of all keys that the camera device has available
- * to use with CaptureRequest.</p>
+ * to use with {@link android.hardware.camera2.CaptureRequest }.</p>
* <p>Attempting to set a key into a CaptureRequest that is not
* listed here will result in an invalid request and will be rejected
* by the camera device.</p>
@@ -1370,7 +1369,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>A list of all keys that the camera device has available
- * to use with CaptureResult.</p>
+ * to use with {@link android.hardware.camera2.CaptureResult }.</p>
* <p>Attempting to get a key from a CaptureResult that is not
* listed here will always return a <code>null</code> value. Getting a key from
* a CaptureResult that is listed here will generally never return a <code>null</code>
@@ -1396,7 +1395,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>A list of all keys that the camera device has available
- * to use with CameraCharacteristics.</p>
+ * to use with {@link android.hardware.camera2.CameraCharacteristics }.</p>
* <p>This entry follows the same rules as
* android.request.availableResultKeys (except that it applies for
* CameraCharacteristics instead of CaptureResult). See above for more
@@ -1535,34 +1534,31 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* </thead>
* <tbody>
* <tr>
- * <td align="left">PRIVATE (ImageFormat#PRIVATE)</td>
- * <td align="left">JPEG</td>
+ * <td align="left">{@link android.graphics.ImageFormat#PRIVATE }</td>
+ * <td align="left">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="left">OPAQUE_REPROCESSING</td>
* </tr>
* <tr>
- * <td align="left">PRIVATE</td>
- * <td align="left">YUV_420_888</td>
+ * <td align="left">{@link android.graphics.ImageFormat#PRIVATE }</td>
+ * <td align="left">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
* <td align="left">OPAQUE_REPROCESSING</td>
* </tr>
* <tr>
- * <td align="left">YUV_420_888</td>
- * <td align="left">JPEG</td>
+ * <td align="left">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
+ * <td align="left">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="left">YUV_REPROCESSING</td>
* </tr>
* <tr>
- * <td align="left">YUV_420_888</td>
- * <td align="left">YUV_420_888</td>
+ * <td align="left">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
+ * <td align="left">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
* <td align="left">YUV_REPROCESSING</td>
* </tr>
* </tbody>
* </table>
- * <p>PRIVATE refers to a device-internal format that is not directly application-visible.
- * A PRIVATE input surface can be acquired by
- * ImageReader.newOpaqueInstance(width, height, maxImages).
- * For a OPAQUE_REPROCESSING-capable camera device, using the PRIVATE format
- * as either input or output will never hurt maximum frame rate (i.e.
- * StreamConfigurationMap#getOutputStallDuration(format, size) is always 0),
- * where format is ImageFormat#PRIVATE.</p>
+ * <p>PRIVATE refers to a device-internal format that is not directly application-visible. A
+ * PRIVATE input surface can be acquired by {@link android.media.ImageReader#newOpaqueInstance }.</p>
+ * <p>For a OPAQUE_REPROCESSING-capable camera device, using the PRIVATE format as either input
+ * or output will never hurt maximum frame rate (i.e. {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration getOutputStallDuration(ImageFormat.PRIVATE, size)} is always 0),</p>
* <p>Attempting to configure an input stream with output streams not
* listed as available in this map is not valid.</p>
* <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
@@ -1680,7 +1676,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* android.scaler.availableStallDurations for more details about
* calculating the max frame rate.</p>
* <p>(Keep in sync with
- * StreamConfigurationMap#getOutputMinFrameDuration)</p>
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration })</p>
* <p><b>Units</b>: (format, width, height, ns) x n</p>
* <p>This key is available on all devices.</p>
*
@@ -1692,7 +1688,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>This lists the maximum stall duration for each
- * format/size combination.</p>
+ * output format/size combination.</p>
* <p>A stall duration is how much extra time would get added
* to the normal minimum frame duration for a repeating request
* that has streams with non-zero stall.</p>
@@ -1734,12 +1730,13 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* ignored).</p>
* <p>The following formats may always have a stall duration:</p>
* <ul>
- * <li>ImageFormat#JPEG</li>
- * <li>ImageFormat#RAW_SENSOR</li>
+ * <li>{@link android.graphics.ImageFormat#JPEG }</li>
+ * <li>{@link android.graphics.ImageFormat#RAW_SENSOR }</li>
* </ul>
* <p>The following formats will never have a stall duration:</p>
* <ul>
- * <li>ImageFormat#YUV_420_888</li>
+ * <li>{@link android.graphics.ImageFormat#YUV_420_888 }</li>
+ * <li>{@link android.graphics.ImageFormat#RAW10 }</li>
* </ul>
* <p>All other formats may or may not have an allowed stall duration on
* a per-capability basis; refer to {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities}
@@ -1747,7 +1744,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>See {@link CaptureRequest#SENSOR_FRAME_DURATION android.sensor.frameDuration} for more information about
* calculating the max frame rate (absent stalls).</p>
* <p>(Keep up to date with
- * StreamConfigurationMap#getOutputStallDuration(int, Size) )</p>
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration } )</p>
* <p><b>Units</b>: (format, width, height, ns) x n</p>
* <p>This key is available on all devices.</p>
*
@@ -1786,57 +1783,57 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* </thead>
* <tbody>
* <tr>
- * <td align="center">JPEG</td>
+ * <td align="center">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="center">{@link CameraCharacteristics#SENSOR_INFO_ACTIVE_ARRAY_SIZE android.sensor.info.activeArraySize}</td>
* <td align="center">Any</td>
* <td align="center"></td>
* </tr>
* <tr>
- * <td align="center">JPEG</td>
+ * <td align="center">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="center">1920x1080 (1080p)</td>
* <td align="center">Any</td>
* <td align="center">if 1080p &lt;= activeArraySize</td>
* </tr>
* <tr>
- * <td align="center">JPEG</td>
+ * <td align="center">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="center">1280x720 (720)</td>
* <td align="center">Any</td>
* <td align="center">if 720p &lt;= activeArraySize</td>
* </tr>
* <tr>
- * <td align="center">JPEG</td>
+ * <td align="center">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="center">640x480 (480p)</td>
* <td align="center">Any</td>
* <td align="center">if 480p &lt;= activeArraySize</td>
* </tr>
* <tr>
- * <td align="center">JPEG</td>
+ * <td align="center">{@link android.graphics.ImageFormat#JPEG }</td>
* <td align="center">320x240 (240p)</td>
* <td align="center">Any</td>
* <td align="center">if 240p &lt;= activeArraySize</td>
* </tr>
* <tr>
- * <td align="center">YUV_420_888</td>
+ * <td align="center">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
* <td align="center">all output sizes available for JPEG</td>
* <td align="center">FULL</td>
* <td align="center"></td>
* </tr>
* <tr>
- * <td align="center">YUV_420_888</td>
+ * <td align="center">{@link android.graphics.ImageFormat#YUV_420_888 }</td>
* <td align="center">all output sizes available for JPEG, up to the maximum video size</td>
* <td align="center">LIMITED</td>
* <td align="center"></td>
* </tr>
* <tr>
- * <td align="center">IMPLEMENTATION_DEFINED</td>
+ * <td align="center">{@link android.graphics.ImageFormat#PRIVATE }</td>
* <td align="center">same as YUV_420_888</td>
* <td align="center">Any</td>
* <td align="center"></td>
* </tr>
* </tbody>
* </table>
- * <p>Refer to {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} for additional
- * mandatory stream configurations on a per-capability basis.</p>
+ * <p>Refer to {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} and {@link android.hardware.camera2.CameraDevice#createCaptureSession } for additional mandatory
+ * stream configurations on a per-capability basis.</p>
* <p>This key is available on all devices.</p>
*
* @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
@@ -1973,8 +1970,8 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>Attempting to use frame durations beyond the maximum will result in the frame
* duration being clipped to the maximum. See that control for a full definition of frame
* durations.</p>
- * <p>Refer to StreamConfigurationMap#getOutputMinFrameDuration(int,Size) for the minimum
- * frame duration values.</p>
+ * <p>Refer to {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }
+ * for the minimum frame duration values.</p>
* <p><b>Units</b>: Nanoseconds</p>
* <p><b>Range of valid values:</b><br>
* For FULL capability devices
@@ -2634,6 +2631,41 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
new Key<Integer>("android.sync.maxLatency", int.class);
/**
+ * <p>The maximal camera capture pipeline stall (in unit of frame count) introduced by a
+ * reprocess capture request.</p>
+ * <p>The key describes the maximal interference that one reprocess (input) request
+ * can introduce to the camera simultaneous streaming of regular (output) capture
+ * requests, including repeating requests.</p>
+ * <p>When a reprocessing capture request is submitted while a camera output repeating request
+ * (e.g. preview) is being served by the camera device, it may preempt the camera capture
+ * pipeline for at least one frame duration so that the camera device is unable to process
+ * the following capture request in time for the next sensor start of exposure boundary.
+ * When this happens, the application may observe a capture time gap (longer than one frame
+ * duration) between adjacent capture output frames, which usually exhibits as preview
+ * glitch if the repeating request output targets include a preview surface. This key gives
+ * the worst-case number of frame stall introduced by one reprocess request with any kind of
+ * formats/sizes combination.</p>
+ * <p>If this key reports 0, it means a reprocess request doesn't introduce any glitch to the
+ * ongoing camera repeating request outputs, as if this reprocess request is never issued.</p>
+ * <p>This key is supported if the camera device supports OPAQUE or YUV reprocessing (
+ * i.e. {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} contains OPAQUE_REPROCESSING or
+ * YUV_REPROCESSING).</p>
+ * <p><b>Units</b>: Number of frames.</p>
+ * <p><b>Range of valid values:</b><br>
+ * &lt;= 4</p>
+ * <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
+ *
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
+ * @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
+ */
+ @PublicKey
+ public static final Key<Integer> REPROCESS_MAX_CAPTURE_STALL =
+ new Key<Integer>("android.reprocess.maxCaptureStall", int.class);
+
+ /**
* <p>The available depth dataspace stream
* configurations that this camera device supports
* (i.e. format, width, height, output/input stream).</p>
@@ -2672,8 +2704,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
* <p>See {@link CaptureRequest#SENSOR_FRAME_DURATION android.sensor.frameDuration} and
* android.scaler.availableStallDurations for more details about
* calculating the max frame rate.</p>
- * <p>(Keep in sync with
- * StreamConfigurationMap#getOutputMinFrameDuration)</p>
+ * <p>(Keep in sync with {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration })</p>
* <p><b>Units</b>: (format, width, height, ns) x n</p>
* <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
* <p><b>Limited capability</b> -
@@ -2689,7 +2720,7 @@ public final class CameraCharacteristics extends CameraMetadata<CameraCharacteri
/**
* <p>This lists the maximum stall duration for each
- * format/size combination for depth streams.</p>
+ * output format/size combination for depth streams.</p>
* <p>A stall duration is how much extra time would get added
* to the normal minimum frame duration for a repeating request
* that has streams with non-zero stall.</p>
diff --git a/core/java/android/hardware/camera2/CameraDevice.java b/core/java/android/hardware/camera2/CameraDevice.java
index 51b326b..f6791a4 100644
--- a/core/java/android/hardware/camera2/CameraDevice.java
+++ b/core/java/android/hardware/camera2/CameraDevice.java
@@ -54,6 +54,7 @@ public abstract class CameraDevice implements AutoCloseable {
* means that high frame rate is given priority over the highest-quality
* post-processing. These requests would normally be used with the
* {@link CameraCaptureSession#setRepeatingRequest} method.
+ * This template is guaranteed to be supported on all camera devices.
*
* @see #createCaptureRequest
*/
@@ -63,6 +64,7 @@ public abstract class CameraDevice implements AutoCloseable {
* Create a request suitable for still image capture. Specifically, this
* means prioritizing image quality over frame rate. These requests would
* commonly be used with the {@link CameraCaptureSession#capture} method.
+ * This template is guaranteed to be supported on all camera devices.
*
* @see #createCaptureRequest
*/
@@ -73,6 +75,7 @@ public abstract class CameraDevice implements AutoCloseable {
* that a stable frame rate is used, and post-processing is set for
* recording quality. These requests would commonly be used with the
* {@link CameraCaptureSession#setRepeatingRequest} method.
+ * This template is guaranteed to be supported on all camera devices.
*
* @see #createCaptureRequest
*/
@@ -84,6 +87,9 @@ public abstract class CameraDevice implements AutoCloseable {
* disrupting the ongoing recording. These requests would commonly be used
* with the {@link CameraCaptureSession#capture} method while a request based on
* {@link #TEMPLATE_RECORD} is is in use with {@link CameraCaptureSession#setRepeatingRequest}.
+ * This template is guaranteed to be supported on all camera devices except
+ * legacy devices ({@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL}
+ * {@code == }{@link CameraMetadata#INFO_SUPPORTED_HARDWARE_LEVEL_LEGACY LEGACY})
*
* @see #createCaptureRequest
*/
@@ -93,6 +99,11 @@ public abstract class CameraDevice implements AutoCloseable {
* Create a request suitable for zero shutter lag still capture. This means
* means maximizing image quality without compromising preview frame rate.
* AE/AWB/AF should be on auto mode.
+ * This template is guaranteed to be supported on camera devices that support the
+ * {@link CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_OPAQUE_REPROCESSING OPAQUE_REPROCESSING}
+ * capability or the
+ * {@link CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_YUV_REPROCESSING YUV_REPROCESSING}
+ * capability.
*
* @see #createCaptureRequest
*/
@@ -105,6 +116,9 @@ public abstract class CameraDevice implements AutoCloseable {
* quality. The manual capture parameters (exposure, sensitivity, and so on)
* are set to reasonable defaults, but should be overriden by the
* application depending on the intended use case.
+ * This template is guaranteed to be supported on camera devices that support the
+ * {@link CameraMetadata#REQUEST_AVAILABLE_CAPABILITIES_MANUAL_SENSOR MANUAL_SENSOR}
+ * capability.
*
* @see #createCaptureRequest
*/
@@ -473,12 +487,14 @@ public abstract class CameraDevice implements AutoCloseable {
* settings as desired, instead.</p>
*
* @param templateType An enumeration selecting the use case for this
- * request; one of the CameraDevice.TEMPLATE_ values.
+ * request; one of the CameraDevice.TEMPLATE_ values. Not all template
+ * types are supported on every device. See the documentation for each
+ * template type for details.
* @return a builder for a capture request, initialized with default
* settings for that template, and no output streams
*
- * @throws IllegalArgumentException if the templateType is not in the list
- * of supported templates.
+ * @throws IllegalArgumentException if the templateType is not supported by
+ * this device.
* @throws CameraAccessException if the camera device is no longer connected or has
* encountered a fatal error
* @throws IllegalStateException if the camera device has been closed
diff --git a/core/java/android/hardware/camera2/CameraMetadata.java b/core/java/android/hardware/camera2/CameraMetadata.java
index e3f1d73..ca9439b 100644
--- a/core/java/android/hardware/camera2/CameraMetadata.java
+++ b/core/java/android/hardware/camera2/CameraMetadata.java
@@ -461,22 +461,21 @@ public abstract class CameraMetadata<TKey> {
* <p>The camera device supports the Zero Shutter Lag reprocessing use case.</p>
* <ul>
* <li>One input stream is supported, that is, <code>{@link CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS android.request.maxNumInputStreams} == 1</code>.</li>
- * <li>ImageFormat#PRIVATE is supported as an output/input format, that is,
- * ImageFormat#PRIVATE is included in the lists of formats returned by
- * StreamConfigurationMap#getInputFormats and
- * StreamConfigurationMap#getOutputFormats.</li>
- * <li>StreamConfigurationMap#getValidOutputFormatsForInput returns non empty int[] for
- * each supported input format returned by StreamConfigurationMap#getInputFormats.</li>
- * <li>Each size returned by StreamConfigurationMap#getInputSizes(ImageFormat#PRIVATE)
- * is also included in StreamConfigurationMap#getOutputSizes(ImageFormat#PRIVATE)</li>
- * <li>Using ImageFormat#PRIVATE does not cause a frame rate drop
- * relative to the sensor's maximum capture rate (at that
- * resolution).</li>
- * <li>ImageFormat#PRIVATE will be reprocessable into both YUV_420_888
- * and JPEG formats.</li>
+ * <li>{@link android.graphics.ImageFormat#PRIVATE } is supported as an output/input format,
+ * that is, {@link android.graphics.ImageFormat#PRIVATE } is included in the lists of
+ * formats returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputFormats } and {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputFormats }.</li>
+ * <li>{@link android.hardware.camera2.params.StreamConfigurationMap#getValidOutputFormatsForInput }
+ * returns non empty int[] for each supported input format returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputFormats }.</li>
+ * <li>Each size returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputSizes getInputSizes(ImageFormat.PRIVATE)} is also included in {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputSizes getOutputSizes(ImageFormat.PRIVATE)}</li>
+ * <li>Using {@link android.graphics.ImageFormat#PRIVATE } does not cause a frame rate drop
+ * relative to the sensor's maximum capture rate (at that resolution).</li>
+ * <li>{@link android.graphics.ImageFormat#PRIVATE } will be reprocessable into both
+ * {@link android.graphics.ImageFormat#YUV_420_888 } and
+ * {@link android.graphics.ImageFormat#JPEG } formats.</li>
* <li>The maximum available resolution for OPAQUE streams
* (both input/output) will match the maximum available
* resolution of JPEG streams.</li>
+ * <li>Static metadata {@link CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL android.reprocess.maxCaptureStall}.</li>
* <li>Only below controls are effective for reprocessing requests and
* will be present in capture results, other controls in reprocess
* requests will be ignored by the camera device.<ul>
@@ -489,6 +488,7 @@ public abstract class CameraMetadata<TKey> {
*
* @see CaptureRequest#EDGE_MODE
* @see CaptureRequest#NOISE_REDUCTION_MODE
+ * @see CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL
* @see CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS
* @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
*/
@@ -569,25 +569,25 @@ public abstract class CameraMetadata<TKey> {
* following:</p>
* <ul>
* <li>One input stream is supported, that is, <code>{@link CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS android.request.maxNumInputStreams} == 1</code>.</li>
- * <li>YUV_420_888 is supported as an output/input format, that is,
+ * <li>{@link android.graphics.ImageFormat#YUV_420_888 } is supported as an output/input format, that is,
* YUV_420_888 is included in the lists of formats returned by
- * StreamConfigurationMap#getInputFormats and
- * StreamConfigurationMap#getOutputFormats.</li>
- * <li>StreamConfigurationMap#getValidOutputFormatsForInput returns non empty int[] for
- * each supported input format returned by StreamConfigurationMap#getInputFormats.</li>
- * <li>Each size returned by StreamConfigurationMap#getInputSizes(YUV_420_888)
- * is also included in StreamConfigurationMap#getOutputSizes(YUV_420_888)</li>
- * <li>Using YUV_420_888 does not cause a frame rate drop
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getInputFormats } and
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputFormats }.</li>
+ * <li>{@link android.hardware.camera2.params.StreamConfigurationMap#getValidOutputFormatsForInput }
+ * returns non-empty int[] for each supported input format returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputFormats }.</li>
+ * <li>Each size returned by {@link android.hardware.camera2.params.StreamConfigurationMap#getInputSizes getInputSizes(YUV_420_888)} is also included in {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputSizes getOutputSizes(YUV_420_888)}</li>
+ * <li>Using {@link android.graphics.ImageFormat#YUV_420_888 } does not cause a frame rate drop
* relative to the sensor's maximum capture rate (at that resolution).</li>
- * <li>YUV_420_888 will be reprocessable into both YUV_420_888
- * and JPEG formats.</li>
- * <li>The maximum available resolution for YUV_420_888 streams
- * (both input/output) will match the maximum available
- * resolution of JPEG streams.</li>
- * <li>Only the below controls are effective for reprocessing requests and will be
- * present in capture results. The reprocess requests are from the original capture
- * results that are assocaited with the intermidate YUV_420_888 output buffers.
- * All other controls in the reprocess requests will be ignored by the camera device.<ul>
+ * <li>{@link android.graphics.ImageFormat#YUV_420_888 } will be reprocessable into both
+ * {@link android.graphics.ImageFormat#YUV_420_888 } and {@link android.graphics.ImageFormat#JPEG } formats.</li>
+ * <li>The maximum available resolution for {@link android.graphics.ImageFormat#YUV_420_888 } streams (both input/output) will match the
+ * maximum available resolution of {@link android.graphics.ImageFormat#JPEG } streams.</li>
+ * <li>Static metadata {@link CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL android.reprocess.maxCaptureStall}.</li>
+ * <li>Only the below controls are effective for reprocessing requests and will be present
+ * in capture results. The reprocess requests are from the original capture results that
+ * are associated with the intermediate {@link android.graphics.ImageFormat#YUV_420_888 }
+ * output buffers. All other controls in the reprocess requests will be ignored by the
+ * camera device.<ul>
* <li>android.jpeg.*</li>
* <li>{@link CaptureRequest#NOISE_REDUCTION_MODE android.noiseReduction.mode}</li>
* <li>{@link CaptureRequest#EDGE_MODE android.edge.mode}</li>
@@ -599,6 +599,7 @@ public abstract class CameraMetadata<TKey> {
* @see CaptureRequest#EDGE_MODE
* @see CaptureRequest#NOISE_REDUCTION_MODE
* @see CaptureRequest#REPROCESS_EFFECTIVE_EXPOSURE_FACTOR
+ * @see CameraCharacteristics#REPROCESS_MAX_CAPTURE_STALL
* @see CameraCharacteristics#REQUEST_MAX_NUM_INPUT_STREAMS
* @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
*/
@@ -608,11 +609,13 @@ public abstract class CameraMetadata<TKey> {
* <p>The camera device can produce depth measurements from its field of view.</p>
* <p>This capability requires the camera device to support the following:</p>
* <ul>
- * <li>DEPTH16 is supported as an output format.</li>
- * <li>DEPTH_POINT_CLOUD is optionally supported as an output format.</li>
- * <li>This camera device, and all camera devices with the same android.lens.info.facing,
- * will list the following calibration entries in both CameraCharacteristics and
- * CaptureResults:<ul>
+ * <li>{@link android.graphics.ImageFormat#DEPTH16 } is supported as an output format.</li>
+ * <li>{@link android.graphics.ImageFormat#DEPTH_POINT_CLOUD } is optionally supported as an
+ * output format.</li>
+ * <li>This camera device, and all camera devices with the same {@link CameraCharacteristics#LENS_FACING android.lens.facing},
+ * will list the following calibration entries in both
+ * {@link android.hardware.camera2.CameraCharacteristics } and
+ * {@link android.hardware.camera2.CaptureResult }:<ul>
* <li>{@link CameraCharacteristics#LENS_POSE_TRANSLATION android.lens.poseTranslation}</li>
* <li>{@link CameraCharacteristics#LENS_POSE_ROTATION android.lens.poseRotation}</li>
* <li>android.lens.intrinsicCalibration</li>
@@ -627,13 +630,14 @@ public abstract class CameraMetadata<TKey> {
* <p>Generally, depth output operates at a slower frame rate than standard color capture,
* so the DEPTH16 and DEPTH_POINT_CLOUD formats will commonly have a stall duration that
* should be accounted for (see
- * android.hardware.camera2.StreamConfigurationMap#getOutputStallDuration). On a device
- * that supports both depth and color-based output, to enable smooth preview, using a
- * repeating burst is recommended, where a depth-output target is only included once
- * every N frames, where N is the ratio between preview output rate and depth output
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration }).
+ * On a device that supports both depth and color-based output, to enable smooth preview,
+ * using a repeating burst is recommended, where a depth-output target is only included
+ * once every N frames, where N is the ratio between preview output rate and depth output
* rate, including depth stall time.</p>
*
* @see CameraCharacteristics#DEPTH_DEPTH_IS_EXCLUSIVE
+ * @see CameraCharacteristics#LENS_FACING
* @see CameraCharacteristics#LENS_POSE_ROTATION
* @see CameraCharacteristics#LENS_POSE_TRANSLATION
* @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
@@ -707,7 +711,7 @@ public abstract class CameraMetadata<TKey> {
/**
* <p>Timestamps from {@link CaptureResult#SENSOR_TIMESTAMP android.sensor.timestamp} are in the same timebase as
- * android.os.SystemClock#elapsedRealtimeNanos(),
+ * {@link android.os.SystemClock#elapsedRealtimeNanos },
* and they can be compared to other timestamps using that base.</p>
*
* @see CaptureResult#SENSOR_TIMESTAMP
@@ -866,7 +870,7 @@ public abstract class CameraMetadata<TKey> {
/**
* <p>Every frame has the requests immediately applied.</p>
* <p>Furthermore for all results,
- * <code>android.sync.frameNumber == CaptureResult#getFrameNumber()</code></p>
+ * <code>android.sync.frameNumber == {@link android.hardware.camera2.CaptureResult#getFrameNumber }</code></p>
* <p>Changing controls over multiple requests one after another will
* produce results that have those controls applied atomically
* each frame.</p>
diff --git a/core/java/android/hardware/camera2/CaptureRequest.java b/core/java/android/hardware/camera2/CaptureRequest.java
index 19d17b1..ab6ce91 100644
--- a/core/java/android/hardware/camera2/CaptureRequest.java
+++ b/core/java/android/hardware/camera2/CaptureRequest.java
@@ -1275,8 +1275,9 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <p>This control (except for MANUAL) is only effective if
* <code>{@link CaptureRequest#CONTROL_MODE android.control.mode} != OFF</code> and any 3A routine is active.</p>
* <p>ZERO_SHUTTER_LAG will be supported if {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities}
- * contains OPAQUE_REPROCESSING. MANUAL will be supported if {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities}
- * contains MANUAL_SENSOR. Other intent values are always supported.</p>
+ * contains OPAQUE_REPROCESSING or YUV_REPROCESSING. MANUAL will be supported if
+ * {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} contains MANUAL_SENSOR. Other intent values are
+ * always supported.</p>
* <p><b>Possible values:</b>
* <ul>
* <li>{@link #CONTROL_CAPTURE_INTENT_CUSTOM CUSTOM}</li>
@@ -2039,8 +2040,8 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* cannot process more than 1 capture at a time.</li>
* </ul>
* <p>The necessary information for the application, given the model above,
- * is provided via the {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} field
- * using StreamConfigurationMap#getOutputMinFrameDuration(int, Size).
+ * is provided via the {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} field using
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }.
* These are used to determine the maximum frame rate / minimum frame
* duration that is possible for a given stream configuration.</p>
* <p>Specifically, the application can use the following rules to
@@ -2049,21 +2050,19 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <ol>
* <li>Let the set of currently configured input/output streams
* be called <code>S</code>.</li>
- * <li>Find the minimum frame durations for each stream in <code>S</code>, by
- * looking it up in {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} using
- * StreamConfigurationMap#getOutputMinFrameDuration(int, Size) (with
- * its respective size/format). Let this set of frame durations be called
- * <code>F</code>.</li>
+ * <li>Find the minimum frame durations for each stream in <code>S</code>, by looking
+ * it up in {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} using {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }
+ * (with its respective size/format). Let this set of frame durations be
+ * called <code>F</code>.</li>
* <li>For any given request <code>R</code>, the minimum frame duration allowed
* for <code>R</code> is the maximum out of all values in <code>F</code>. Let the streams
* used in <code>R</code> be called <code>S_r</code>.</li>
* </ol>
- * <p>If none of the streams in <code>S_r</code> have a stall time (listed in
- * StreamConfigurationMap#getOutputStallDuration(int,Size) using its
- * respective size/format), then the frame duration in
- * <code>F</code> determines the steady state frame rate that the application will
- * get if it uses <code>R</code> as a repeating request. Let this special kind
- * of request be called <code>Rsimple</code>.</p>
+ * <p>If none of the streams in <code>S_r</code> have a stall time (listed in {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration }
+ * using its respective size/format), then the frame duration in <code>F</code>
+ * determines the steady state frame rate that the application will get
+ * if it uses <code>R</code> as a repeating request. Let this special kind of
+ * request be called <code>Rsimple</code>.</p>
* <p>A repeating request <code>Rsimple</code> can be <em>occasionally</em> interleaved
* by a single capture of a new request <code>Rstall</code> (which has at least
* one in-use stream with a non-0 stall time) and if <code>Rstall</code> has the
@@ -2071,7 +2070,7 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* if all buffers from the previous <code>Rstall</code> have already been
* delivered.</p>
* <p>For more details about stalling, see
- * StreamConfigurationMap#getOutputStallDuration(int,Size).</p>
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration }.</p>
* <p>This control is only effective if {@link CaptureRequest#CONTROL_AE_MODE android.control.aeMode} or {@link CaptureRequest#CONTROL_MODE android.control.mode} is set to
* OFF; otherwise the auto-exposure algorithm will override this value.</p>
* <p><b>Units</b>: Nanoseconds</p>
@@ -2647,8 +2646,12 @@ public final class CaptureRequest extends CameraMetadata<CaptureRequest.Key<?>>
* <p><b>Range of valid values:</b><br>
* &gt;= 1.0</p>
* <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
*
* @see CaptureRequest#EDGE_MODE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
* @see CaptureRequest#NOISE_REDUCTION_MODE
* @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
*/
diff --git a/core/java/android/hardware/camera2/CaptureResult.java b/core/java/android/hardware/camera2/CaptureResult.java
index ef5d75c..3dc8970 100644
--- a/core/java/android/hardware/camera2/CaptureResult.java
+++ b/core/java/android/hardware/camera2/CaptureResult.java
@@ -1698,8 +1698,9 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p>This control (except for MANUAL) is only effective if
* <code>{@link CaptureRequest#CONTROL_MODE android.control.mode} != OFF</code> and any 3A routine is active.</p>
* <p>ZERO_SHUTTER_LAG will be supported if {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities}
- * contains OPAQUE_REPROCESSING. MANUAL will be supported if {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities}
- * contains MANUAL_SENSOR. Other intent values are always supported.</p>
+ * contains OPAQUE_REPROCESSING or YUV_REPROCESSING. MANUAL will be supported if
+ * {@link CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES android.request.availableCapabilities} contains MANUAL_SENSOR. Other intent values are
+ * always supported.</p>
* <p><b>Possible values:</b>
* <ul>
* <li>{@link #CONTROL_CAPTURE_INTENT_CUSTOM CUSTOM}</li>
@@ -2885,8 +2886,8 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* cannot process more than 1 capture at a time.</li>
* </ul>
* <p>The necessary information for the application, given the model above,
- * is provided via the {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} field
- * using StreamConfigurationMap#getOutputMinFrameDuration(int, Size).
+ * is provided via the {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} field using
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }.
* These are used to determine the maximum frame rate / minimum frame
* duration that is possible for a given stream configuration.</p>
* <p>Specifically, the application can use the following rules to
@@ -2895,21 +2896,19 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <ol>
* <li>Let the set of currently configured input/output streams
* be called <code>S</code>.</li>
- * <li>Find the minimum frame durations for each stream in <code>S</code>, by
- * looking it up in {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} using
- * StreamConfigurationMap#getOutputMinFrameDuration(int, Size) (with
- * its respective size/format). Let this set of frame durations be called
- * <code>F</code>.</li>
+ * <li>Find the minimum frame durations for each stream in <code>S</code>, by looking
+ * it up in {@link CameraCharacteristics#SCALER_STREAM_CONFIGURATION_MAP android.scaler.streamConfigurationMap} using {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }
+ * (with its respective size/format). Let this set of frame durations be
+ * called <code>F</code>.</li>
* <li>For any given request <code>R</code>, the minimum frame duration allowed
* for <code>R</code> is the maximum out of all values in <code>F</code>. Let the streams
* used in <code>R</code> be called <code>S_r</code>.</li>
* </ol>
- * <p>If none of the streams in <code>S_r</code> have a stall time (listed in
- * StreamConfigurationMap#getOutputStallDuration(int,Size) using its
- * respective size/format), then the frame duration in
- * <code>F</code> determines the steady state frame rate that the application will
- * get if it uses <code>R</code> as a repeating request. Let this special kind
- * of request be called <code>Rsimple</code>.</p>
+ * <p>If none of the streams in <code>S_r</code> have a stall time (listed in {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration }
+ * using its respective size/format), then the frame duration in <code>F</code>
+ * determines the steady state frame rate that the application will get
+ * if it uses <code>R</code> as a repeating request. Let this special kind of
+ * request be called <code>Rsimple</code>.</p>
* <p>A repeating request <code>Rsimple</code> can be <em>occasionally</em> interleaved
* by a single capture of a new request <code>Rstall</code> (which has at least
* one in-use stream with a non-0 stall time) and if <code>Rstall</code> has the
@@ -2917,7 +2916,7 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* if all buffers from the previous <code>Rstall</code> have already been
* delivered.</p>
* <p>For more details about stalling, see
- * StreamConfigurationMap#getOutputStallDuration(int,Size).</p>
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputStallDuration }.</p>
* <p>This control is only effective if {@link CaptureRequest#CONTROL_AE_MODE android.control.aeMode} or {@link CaptureRequest#CONTROL_MODE android.control.mode} is set to
* OFF; otherwise the auto-exposure algorithm will override this value.</p>
* <p><b>Units</b>: Nanoseconds</p>
@@ -2979,11 +2978,10 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* and are monotonically increasing. They can be compared with the
* timestamps for other captures from the same camera device, but are
* not guaranteed to be comparable to any other time source.</p>
- * <p>When {@link CameraCharacteristics#SENSOR_INFO_TIMESTAMP_SOURCE android.sensor.info.timestampSource} <code>==</code> REALTIME,
- * the timestamps measure time in the same timebase as
- * android.os.SystemClock#elapsedRealtimeNanos(), and they can be
- * compared to other timestamps from other subsystems that are using
- * that base.</p>
+ * <p>When {@link CameraCharacteristics#SENSOR_INFO_TIMESTAMP_SOURCE android.sensor.info.timestampSource} <code>==</code> REALTIME, the
+ * 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><b>Units</b>: Nanoseconds</p>
* <p><b>Range of valid values:</b><br>
* &gt; 0</p>
@@ -3141,7 +3139,7 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p><b>Units</b>: Nanoseconds</p>
* <p><b>Range of valid values:</b><br>
* &gt;= 0 and &lt;
- * StreamConfigurationMap#getOutputMinFrameDuration(int, Size).</p>
+ * {@link android.hardware.camera2.params.StreamConfigurationMap#getOutputMinFrameDuration }.</p>
* <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
* <p><b>Limited capability</b> -
* Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
@@ -3966,8 +3964,12 @@ public class CaptureResult extends CameraMetadata<CaptureResult.Key<?>> {
* <p><b>Range of valid values:</b><br>
* &gt;= 1.0</p>
* <p><b>Optional</b> - This value may be {@code null} on some devices.</p>
+ * <p><b>Limited capability</b> -
+ * Present on all camera devices that report being at least {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL_LIMITED HARDWARE_LEVEL_LIMITED} devices in the
+ * {@link CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL android.info.supportedHardwareLevel} key</p>
*
* @see CaptureRequest#EDGE_MODE
+ * @see CameraCharacteristics#INFO_SUPPORTED_HARDWARE_LEVEL
* @see CaptureRequest#NOISE_REDUCTION_MODE
* @see CameraCharacteristics#REQUEST_AVAILABLE_CAPABILITIES
*/
diff --git a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
index abe26ea..edad00f 100644
--- a/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
+++ b/core/java/android/hardware/camera2/legacy/CameraDeviceUserShim.java
@@ -202,6 +202,7 @@ public class CameraDeviceUserShim implements ICameraDeviceUser {
private static final int CAMERA_IDLE = 1;
private static final int CAPTURE_STARTED = 2;
private static final int RESULT_RECEIVED = 3;
+ private static final int PREPARED = 4;
private final HandlerThread mHandlerThread;
private Handler mHandler;
@@ -253,7 +254,9 @@ public class CameraDeviceUserShim implements ICameraDeviceUser {
@Override
public void onPrepared(int streamId) {
- // TODO
+ Message msg = getHandler().obtainMessage(PREPARED,
+ /*arg1*/ streamId, /*arg2*/ 0);
+ getHandler().sendMessage(msg);
}
@Override
@@ -301,6 +304,11 @@ public class CameraDeviceUserShim implements ICameraDeviceUser {
mCallbacks.onResultReceived(result, resultExtras);
break;
}
+ case PREPARED: {
+ int streamId = msg.arg1;
+ mCallbacks.onPrepared(streamId);
+ break;
+ }
default:
throw new IllegalArgumentException(
"Unknown callback message " + msg.what);
@@ -631,7 +639,9 @@ public class CameraDeviceUserShim implements ICameraDeviceUser {
return CameraBinderDecorator.ENODEV;
}
- // TODO: Implement and fire callback
+ // LEGACY doesn't support actual prepare, just signal success right away
+ mCameraCallbacks.onPrepared(streamId);
+
return CameraBinderDecorator.NO_ERROR;
}
diff --git a/core/java/android/hardware/display/DisplayManagerInternal.java b/core/java/android/hardware/display/DisplayManagerInternal.java
index adab9be..02793f1 100644
--- a/core/java/android/hardware/display/DisplayManagerInternal.java
+++ b/core/java/android/hardware/display/DisplayManagerInternal.java
@@ -182,6 +182,10 @@ public abstract class DisplayManagerInternal {
// The screen auto-brightness adjustment factor in the range -1 (dimmer) to 1 (brighter).
public float screenAutoBrightnessAdjustment;
+ // Set to true if screenBrightness and screenAutoBrightnessAdjustment were both
+ // set by the user as opposed to being programmatically controlled by apps.
+ public boolean brightnessSetByUser;
+
// If true, enables automatic brightness control.
public boolean useAutoBrightness;
@@ -229,6 +233,7 @@ public abstract class DisplayManagerInternal {
useProximitySensor = other.useProximitySensor;
screenBrightness = other.screenBrightness;
screenAutoBrightnessAdjustment = other.screenAutoBrightnessAdjustment;
+ brightnessSetByUser = other.brightnessSetByUser;
useAutoBrightness = other.useAutoBrightness;
blockScreenOn = other.blockScreenOn;
lowPowerMode = other.lowPowerMode;
@@ -249,6 +254,7 @@ public abstract class DisplayManagerInternal {
&& useProximitySensor == other.useProximitySensor
&& screenBrightness == other.screenBrightness
&& screenAutoBrightnessAdjustment == other.screenAutoBrightnessAdjustment
+ && brightnessSetByUser == other.brightnessSetByUser
&& useAutoBrightness == other.useAutoBrightness
&& blockScreenOn == other.blockScreenOn
&& lowPowerMode == other.lowPowerMode
@@ -268,6 +274,7 @@ public abstract class DisplayManagerInternal {
+ ", useProximitySensor=" + useProximitySensor
+ ", screenBrightness=" + screenBrightness
+ ", screenAutoBrightnessAdjustment=" + screenAutoBrightnessAdjustment
+ + ", brightnessSetByUser=" + brightnessSetByUser
+ ", useAutoBrightness=" + useAutoBrightness
+ ", blockScreenOn=" + blockScreenOn
+ ", lowPowerMode=" + lowPowerMode
diff --git a/core/java/android/hardware/fingerprint/FingerprintManager.java b/core/java/android/hardware/fingerprint/FingerprintManager.java
index 2257b0a..cf96145 100644
--- a/core/java/android/hardware/fingerprint/FingerprintManager.java
+++ b/core/java/android/hardware/fingerprint/FingerprintManager.java
@@ -42,6 +42,7 @@ import java.util.HashMap;
import java.util.List;
import javax.crypto.Cipher;
+import javax.crypto.Mac;
/**
* A class that coordinates access to the fingerprint hardware.
@@ -195,18 +196,26 @@ public class FingerprintManager {
/**
* A wrapper class for the crypto objects supported by FingerprintManager. Currently the
- * framework supports {@link Signature} and {@link Cipher} objects.
+ * framework supports {@link Signature}, {@link Cipher} and {@link Mac} objects.
*/
public static class CryptoObject {
- public CryptoObject(Signature signature) {
+ public CryptoObject(@NonNull Signature signature) {
mSignature = signature;
mCipher = null;
+ mMac = null;
}
- public CryptoObject(Cipher cipher) {
+ public CryptoObject(@NonNull Cipher cipher) {
mCipher = cipher;
mSignature = null;
+ mMac = null;
+ }
+
+ public CryptoObject(@NonNull Mac mac) {
+ mMac = mac;
+ mCipher = null;
+ mSignature = null;
}
/**
@@ -222,6 +231,12 @@ public class FingerprintManager {
public Cipher getCipher() { return mCipher; }
/**
+ * Get {@link Mac} object.
+ * @return {@link Mac} object or null if this doesn't contain one.
+ */
+ public Mac getMac() { return mMac; }
+
+ /**
* @hide
* @return the opId associated with this object or 0 if none
*/
@@ -230,12 +245,15 @@ public class FingerprintManager {
return AndroidKeyStoreProvider.getKeyStoreOperationHandle(mSignature);
} else if (mCipher != null) {
return AndroidKeyStoreProvider.getKeyStoreOperationHandle(mCipher);
+ } else if (mMac != null) {
+ return AndroidKeyStoreProvider.getKeyStoreOperationHandle(mMac);
}
return 0;
}
private final Signature mSignature;
private final Cipher mCipher;
+ private final Mac mMac;
};
/**
@@ -416,7 +434,8 @@ public class FingerprintManager {
mAuthenticationCallback = callback;
mCryptoObject = crypto;
long sessionId = crypto != null ? crypto.getOpId() : 0;
- mService.authenticate(mToken, sessionId, userId, mServiceReceiver, flags);
+ mService.authenticate(mToken, sessionId, userId, mServiceReceiver, flags,
+ mContext.getOpPackageName());
} catch (RemoteException e) {
Log.w(TAG, "Remote exception while authenticating: ", e);
if (callback != null) {
@@ -537,7 +556,7 @@ public class FingerprintManager {
*/
public List<Fingerprint> getEnrolledFingerprints(int userId) {
if (mService != null) try {
- return mService.getEnrolledFingerprints(userId);
+ return mService.getEnrolledFingerprints(userId, mContext.getOpPackageName());
} catch (RemoteException e) {
Log.v(TAG, "Remote exception in getEnrolledFingerprints: ", e);
}
@@ -561,7 +580,8 @@ public class FingerprintManager {
*/
public boolean hasEnrolledFingerprints() {
if (mService != null) try {
- return mService.hasEnrolledFingerprints(UserHandle.myUserId());
+ return mService.hasEnrolledFingerprints(UserHandle.myUserId(),
+ mContext.getOpPackageName());
} catch (RemoteException e) {
Log.v(TAG, "Remote exception in getEnrolledFingerprints: ", e);
}
@@ -577,7 +597,7 @@ public class FingerprintManager {
if (mService != null) {
try {
long deviceId = 0; /* TODO: plumb hardware id to FPMS */
- return mService.isHardwareDetected(deviceId);
+ return mService.isHardwareDetected(deviceId, mContext.getOpPackageName());
} catch (RemoteException e) {
Log.v(TAG, "Remote exception in isFingerprintHardwareDetected(): ", e);
}
@@ -596,7 +616,7 @@ public class FingerprintManager {
public long getAuthenticatorId() {
if (mService != null) {
try {
- return mService.getAuthenticatorId();
+ return mService.getAuthenticatorId(mContext.getOpPackageName());
} catch (RemoteException e) {
Log.v(TAG, "Remote exception in getAuthenticatorId(): ", e);
}
@@ -606,7 +626,13 @@ public class FingerprintManager {
return 0;
}
- private Handler mHandler = new Handler() {
+ private Handler mHandler;
+
+ private class MyHandler extends Handler {
+ private MyHandler(Context context) {
+ super(context.getMainLooper());
+ }
+
public void handleMessage(android.os.Message msg) {
switch(msg.what) {
case MSG_ENROLL_RESULT:
@@ -691,6 +717,7 @@ public class FingerprintManager {
if (mService == null) {
Slog.v(TAG, "FingerprintManagerService was null");
}
+ mHandler = new MyHandler(context);
}
private int getCurrentUserId() {
@@ -718,7 +745,7 @@ public class FingerprintManager {
private void cancelAuthentication(CryptoObject cryptoObject) {
if (mService != null) try {
- mService.cancelAuthentication(mToken);
+ mService.cancelAuthentication(mToken, mContext.getOpPackageName());
} catch (RemoteException e) {
if (DEBUG) Log.w(TAG, "Remote exception while canceling enrollment");
}
diff --git a/core/java/android/hardware/fingerprint/IFingerprintService.aidl b/core/java/android/hardware/fingerprint/IFingerprintService.aidl
index c5ec08c..0484806 100644
--- a/core/java/android/hardware/fingerprint/IFingerprintService.aidl
+++ b/core/java/android/hardware/fingerprint/IFingerprintService.aidl
@@ -27,10 +27,10 @@ import java.util.List;
interface IFingerprintService {
// Authenticate the given sessionId with a fingerprint
void authenticate(IBinder token, long sessionId, int groupId,
- IFingerprintServiceReceiver receiver, int flags);
+ IFingerprintServiceReceiver receiver, int flags, String opPackageName);
// Cancel authentication for the given sessionId
- void cancelAuthentication(IBinder token);
+ void cancelAuthentication(IBinder token, String opPackageName);
// Start fingerprint enrollment
void enroll(IBinder token, in byte [] cryptoToken, int groupId, IFingerprintServiceReceiver receiver,
@@ -46,16 +46,16 @@ interface IFingerprintService {
void rename(int fingerId, int groupId, String name);
// Get a list of enrolled fingerprints in the given group.
- List<Fingerprint> getEnrolledFingerprints(int groupId);
+ List<Fingerprint> getEnrolledFingerprints(int groupId, String opPackageName);
// Determine if HAL is loaded and ready
- boolean isHardwareDetected(long deviceId);
+ boolean isHardwareDetected(long deviceId, String opPackageName);
// Get a pre-enrollment authentication token
long preEnroll(IBinder token);
// Determine if a user has at least one enrolled fingerprint
- boolean hasEnrolledFingerprints(int groupId);
+ boolean hasEnrolledFingerprints(int groupId, String opPackageName);
// Gets the number of hardware devices
// int getHardwareDeviceCount();
@@ -64,5 +64,5 @@ interface IFingerprintService {
// long getHardwareDevice(int i);
// Gets the authenticator ID for fingerprint
- long getAuthenticatorId();
+ long getAuthenticatorId(String opPackageName);
}
diff --git a/core/java/android/hardware/usb/UsbDevice.java b/core/java/android/hardware/usb/UsbDevice.java
index 1a42319..410d550 100644
--- a/core/java/android/hardware/usb/UsbDevice.java
+++ b/core/java/android/hardware/usb/UsbDevice.java
@@ -45,6 +45,7 @@ public class UsbDevice implements Parcelable {
private final String mName;
private final String mManufacturerName;
private final String mProductName;
+ private final String mVersion;
private final String mSerialNumber;
private final int mVendorId;
private final int mProductId;
@@ -62,7 +63,7 @@ public class UsbDevice implements Parcelable {
*/
public UsbDevice(String name, int vendorId, int productId,
int Class, int subClass, int protocol,
- String manufacturerName, String productName, String serialNumber) {
+ String manufacturerName, String productName, String version, String serialNumber) {
mName = name;
mVendorId = vendorId;
mProductId = productId;
@@ -71,6 +72,7 @@ public class UsbDevice implements Parcelable {
mProtocol = protocol;
mManufacturerName = manufacturerName;
mProductName = productName;
+ mVersion = version;
mSerialNumber = serialNumber;
}
@@ -104,6 +106,15 @@ public class UsbDevice implements Parcelable {
}
/**
+ * Returns the version number of the device.
+ *
+ * @return the device version
+ */
+ public String getVersion() {
+ return mVersion;
+ }
+
+ /**
* Returns the serial number of the device.
*
* @return the serial number name
@@ -263,7 +274,7 @@ public class UsbDevice implements Parcelable {
",mVendorId=" + mVendorId + ",mProductId=" + mProductId +
",mClass=" + mClass + ",mSubclass=" + mSubclass + ",mProtocol=" + mProtocol +
",mManufacturerName=" + mManufacturerName + ",mProductName=" + mProductName +
- ",mSerialNumber=" + mSerialNumber + ",mConfigurations=[");
+ ",mVersion=" + mVersion + ",mSerialNumber=" + mSerialNumber + ",mConfigurations=[");
for (int i = 0; i < mConfigurations.length; i++) {
builder.append("\n");
builder.append(mConfigurations[i].toString());
@@ -283,10 +294,11 @@ public class UsbDevice implements Parcelable {
int protocol = in.readInt();
String manufacturerName = in.readString();
String productName = in.readString();
+ String version = in.readString();
String serialNumber = in.readString();
Parcelable[] configurations = in.readParcelableArray(UsbInterface.class.getClassLoader());
UsbDevice device = new UsbDevice(name, vendorId, productId, clasz, subClass, protocol,
- manufacturerName, productName, serialNumber);
+ manufacturerName, productName, version, serialNumber);
device.setConfigurations(configurations);
return device;
}
@@ -309,6 +321,7 @@ public class UsbDevice implements Parcelable {
parcel.writeInt(mProtocol);
parcel.writeString(mManufacturerName);
parcel.writeString(mProductName);
+ parcel.writeString(mVersion);
parcel.writeString(mSerialNumber);
parcel.writeParcelableArray(mConfigurations, 0);
}
diff --git a/core/java/android/net/ConnectivityManager.java b/core/java/android/net/ConnectivityManager.java
index c531e7e..2d63e3f 100644
--- a/core/java/android/net/ConnectivityManager.java
+++ b/core/java/android/net/ConnectivityManager.java
@@ -341,7 +341,8 @@ public class ConnectivityManager {
* one. This is used by applications needing to talk to the carrier's
* Multimedia Messaging Service servers.
*
- * @deprecated Applications should instead use {@link #requestNetwork} to request a network that
+ * @deprecated Applications should instead use
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
* provides the {@link NetworkCapabilities#NET_CAPABILITY_MMS} capability.
*/
public static final int TYPE_MOBILE_MMS = 2;
@@ -351,7 +352,8 @@ public class ConnectivityManager {
* one. This is used by applications needing to talk to the carrier's
* Secure User Plane Location servers for help locating the device.
*
- * @deprecated Applications should instead use {@link #requestNetwork} to request a network that
+ * @deprecated Applications should instead use
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
* provides the {@link NetworkCapabilities#NET_CAPABILITY_SUPL} capability.
*/
public static final int TYPE_MOBILE_SUPL = 3;
@@ -367,7 +369,8 @@ public class ConnectivityManager {
* same network interface as {@link #TYPE_MOBILE} but the routing setup
* is different.
*
- * @deprecated Applications should instead use {@link #requestNetwork} to request a network that
+ * @deprecated Applications should instead use
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} to request a network that
* uses the {@link NetworkCapabilities#TRANSPORT_CELLULAR} transport.
*/
public static final int TYPE_MOBILE_HIPRI = 5;
@@ -910,7 +913,8 @@ public class ConnectivityManager {
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*
- * @deprecated Deprecated in favor of the cleaner {@link #requestNetwork} api.
+ * @deprecated Deprecated in favor of the cleaner
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} API.
* @removed
*/
public int startUsingNetworkFeature(int networkType, String feature) {
@@ -958,7 +962,7 @@ public class ConnectivityManager {
* implementation+feature combination, except that the value {@code -1}
* always indicates failure.
*
- * @deprecated Deprecated in favor of the cleaner {@link #requestNetwork} api.
+ * @deprecated Deprecated in favor of the cleaner {@link unregisterNetworkCallback} API.
* @removed
*/
public int stopUsingNetworkFeature(int networkType, String feature) {
@@ -1236,8 +1240,9 @@ public class ConnectivityManager {
* @param hostAddress the IP address of the host to which the route is desired
* @return {@code true} on success, {@code false} on failure
*
- * @deprecated Deprecated in favor of the {@link #requestNetwork},
- * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} api.
+ * @deprecated Deprecated in favor of the
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)},
+ * {@link #bindProcessToNetwork} and {@link Network#getSocketFactory} API.
* @removed
*/
public boolean requestRouteToHost(int networkType, int hostAddress) {
@@ -1256,7 +1261,7 @@ public class ConnectivityManager {
* @return {@code true} on success, {@code false} on failure
* @hide
* @deprecated Deprecated in favor of the {@link #requestNetwork} and
- * {@link #bindProcessToNetwork} api.
+ * {@link #bindProcessToNetwork} API.
* @removed
*/
public boolean requestRouteToHostAddress(int networkType, InetAddress hostAddress) {
@@ -2144,14 +2149,22 @@ public class ConnectivityManager {
public static final int CANCELED = 8;
/**
- * @hide
- * Called whenever the framework connects to a network that it may use to
- * satisfy this request
+ * Called when the framework connects to a new network to evaluate whether it satisfies this
+ * request. If evaluation succeeds, this callback may be followed by an {@link #onAvailable}
+ * callback. There is no guarantee that this new network will satisfy any requests, or that
+ * the network will stay connected for longer than the time necessary to evaluate it.
+ * <p>
+ * Most applications <b>should not</b> act on this callback, and should instead use
+ * {@link #onAvailable}. This callback is intended for use by applications that can assist
+ * the framework in properly evaluating the network &mdash; for example, an application that
+ * can automatically log in to a captive portal without user intervention.
+ *
+ * @param network The {@link Network} of the network that is being evaluated.
*/
public void onPreCheck(Network network) {}
/**
- * Called when the framework connects and has declared new network ready for use.
+ * Called when the framework connects and has declared a new network ready for use.
* This callback may be called more than once if the {@link Network} that is
* satisfying the request changes.
*
@@ -2251,116 +2264,82 @@ public class ConnectivityManager {
@Override
public void handleMessage(Message message) {
Log.d(TAG, "CM callback handler got msg " + message.what);
+ NetworkRequest request = (NetworkRequest) getObject(message, NetworkRequest.class);
+ Network network = (Network) getObject(message, Network.class);
switch (message.what) {
case CALLBACK_PRECHECK: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- callbacks.onPreCheck((Network)getObject(message, Network.class));
- } else {
- Log.e(TAG, "callback not found for PRECHECK message");
+ NetworkCallback callback = getCallback(request, "PRECHECK");
+ if (callback != null) {
+ callback.onPreCheck(network);
}
break;
}
case CALLBACK_AVAILABLE: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- callbacks.onAvailable((Network)getObject(message, Network.class));
- } else {
- Log.e(TAG, "callback not found for AVAILABLE message");
+ NetworkCallback callback = getCallback(request, "AVAILABLE");
+ if (callback != null) {
+ callback.onAvailable(network);
}
break;
}
case CALLBACK_LOSING: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- callbacks.onLosing((Network)getObject(message, Network.class),
- message.arg1);
- } else {
- Log.e(TAG, "callback not found for LOSING message");
+ NetworkCallback callback = getCallback(request, "LOSING");
+ if (callback != null) {
+ callback.onLosing(network, message.arg1);
}
break;
}
case CALLBACK_LOST: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
-
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- callbacks.onLost((Network)getObject(message, Network.class));
- } else {
- Log.e(TAG, "callback not found for LOST message");
+ NetworkCallback callback = getCallback(request, "LOST");
+ if (callback != null) {
+ callback.onLost(network);
}
break;
}
case CALLBACK_UNAVAIL: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = null;
- synchronized(mCallbackMap) {
- callbacks = mCallbackMap.get(request);
- }
- if (callbacks != null) {
- callbacks.onUnavailable();
- } else {
- Log.e(TAG, "callback not found for UNAVAIL message");
+ NetworkCallback callback = getCallback(request, "UNAVAIL");
+ if (callback != null) {
+ callback.onUnavailable();
}
break;
}
case CALLBACK_CAP_CHANGED: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- Network network = (Network)getObject(message, Network.class);
+ NetworkCallback callback = getCallback(request, "CAP_CHANGED");
+ if (callback != null) {
NetworkCapabilities cap = (NetworkCapabilities)getObject(message,
NetworkCapabilities.class);
- callbacks.onCapabilitiesChanged(network, cap);
- } else {
- Log.e(TAG, "callback not found for CAP_CHANGED message");
+ callback.onCapabilitiesChanged(network, cap);
}
break;
}
case CALLBACK_IP_CHANGED: {
- NetworkRequest request = (NetworkRequest)getObject(message,
- NetworkRequest.class);
- NetworkCallback callbacks = getCallbacks(request);
- if (callbacks != null) {
- Network network = (Network)getObject(message, Network.class);
+ NetworkCallback callback = getCallback(request, "IP_CHANGED");
+ if (callback != null) {
LinkProperties lp = (LinkProperties)getObject(message,
LinkProperties.class);
- callbacks.onLinkPropertiesChanged(network, lp);
- } else {
- Log.e(TAG, "callback not found for IP_CHANGED message");
+ callback.onLinkPropertiesChanged(network, lp);
}
break;
}
case CALLBACK_RELEASED: {
- NetworkRequest req = (NetworkRequest)getObject(message, NetworkRequest.class);
- NetworkCallback callbacks = null;
+ NetworkCallback callback = null;
synchronized(mCallbackMap) {
- callbacks = mCallbackMap.remove(req);
+ callback = mCallbackMap.remove(request);
}
- if (callbacks != null) {
+ if (callback != null) {
synchronized(mRefCount) {
if (mRefCount.decrementAndGet() == 0) {
getLooper().quit();
}
}
} else {
- Log.e(TAG, "callback not found for CANCELED message");
+ Log.e(TAG, "callback not found for RELEASED message");
}
break;
}
case CALLBACK_EXIT: {
- Log.d(TAG, "Listener quiting");
+ Log.d(TAG, "Listener quitting");
getLooper().quit();
break;
}
@@ -2374,10 +2353,16 @@ public class ConnectivityManager {
private Object getObject(Message msg, Class c) {
return msg.getData().getParcelable(c.getSimpleName());
}
- private NetworkCallback getCallbacks(NetworkRequest req) {
+
+ private NetworkCallback getCallback(NetworkRequest req, String name) {
+ NetworkCallback callback;
synchronized(mCallbackMap) {
- return mCallbackMap.get(req);
+ callback = mCallbackMap.get(req);
+ }
+ if (callback == null) {
+ Log.e(TAG, "callback not found for " + name + " message");
}
+ return callback;
}
}
@@ -2601,10 +2586,10 @@ public class ConnectivityManager {
/**
* Unregisters callbacks about and possibly releases networks originating from
- * {@link #requestNetwork} and {@link #registerNetworkCallback} calls. If the
- * given {@code NetworkCallback} had previously been used with {@code #requestNetwork},
- * any networks that had been connected to only to satisfy that request will be
- * disconnected.
+ * {@link #requestNetwork(NetworkRequest, NetworkCallback)} and {@link #registerNetworkCallback}
+ * calls. If the given {@code NetworkCallback} had previously been used with
+ * {@code #requestNetwork}, any networks that had been connected to only to satisfy that request
+ * will be disconnected.
*
* @param networkCallback The {@link NetworkCallback} used when making the request.
*/
diff --git a/core/java/android/net/INetworkPolicyManager.aidl b/core/java/android/net/INetworkPolicyManager.aidl
index c722fbc..7f5f377 100644
--- a/core/java/android/net/INetworkPolicyManager.aidl
+++ b/core/java/android/net/INetworkPolicyManager.aidl
@@ -38,8 +38,6 @@ interface INetworkPolicyManager {
boolean isUidForeground(int uid);
- int[] getPowerSaveAppIdWhitelist();
-
void registerListener(INetworkPolicyListener listener);
void unregisterListener(INetworkPolicyListener listener);
diff --git a/core/java/android/net/NetworkCapabilities.java b/core/java/android/net/NetworkCapabilities.java
index 8c8bfab..ab70485 100644
--- a/core/java/android/net/NetworkCapabilities.java
+++ b/core/java/android/net/NetworkCapabilities.java
@@ -37,6 +37,11 @@ public final class NetworkCapabilities implements Parcelable {
* @hide
*/
public NetworkCapabilities() {
+ clearAll();
+ mNetworkCapabilities =
+ (1 << NET_CAPABILITY_NOT_RESTRICTED) |
+ (1 << NET_CAPABILITY_TRUSTED) |
+ (1 << NET_CAPABILITY_NOT_VPN);
}
public NetworkCapabilities(NetworkCapabilities nc) {
@@ -50,11 +55,21 @@ public final class NetworkCapabilities implements Parcelable {
}
/**
+ * Completely clears the contents of this object, removing even the capabilities that are set
+ * by default when the object is constructed.
+ * @hide
+ */
+ public void clearAll() {
+ mNetworkCapabilities = mTransportTypes = 0;
+ mLinkUpBandwidthKbps = mLinkDownBandwidthKbps = 0;
+ mNetworkSpecifier = null;
+ }
+
+ /**
* Represents the network's capabilities. If any are specified they will be satisfied
* by any Network that matches all of them.
*/
- private long mNetworkCapabilities = (1 << NET_CAPABILITY_NOT_RESTRICTED) |
- (1 << NET_CAPABILITY_TRUSTED) | (1 << NET_CAPABILITY_NOT_VPN);
+ private long mNetworkCapabilities;
/**
* Indicates this is a network that has the ability to reach the
diff --git a/core/java/android/net/NetworkPolicyManager.java b/core/java/android/net/NetworkPolicyManager.java
index bc03637..ecc3fb4 100644
--- a/core/java/android/net/NetworkPolicyManager.java
+++ b/core/java/android/net/NetworkPolicyManager.java
@@ -41,6 +41,7 @@ import java.util.HashSet;
*/
public class NetworkPolicyManager {
+ /* POLICY_* are masks and can be ORed */
/** No specific network policy, use system default. */
public static final int POLICY_NONE = 0x0;
/** Reject network usage on metered networks when application in background. */
@@ -48,10 +49,17 @@ public class NetworkPolicyManager {
/** Allow network use (metered or not) in the background in battery save mode. */
public static final int POLICY_ALLOW_BACKGROUND_BATTERY_SAVE = 0x2;
+ /* RULE_* are not masks and they must be exclusive */
/** All network traffic should be allowed. */
public static final int RULE_ALLOW_ALL = 0x0;
/** Reject traffic on metered networks. */
public static final int RULE_REJECT_METERED = 0x1;
+ /** Reject traffic on all networks. */
+ public static final int RULE_REJECT_ALL = 0x2;
+
+ public static final int FIREWALL_RULE_DEFAULT = 0;
+ public static final int FIREWALL_RULE_ALLOW = 1;
+ public static final int FIREWALL_RULE_DENY = 2;
private static final boolean ALLOW_PLATFORM_APP_POLICY = true;
@@ -80,7 +88,7 @@ public class NetworkPolicyManager {
* Set policy flags for specific UID.
*
* @param policy {@link #POLICY_NONE} or combination of flags like
- * {@link #POLICY_REJECT_METERED_BACKGROUND}, {@link #POLICY_ALLOW_BACKGROUND_BATTERY_SAVE}.
+ * {@link #POLICY_REJECT_METERED_BACKGROUND} or {@link #POLICY_ALLOW_BACKGROUND_BATTERY_SAVE}.
*/
public void setUidPolicy(int uid, int policy) {
try {
@@ -129,14 +137,6 @@ public class NetworkPolicyManager {
}
}
- public int[] getPowerSaveAppIdWhitelist() {
- try {
- return mService.getPowerSaveAppIdWhitelist();
- } catch (RemoteException e) {
- return new int[0];
- }
- }
-
public void registerListener(INetworkPolicyListener listener) {
try {
mService.registerListener(listener);
@@ -330,6 +330,8 @@ public class NetworkPolicyManager {
fout.write("[");
if ((rules & RULE_REJECT_METERED) != 0) {
fout.write("REJECT_METERED");
+ } else if ((rules & RULE_REJECT_ALL) != 0) {
+ fout.write("REJECT_ALL");
}
fout.write("]");
}
diff --git a/core/java/android/net/Uri.java b/core/java/android/net/Uri.java
index f305b2a..4a8dfbc 100644
--- a/core/java/android/net/Uri.java
+++ b/core/java/android/net/Uri.java
@@ -1657,7 +1657,7 @@ public abstract class Uri implements Parcelable, Comparable<Uri> {
/**
* Searches the query string for the first value with the given key.
*
- * <p><strong>Warning:</strong> Prior to Ice Cream Sandwich, this decoded
+ * <p><strong>Warning:</strong> Prior to Jelly Bean, this decoded
* the '+' character as '+' rather than ' '.
*
* @param key which will be encoded
diff --git a/core/java/android/os/Environment.java b/core/java/android/os/Environment.java
index 2eb97f1..8e0584a 100644
--- a/core/java/android/os/Environment.java
+++ b/core/java/android/os/Environment.java
@@ -20,6 +20,7 @@ import android.app.admin.DevicePolicyManager;
import android.content.Context;
import android.os.storage.StorageManager;
import android.os.storage.StorageVolume;
+import android.text.TextUtils;
import android.util.Log;
import java.io.File;
@@ -242,6 +243,15 @@ public class Environment {
return DATA_DIRECTORY;
}
+ /** {@hide} */
+ public static File getDataAppDirectory(String volumeUuid) {
+ if (TextUtils.isEmpty(volumeUuid)) {
+ return new File("/data/app");
+ } else {
+ return new File("/mnt/expand/" + volumeUuid + "/app");
+ }
+ }
+
/**
* Return the primary external storage directory. This directory may not
* currently be accessible if it has been mounted by the user on their
@@ -758,7 +768,6 @@ public class Environment {
* @hide
*/
public static File maybeTranslateEmulatedPathToInternal(File path) {
- // TODO: bring back this optimization
- return path;
+ return StorageManager.maybeTranslateEmulatedPathToInternal(path);
}
}
diff --git a/core/java/android/os/FileUtils.java b/core/java/android/os/FileUtils.java
index 931cd3e..021e5e4 100644
--- a/core/java/android/os/FileUtils.java
+++ b/core/java/android/os/FileUtils.java
@@ -390,7 +390,7 @@ public class FileUtils {
* attacks.
*/
public static boolean contains(File dir, File file) {
- if (file == null) return false;
+ if (dir == null || file == null) return false;
String dirPath = dir.getAbsolutePath();
String filePath = file.getAbsolutePath();
diff --git a/core/java/android/os/IDeviceIdleController.aidl b/core/java/android/os/IDeviceIdleController.aidl
new file mode 100644
index 0000000..3cb29ff
--- /dev/null
+++ b/core/java/android/os/IDeviceIdleController.aidl
@@ -0,0 +1,26 @@
+/**
+ * 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.os;
+
+/** @hide */
+interface IDeviceIdleController {
+ void addPowerSaveWhitelistApp(String name);
+ void removePowerSaveWhitelistApp(String name);
+ String[] getSystemPowerWhitelist();
+ String[] getFullPowerWhitelist();
+ int[] getAppIdWhitelist();
+}
diff --git a/core/java/android/os/INetworkManagementService.aidl b/core/java/android/os/INetworkManagementService.aidl
index f93550a..b29e8d0 100644
--- a/core/java/android/os/INetworkManagementService.aidl
+++ b/core/java/android/os/INetworkManagementService.aidl
@@ -342,7 +342,7 @@ interface INetworkManagementService
void setFirewallInterfaceRule(String iface, boolean allow);
void setFirewallEgressSourceRule(String addr, boolean allow);
void setFirewallEgressDestRule(String addr, int port, boolean allow);
- void setFirewallUidRule(int uid, boolean allow);
+ void setFirewallUidRule(int uid, int rule);
/**
* Set all packets from users in ranges to go through VPN specified by netId.
diff --git a/core/java/android/os/IPermissionController.aidl b/core/java/android/os/IPermissionController.aidl
index 73a68f1..0cc1603 100644
--- a/core/java/android/os/IPermissionController.aidl
+++ b/core/java/android/os/IPermissionController.aidl
@@ -20,4 +20,5 @@ package android.os;
/** @hide */
interface IPermissionController {
boolean checkPermission(String permission, int pid, int uid);
+ String[] getPackagesForUid(int uid);
}
diff --git a/core/java/android/os/PowerManager.java b/core/java/android/os/PowerManager.java
index 01c9a21..1d9d7d2 100644
--- a/core/java/android/os/PowerManager.java
+++ b/core/java/android/os/PowerManager.java
@@ -920,6 +920,14 @@ public final class PowerManager {
= "android.os.action.DEVICE_IDLE_MODE_CHANGED";
/**
+ * @hide Intent that is broadcast when the set of power save whitelist apps has changed.
+ * This broadcast is only sent to registered receivers.
+ */
+ @SdkConstant(SdkConstant.SdkConstantType.BROADCAST_INTENT_ACTION)
+ public static final String ACTION_POWER_SAVE_WHITELIST_CHANGED
+ = "android.os.action.POWER_SAVE_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/Process.java b/core/java/android/os/Process.java
index 355ec8c..009649f 100644
--- a/core/java/android/os/Process.java
+++ b/core/java/android/os/Process.java
@@ -634,6 +634,9 @@ public class Process {
if ((debugFlags & Zygote.DEBUG_ENABLE_JIT) != 0) {
argsForZygote.add("--enable-jit");
}
+ if ((debugFlags & Zygote.DEBUG_GENERATE_CFI) != 0) {
+ argsForZygote.add("--generate-cfi");
+ }
if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
argsForZygote.add("--enable-assert");
}
diff --git a/core/java/android/os/storage/IMountService.java b/core/java/android/os/storage/IMountService.java
index 16e0bf7..fcde3f4 100644
--- a/core/java/android/os/storage/IMountService.java
+++ b/core/java/android/os/storage/IMountService.java
@@ -942,6 +942,24 @@ public interface IMountService extends IInterface {
}
@Override
+ public VolumeRecord[] getVolumeRecords(int _flags) throws RemoteException {
+ Parcel _data = Parcel.obtain();
+ Parcel _reply = Parcel.obtain();
+ VolumeRecord[] _result;
+ try {
+ _data.writeInterfaceToken(DESCRIPTOR);
+ _data.writeInt(_flags);
+ mRemote.transact(Stub.TRANSACTION_getVolumeRecords, _data, _reply, 0);
+ _reply.readException();
+ _result = _reply.createTypedArray(VolumeRecord.CREATOR);
+ } finally {
+ _reply.recycle();
+ _data.recycle();
+ }
+ return _result;
+ }
+
+ @Override
public void mount(String volId) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
@@ -1033,12 +1051,12 @@ public interface IMountService extends IInterface {
}
@Override
- public void setVolumeNickname(String volId, String nickname) throws RemoteException {
+ public void setVolumeNickname(String fsUuid, String nickname) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
- _data.writeString(volId);
+ _data.writeString(fsUuid);
_data.writeString(nickname);
mRemote.transact(Stub.TRANSACTION_setVolumeNickname, _data, _reply, 0);
_reply.readException();
@@ -1049,12 +1067,12 @@ public interface IMountService extends IInterface {
}
@Override
- public void setVolumeUserFlags(String volId, int flags, int mask) throws RemoteException {
+ public void setVolumeUserFlags(String fsUuid, int flags, int mask) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
- _data.writeString(volId);
+ _data.writeString(fsUuid);
_data.writeInt(flags);
_data.writeInt(mask);
mRemote.transact(Stub.TRANSACTION_setVolumeUserFlags, _data, _reply, 0);
@@ -1066,6 +1084,21 @@ public interface IMountService extends IInterface {
}
@Override
+ public void forgetVolume(String fsUuid) throws RemoteException {
+ Parcel _data = Parcel.obtain();
+ Parcel _reply = Parcel.obtain();
+ try {
+ _data.writeInterfaceToken(DESCRIPTOR);
+ _data.writeString(fsUuid);
+ mRemote.transact(Stub.TRANSACTION_forgetVolume, _data, _reply, 0);
+ _reply.readException();
+ } finally {
+ _reply.recycle();
+ _data.recycle();
+ }
+ }
+
+ @Override
public String getPrimaryStorageUuid() throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
@@ -1192,20 +1225,22 @@ public interface IMountService extends IInterface {
static final int TRANSACTION_getDisks = IBinder.FIRST_CALL_TRANSACTION + 44;
static final int TRANSACTION_getVolumes = IBinder.FIRST_CALL_TRANSACTION + 45;
+ static final int TRANSACTION_getVolumeRecords = IBinder.FIRST_CALL_TRANSACTION + 46;
- static final int TRANSACTION_mount = IBinder.FIRST_CALL_TRANSACTION + 46;
- static final int TRANSACTION_unmount = IBinder.FIRST_CALL_TRANSACTION + 47;
- static final int TRANSACTION_format = IBinder.FIRST_CALL_TRANSACTION + 48;
+ static final int TRANSACTION_mount = IBinder.FIRST_CALL_TRANSACTION + 47;
+ static final int TRANSACTION_unmount = IBinder.FIRST_CALL_TRANSACTION + 48;
+ static final int TRANSACTION_format = IBinder.FIRST_CALL_TRANSACTION + 49;
- static final int TRANSACTION_partitionPublic = IBinder.FIRST_CALL_TRANSACTION + 49;
- static final int TRANSACTION_partitionPrivate = IBinder.FIRST_CALL_TRANSACTION + 50;
- static final int TRANSACTION_partitionMixed = IBinder.FIRST_CALL_TRANSACTION + 51;
+ static final int TRANSACTION_partitionPublic = IBinder.FIRST_CALL_TRANSACTION + 50;
+ static final int TRANSACTION_partitionPrivate = IBinder.FIRST_CALL_TRANSACTION + 51;
+ static final int TRANSACTION_partitionMixed = IBinder.FIRST_CALL_TRANSACTION + 52;
- static final int TRANSACTION_setVolumeNickname = IBinder.FIRST_CALL_TRANSACTION + 52;
- static final int TRANSACTION_setVolumeUserFlags = IBinder.FIRST_CALL_TRANSACTION + 53;
+ static final int TRANSACTION_setVolumeNickname = IBinder.FIRST_CALL_TRANSACTION + 53;
+ static final int TRANSACTION_setVolumeUserFlags = IBinder.FIRST_CALL_TRANSACTION + 54;
+ static final int TRANSACTION_forgetVolume = IBinder.FIRST_CALL_TRANSACTION + 55;
- static final int TRANSACTION_getPrimaryStorageUuid = IBinder.FIRST_CALL_TRANSACTION + 54;
- static final int TRANSACTION_setPrimaryStorageUuid = IBinder.FIRST_CALL_TRANSACTION + 55;
+ static final int TRANSACTION_getPrimaryStorageUuid = IBinder.FIRST_CALL_TRANSACTION + 56;
+ static final int TRANSACTION_setPrimaryStorageUuid = IBinder.FIRST_CALL_TRANSACTION + 57;
/**
* Cast an IBinder object into an IMountService interface, generating a
@@ -1647,6 +1682,14 @@ public interface IMountService extends IInterface {
reply.writeTypedArray(volumes, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
return true;
}
+ case TRANSACTION_getVolumeRecords: {
+ data.enforceInterface(DESCRIPTOR);
+ int _flags = data.readInt();
+ VolumeRecord[] volumes = getVolumeRecords(_flags);
+ reply.writeNoException();
+ reply.writeTypedArray(volumes, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
+ return true;
+ }
case TRANSACTION_mount: {
data.enforceInterface(DESCRIPTOR);
String volId = data.readString();
@@ -1707,6 +1750,13 @@ public interface IMountService extends IInterface {
reply.writeNoException();
return true;
}
+ case TRANSACTION_forgetVolume: {
+ data.enforceInterface(DESCRIPTOR);
+ String fsUuid = data.readString();
+ forgetVolume(fsUuid);
+ reply.writeNoException();
+ return true;
+ }
case TRANSACTION_getPrimaryStorageUuid: {
data.enforceInterface(DESCRIPTOR);
String volumeUuid = getPrimaryStorageUuid();
@@ -2012,6 +2062,7 @@ public interface IMountService extends IInterface {
public DiskInfo[] getDisks() throws RemoteException;
public VolumeInfo[] getVolumes(int flags) throws RemoteException;
+ public VolumeRecord[] getVolumeRecords(int flags) throws RemoteException;
public void mount(String volId) throws RemoteException;
public void unmount(String volId) throws RemoteException;
@@ -2021,8 +2072,9 @@ public interface IMountService extends IInterface {
public void partitionPrivate(String diskId) throws RemoteException;
public void partitionMixed(String diskId, int ratio) throws RemoteException;
- public void setVolumeNickname(String volId, String nickname) throws RemoteException;
- public void setVolumeUserFlags(String volId, int flags, int mask) throws RemoteException;
+ public void setVolumeNickname(String fsUuid, String nickname) throws RemoteException;
+ public void setVolumeUserFlags(String fsUuid, int flags, int mask) throws RemoteException;
+ public void forgetVolume(String fsUuid) throws RemoteException;
public String getPrimaryStorageUuid() throws RemoteException;
public void setPrimaryStorageUuid(String volumeUuid, IPackageMoveObserver callback)
diff --git a/core/java/android/os/storage/IMountServiceListener.java b/core/java/android/os/storage/IMountServiceListener.java
index fcb4779..c958fb0 100644
--- a/core/java/android/os/storage/IMountServiceListener.java
+++ b/core/java/android/os/storage/IMountServiceListener.java
@@ -91,10 +91,17 @@ public interface IMountServiceListener extends IInterface {
reply.writeNoException();
return true;
}
- case TRANSACTION_onVolumeMetadataChanged: {
+ case TRANSACTION_onVolumeRecordChanged: {
data.enforceInterface(DESCRIPTOR);
- final VolumeInfo vol = (VolumeInfo) data.readParcelable(null);
- onVolumeMetadataChanged(vol);
+ final VolumeRecord rec = (VolumeRecord) data.readParcelable(null);
+ onVolumeRecordChanged(rec);
+ reply.writeNoException();
+ return true;
+ }
+ case TRANSACTION_onVolumeForgotten: {
+ data.enforceInterface(DESCRIPTOR);
+ final String fsUuid = data.readString();
+ onVolumeForgotten(fsUuid);
reply.writeNoException();
return true;
}
@@ -192,13 +199,29 @@ public interface IMountServiceListener extends IInterface {
}
@Override
- public void onVolumeMetadataChanged(VolumeInfo vol) throws RemoteException {
+ public void onVolumeRecordChanged(VolumeRecord rec) throws RemoteException {
Parcel _data = Parcel.obtain();
Parcel _reply = Parcel.obtain();
try {
_data.writeInterfaceToken(DESCRIPTOR);
- _data.writeParcelable(vol, 0);
- mRemote.transact(Stub.TRANSACTION_onVolumeMetadataChanged, _data, _reply,
+ _data.writeParcelable(rec, 0);
+ mRemote.transact(Stub.TRANSACTION_onVolumeRecordChanged, _data, _reply,
+ android.os.IBinder.FLAG_ONEWAY);
+ _reply.readException();
+ } finally {
+ _reply.recycle();
+ _data.recycle();
+ }
+ }
+
+ @Override
+ public void onVolumeForgotten(String fsUuid) throws RemoteException {
+ Parcel _data = Parcel.obtain();
+ Parcel _reply = Parcel.obtain();
+ try {
+ _data.writeInterfaceToken(DESCRIPTOR);
+ _data.writeString(fsUuid);
+ mRemote.transact(Stub.TRANSACTION_onVolumeForgotten, _data, _reply,
android.os.IBinder.FLAG_ONEWAY);
_reply.readException();
} finally {
@@ -228,8 +251,9 @@ public interface IMountServiceListener extends IInterface {
static final int TRANSACTION_onUsbMassStorageConnectionChanged = (IBinder.FIRST_CALL_TRANSACTION + 0);
static final int TRANSACTION_onStorageStateChanged = (IBinder.FIRST_CALL_TRANSACTION + 1);
static final int TRANSACTION_onVolumeStateChanged = (IBinder.FIRST_CALL_TRANSACTION + 2);
- static final int TRANSACTION_onVolumeMetadataChanged = (IBinder.FIRST_CALL_TRANSACTION + 3);
- static final int TRANSACTION_onDiskScanned = (IBinder.FIRST_CALL_TRANSACTION + 4);
+ static final int TRANSACTION_onVolumeRecordChanged = (IBinder.FIRST_CALL_TRANSACTION + 3);
+ static final int TRANSACTION_onVolumeForgotten = (IBinder.FIRST_CALL_TRANSACTION + 4);
+ static final int TRANSACTION_onDiskScanned = (IBinder.FIRST_CALL_TRANSACTION + 5);
}
/**
@@ -252,8 +276,8 @@ public interface IMountServiceListener extends IInterface {
public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState)
throws RemoteException;
-
- public void onVolumeMetadataChanged(VolumeInfo vol) throws RemoteException;
+ public void onVolumeRecordChanged(VolumeRecord rec) throws RemoteException;
+ public void onVolumeForgotten(String fsUuid) throws RemoteException;
public void onDiskScanned(DiskInfo disk, int volumeCount) throws RemoteException;
}
diff --git a/core/java/android/os/storage/StorageEventListener.java b/core/java/android/os/storage/StorageEventListener.java
index 6a0140e..214c60d 100644
--- a/core/java/android/os/storage/StorageEventListener.java
+++ b/core/java/android/os/storage/StorageEventListener.java
@@ -41,7 +41,10 @@ public class StorageEventListener {
public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) {
}
- public void onVolumeMetadataChanged(VolumeInfo vol) {
+ public void onVolumeRecordChanged(VolumeRecord rec) {
+ }
+
+ public void onVolumeForgotten(String fsUuid) {
}
public void onDiskScanned(DiskInfo disk, int volumeCount) {
diff --git a/core/java/android/os/storage/StorageManager.java b/core/java/android/os/storage/StorageManager.java
index 6116aef..50e7d1c 100644
--- a/core/java/android/os/storage/StorageManager.java
+++ b/core/java/android/os/storage/StorageManager.java
@@ -34,6 +34,7 @@ import android.os.ServiceManager;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
+import android.util.Slog;
import android.util.SparseArray;
import com.android.internal.os.SomeArgs;
@@ -79,9 +80,6 @@ public class StorageManager {
/** {@hide} */
public static final String UUID_PRIMARY_PHYSICAL = "primary_physical";
- /** {@hide} */
- public static final int FLAG_ALL_METADATA = 1 << 0;
-
private final Context mContext;
private final ContentResolver mResolver;
@@ -95,8 +93,9 @@ public class StorageManager {
Handler.Callback {
private static final int MSG_STORAGE_STATE_CHANGED = 1;
private static final int MSG_VOLUME_STATE_CHANGED = 2;
- private static final int MSG_VOLUME_METADATA_CHANGED = 3;
- private static final int MSG_DISK_SCANNED = 4;
+ private static final int MSG_VOLUME_RECORD_CHANGED = 3;
+ private static final int MSG_VOLUME_FORGOTTEN = 4;
+ private static final int MSG_DISK_SCANNED = 5;
final StorageEventListener mCallback;
final Handler mHandler;
@@ -119,8 +118,12 @@ public class StorageManager {
mCallback.onVolumeStateChanged((VolumeInfo) args.arg1, args.argi2, args.argi3);
args.recycle();
return true;
- case MSG_VOLUME_METADATA_CHANGED:
- mCallback.onVolumeMetadataChanged((VolumeInfo) args.arg1);
+ case MSG_VOLUME_RECORD_CHANGED:
+ mCallback.onVolumeRecordChanged((VolumeRecord) args.arg1);
+ args.recycle();
+ return true;
+ case MSG_VOLUME_FORGOTTEN:
+ mCallback.onVolumeForgotten((String) args.arg1);
args.recycle();
return true;
case MSG_DISK_SCANNED:
@@ -156,10 +159,17 @@ public class StorageManager {
}
@Override
- public void onVolumeMetadataChanged(VolumeInfo vol) {
+ public void onVolumeRecordChanged(VolumeRecord rec) {
final SomeArgs args = SomeArgs.obtain();
- args.arg1 = vol;
- mHandler.obtainMessage(MSG_VOLUME_METADATA_CHANGED, args).sendToTarget();
+ args.arg1 = rec;
+ mHandler.obtainMessage(MSG_VOLUME_RECORD_CHANGED, args).sendToTarget();
+ }
+
+ @Override
+ public void onVolumeForgotten(String fsUuid) {
+ final SomeArgs args = SomeArgs.obtain();
+ args.arg1 = fsUuid;
+ mHandler.obtainMessage(MSG_VOLUME_FORGOTTEN, args).sendToTarget();
}
@Override
@@ -248,8 +258,9 @@ public class StorageManager {
}
/** {@hide} */
+ @Deprecated
public static StorageManager from(Context context) {
- return (StorageManager) context.getSystemService(Context.STORAGE_SERVICE);
+ return context.getSystemService(StorageManager.class);
}
/**
@@ -516,6 +527,18 @@ public class StorageManager {
}
/** {@hide} */
+ public @Nullable VolumeRecord findRecordByUuid(String fsUuid) {
+ Preconditions.checkNotNull(fsUuid);
+ // TODO; go directly to service to make this faster
+ for (VolumeRecord rec : getVolumeRecords()) {
+ if (Objects.equals(rec.fsUuid, fsUuid)) {
+ return rec;
+ }
+ }
+ return null;
+ }
+
+ /** {@hide} */
public @Nullable VolumeInfo findPrivateForEmulated(VolumeInfo emulatedVol) {
return findVolumeById(emulatedVol.getId().replace("emulated", "private"));
}
@@ -526,14 +549,29 @@ public class StorageManager {
}
/** {@hide} */
+ public @Nullable VolumeInfo findVolumeByQualifiedUuid(String volumeUuid) {
+ if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
+ return findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
+ } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
+ return getPrimaryPhysicalVolume();
+ } else {
+ return findVolumeByUuid(volumeUuid);
+ }
+ }
+
+ /** {@hide} */
public @NonNull List<VolumeInfo> getVolumes() {
- return getVolumes(0);
+ try {
+ return Arrays.asList(mMountService.getVolumes(0));
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
}
/** {@hide} */
- public @NonNull List<VolumeInfo> getVolumes(int flags) {
+ public @NonNull List<VolumeRecord> getVolumeRecords() {
try {
- return Arrays.asList(mMountService.getVolumes(flags));
+ return Arrays.asList(mMountService.getVolumeRecords(0));
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -541,13 +579,25 @@ public class StorageManager {
/** {@hide} */
public @Nullable String getBestVolumeDescription(VolumeInfo vol) {
- String descrip = vol.getDescription();
- if (vol.disk != null) {
- if (TextUtils.isEmpty(descrip)) {
- descrip = vol.disk.getDescription();
+ if (vol == null) return null;
+
+ // Nickname always takes precedence when defined
+ if (!TextUtils.isEmpty(vol.fsUuid)) {
+ final VolumeRecord rec = findRecordByUuid(vol.fsUuid);
+ if (!TextUtils.isEmpty(rec.nickname)) {
+ return rec.nickname;
}
}
- return descrip;
+
+ if (!TextUtils.isEmpty(vol.getDescription())) {
+ return vol.getDescription();
+ }
+
+ if (vol.disk != null) {
+ return vol.disk.getDescription();
+ }
+
+ return null;
}
/** {@hide} */
@@ -616,29 +666,62 @@ public class StorageManager {
}
/** {@hide} */
- public void setVolumeNickname(String volId, String nickname) {
+ public void wipeAdoptableDisks() {
+ // We only wipe devices in "adoptable" locations, which are in a
+ // long-term stable slot/location on the device, where apps have a
+ // reasonable chance of storing sensitive data. (Apps need to go through
+ // SAF to write to transient volumes.)
+ final List<DiskInfo> disks = getDisks();
+ for (DiskInfo disk : disks) {
+ final String diskId = disk.getId();
+ if (disk.isAdoptable()) {
+ Slog.d(TAG, "Found adoptable " + diskId + "; wiping");
+ try {
+ // TODO: switch to explicit wipe command when we have it,
+ // for now rely on the fact that vfat format does a wipe
+ mMountService.partitionPublic(diskId);
+ } catch (Exception e) {
+ Slog.w(TAG, "Failed to wipe " + diskId + ", but soldiering onward", e);
+ }
+ } else {
+ Slog.d(TAG, "Ignorning non-adoptable disk " + disk.getId());
+ }
+ }
+ }
+
+ /** {@hide} */
+ public void setVolumeNickname(String fsUuid, String nickname) {
try {
- mMountService.setVolumeNickname(volId, nickname);
+ mMountService.setVolumeNickname(fsUuid, nickname);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
/** {@hide} */
- public void setVolumeInited(String volId, boolean inited) {
+ public void setVolumeInited(String fsUuid, boolean inited) {
try {
- mMountService.setVolumeUserFlags(volId, inited ? VolumeInfo.USER_FLAG_INITED : 0,
- VolumeInfo.USER_FLAG_INITED);
+ mMountService.setVolumeUserFlags(fsUuid, inited ? VolumeRecord.USER_FLAG_INITED : 0,
+ VolumeRecord.USER_FLAG_INITED);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
}
/** {@hide} */
- public void setVolumeSnoozed(String volId, boolean snoozed) {
+ public void setVolumeSnoozed(String fsUuid, boolean snoozed) {
try {
- mMountService.setVolumeUserFlags(volId, snoozed ? VolumeInfo.USER_FLAG_SNOOZED : 0,
- VolumeInfo.USER_FLAG_SNOOZED);
+ mMountService.setVolumeUserFlags(fsUuid, snoozed ? VolumeRecord.USER_FLAG_SNOOZED : 0,
+ VolumeRecord.USER_FLAG_SNOOZED);
+ } catch (RemoteException e) {
+ throw e.rethrowAsRuntimeException();
+ }
+ }
+
+ /** {@hide} */
+ public void forgetVolume(String fsUuid) {
+ try {
+ mMountService.forgetVolume(fsUuid);
} catch (RemoteException e) {
throw e.rethrowAsRuntimeException();
}
@@ -804,6 +887,27 @@ public class StorageManager {
DEFAULT_FULL_THRESHOLD_BYTES);
}
+ /** {@hide} */
+ public static File maybeTranslateEmulatedPathToInternal(File path) {
+ final IMountService mountService = IMountService.Stub.asInterface(
+ ServiceManager.getService("mount"));
+ try {
+ final VolumeInfo[] vols = mountService.getVolumes(0);
+ for (VolumeInfo vol : vols) {
+ if ((vol.getType() == VolumeInfo.TYPE_EMULATED
+ || vol.getType() == VolumeInfo.TYPE_PUBLIC) && vol.isMountedReadable()) {
+ final File internalPath = FileUtils.rewriteAfterRename(vol.getPath(),
+ vol.getInternalPath(), path);
+ if (internalPath != null) {
+ return internalPath;
+ }
+ }
+ }
+ } catch (RemoteException ignored) {
+ }
+ return path;
+ }
+
/// Consts to match the password types in cryptfs.h
/** @hide */
public static final int CRYPT_TYPE_PASSWORD = 0;
diff --git a/core/java/android/os/storage/VolumeInfo.java b/core/java/android/os/storage/VolumeInfo.java
index 4e9cfc7..2622ee0 100644
--- a/core/java/android/os/storage/VolumeInfo.java
+++ b/core/java/android/os/storage/VolumeInfo.java
@@ -78,9 +78,6 @@ public class VolumeInfo implements Parcelable {
public static final int MOUNT_FLAG_PRIMARY = 1 << 0;
public static final int MOUNT_FLAG_VISIBLE = 1 << 1;
- public static final int USER_FLAG_INITED = 1 << 0;
- public static final int USER_FLAG_SNOOZED = 1 << 1;
-
private static SparseArray<String> sStateToEnvironment = new SparseArray<>();
private static ArrayMap<String, String> sEnvironmentToBroadcast = new ArrayMap<>();
@@ -132,11 +129,10 @@ public class VolumeInfo implements Parcelable {
public String fsUuid;
public String fsLabel;
public String path;
+ public String internalPath;
/** Framework state */
public final int mtpIndex;
- public String nickname;
- public int userFlags = 0;
public VolumeInfo(String id, int type, DiskInfo disk, int mtpIndex) {
this.id = Preconditions.checkNotNull(id);
@@ -160,9 +156,8 @@ public class VolumeInfo implements Parcelable {
fsUuid = parcel.readString();
fsLabel = parcel.readString();
path = parcel.readString();
+ internalPath = parcel.readString();
mtpIndex = parcel.readInt();
- nickname = parcel.readString();
- userFlags = parcel.readInt();
}
public static @NonNull String getEnvironmentForState(int state) {
@@ -210,10 +205,6 @@ public class VolumeInfo implements Parcelable {
return fsUuid;
}
- public @Nullable String getNickname() {
- return nickname;
- }
-
public int getMountUserId() {
return mountUserId;
}
@@ -221,8 +212,6 @@ public class VolumeInfo implements Parcelable {
public @Nullable String getDescription() {
if (ID_PRIVATE_INTERNAL.equals(id)) {
return Resources.getSystem().getString(com.android.internal.R.string.storage_internal);
- } else if (!TextUtils.isEmpty(nickname)) {
- return nickname;
} else if (!TextUtils.isEmpty(fsLabel)) {
return fsLabel;
} else {
@@ -250,14 +239,6 @@ public class VolumeInfo implements Parcelable {
return (mountFlags & MOUNT_FLAG_VISIBLE) != 0;
}
- public boolean isInited() {
- return (userFlags & USER_FLAG_INITED) != 0;
- }
-
- public boolean isSnoozed() {
- return (userFlags & USER_FLAG_SNOOZED) != 0;
- }
-
public boolean isVisibleToUser(int userId) {
if (type == TYPE_PUBLIC && userId == this.mountUserId) {
return isVisible();
@@ -269,7 +250,11 @@ public class VolumeInfo implements Parcelable {
}
public File getPath() {
- return new File(path);
+ return (path != null) ? new File(path) : null;
+ }
+
+ public File getInternalPath() {
+ return (internalPath != null) ? new File(internalPath) : null;
}
public File getPathForUser(int userId) {
@@ -356,14 +341,11 @@ public class VolumeInfo implements Parcelable {
final Uri uri;
if (type == VolumeInfo.TYPE_PUBLIC) {
uri = DocumentsContract.buildRootUri(DOCUMENT_AUTHORITY, fsUuid);
- } else if (VolumeInfo.ID_EMULATED_INTERNAL.equals(id)) {
+ } else if (type == VolumeInfo.TYPE_EMULATED && isPrimary()) {
uri = DocumentsContract.buildRootUri(DOCUMENT_AUTHORITY,
DOCUMENT_ROOT_PRIMARY_EMULATED);
- } else if (type == VolumeInfo.TYPE_EMULATED) {
- // TODO: build intent once supported
- uri = null;
} else {
- throw new IllegalArgumentException();
+ return null;
}
final Intent intent = new Intent(DocumentsContract.ACTION_BROWSE_DOCUMENT_ROOT);
@@ -393,9 +375,8 @@ public class VolumeInfo implements Parcelable {
pw.printPair("fsLabel", fsLabel);
pw.println();
pw.printPair("path", path);
+ pw.printPair("internalPath", internalPath);
pw.printPair("mtpIndex", mtpIndex);
- pw.printPair("nickname", nickname);
- pw.printPair("userFlags", DebugUtils.flagsToString(getClass(), "USER_FLAG_", userFlags));
pw.decreaseIndent();
pw.println();
}
@@ -460,8 +441,7 @@ public class VolumeInfo implements Parcelable {
parcel.writeString(fsUuid);
parcel.writeString(fsLabel);
parcel.writeString(path);
+ parcel.writeString(internalPath);
parcel.writeInt(mtpIndex);
- parcel.writeString(nickname);
- parcel.writeInt(userFlags);
}
}
diff --git a/core/java/android/os/storage/VolumeRecord.java b/core/java/android/os/storage/VolumeRecord.java
new file mode 100644
index 0000000..096e2dd
--- /dev/null
+++ b/core/java/android/os/storage/VolumeRecord.java
@@ -0,0 +1,139 @@
+/*
+ * 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.os.storage;
+
+import android.os.Parcel;
+import android.os.Parcelable;
+import android.util.DebugUtils;
+
+import com.android.internal.util.IndentingPrintWriter;
+import com.android.internal.util.Preconditions;
+
+import java.util.Objects;
+
+/**
+ * Metadata for a storage volume which may not be currently present.
+ *
+ * @hide
+ */
+public class VolumeRecord implements Parcelable {
+ public static final String EXTRA_FS_UUID =
+ "android.os.storage.extra.FS_UUID";
+
+ public static final int USER_FLAG_INITED = 1 << 0;
+ public static final int USER_FLAG_SNOOZED = 1 << 1;
+
+ public final int type;
+ public final String fsUuid;
+ public String nickname;
+ public int userFlags;
+
+ public VolumeRecord(int type, String fsUuid) {
+ this.type = type;
+ this.fsUuid = Preconditions.checkNotNull(fsUuid);
+ }
+
+ public VolumeRecord(Parcel parcel) {
+ type = parcel.readInt();
+ fsUuid = parcel.readString();
+ nickname = parcel.readString();
+ userFlags = parcel.readInt();
+ }
+
+ public int getType() {
+ return type;
+ }
+
+ public String getFsUuid() {
+ return fsUuid;
+ }
+
+ public String getNickname() {
+ return nickname;
+ }
+
+ public boolean isInited() {
+ return (userFlags & USER_FLAG_INITED) != 0;
+ }
+
+ public boolean isSnoozed() {
+ return (userFlags & USER_FLAG_SNOOZED) != 0;
+ }
+
+ public void dump(IndentingPrintWriter pw) {
+ pw.println("VolumeRecord:");
+ pw.increaseIndent();
+ pw.printPair("type", DebugUtils.valueToString(VolumeInfo.class, "TYPE_", type));
+ pw.printPair("fsUuid", fsUuid);
+ pw.printPair("nickname", nickname);
+ pw.printPair("userFlags",
+ DebugUtils.flagsToString(VolumeRecord.class, "USER_FLAG_", userFlags));
+ pw.decreaseIndent();
+ pw.println();
+ }
+
+ @Override
+ public VolumeRecord clone() {
+ final Parcel temp = Parcel.obtain();
+ try {
+ writeToParcel(temp, 0);
+ temp.setDataPosition(0);
+ return CREATOR.createFromParcel(temp);
+ } finally {
+ temp.recycle();
+ }
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (o instanceof VolumeRecord) {
+ return Objects.equals(fsUuid, ((VolumeRecord) o).fsUuid);
+ } else {
+ return false;
+ }
+ }
+
+ @Override
+ public int hashCode() {
+ return fsUuid.hashCode();
+ }
+
+ public static final Creator<VolumeRecord> CREATOR = new Creator<VolumeRecord>() {
+ @Override
+ public VolumeRecord createFromParcel(Parcel in) {
+ return new VolumeRecord(in);
+ }
+
+ @Override
+ public VolumeRecord[] newArray(int size) {
+ return new VolumeRecord[size];
+ }
+ };
+
+ @Override
+ public int describeContents() {
+ return 0;
+ }
+
+ @Override
+ public void writeToParcel(Parcel parcel, int flags) {
+ parcel.writeInt(type);
+ parcel.writeString(fsUuid);
+ parcel.writeString(nickname);
+ parcel.writeInt(userFlags);
+ }
+}
diff --git a/core/java/android/provider/Settings.java b/core/java/android/provider/Settings.java
index 00c851b..293cf6f 100644
--- a/core/java/android/provider/Settings.java
+++ b/core/java/android/provider/Settings.java
@@ -919,6 +919,15 @@ public final class Settings {
= "android.settings.ZEN_MODE_SCHEDULE_RULE_SETTINGS";
/**
+ * Activity Action: Show Zen Mode event rule configuration settings.
+ *
+ * @hide
+ */
+ @SdkConstant(SdkConstantType.ACTIVITY_INTENT_ACTION)
+ public static final String ACTION_ZEN_MODE_EVENT_RULE_SETTINGS
+ = "android.settings.ZEN_MODE_EVENT_RULE_SETTINGS";
+
+ /**
* Activity Action: Show Zen Mode external rule configuration settings.
*
* @hide
diff --git a/core/java/android/security/keymaster/KeyCharacteristics.java b/core/java/android/security/keymaster/KeyCharacteristics.java
index b3a3aad..03248e5 100644
--- a/core/java/android/security/keymaster/KeyCharacteristics.java
+++ b/core/java/android/security/keymaster/KeyCharacteristics.java
@@ -87,6 +87,28 @@ public class KeyCharacteristics implements Parcelable {
return result;
}
+ public Long getLong(int tag) {
+ if (hwEnforced.containsTag(tag)) {
+ return hwEnforced.getLong(tag, -1);
+ } else if (swEnforced.containsTag(tag)) {
+ return swEnforced.getLong(tag, -1);
+ } else {
+ return null;
+ }
+ }
+
+ public long getLong(int tag, long defaultValue) {
+ Long result = getLong(tag);
+ return (result != null) ? result : defaultValue;
+ }
+
+ public List<Long> getLongs(int tag) {
+ List<Long> result = new ArrayList<Long>();
+ result.addAll(hwEnforced.getLongs(tag));
+ result.addAll(swEnforced.getLongs(tag));
+ return result;
+ }
+
public Date getDate(int tag) {
Date result = hwEnforced.getDate(tag, null);
if (result == null) {
@@ -105,11 +127,11 @@ public class KeyCharacteristics implements Parcelable {
}
}
- public boolean getBoolean(KeyCharacteristics keyCharacteristics, int tag) {
- if (keyCharacteristics.hwEnforced.containsTag(tag)) {
- return keyCharacteristics.hwEnforced.getBoolean(tag, false);
+ public boolean getBoolean(int tag) {
+ if (hwEnforced.containsTag(tag)) {
+ return hwEnforced.getBoolean(tag, false);
} else {
- return keyCharacteristics.swEnforced.getBoolean(tag, false);
+ return swEnforced.getBoolean(tag, false);
}
}
}
diff --git a/core/java/android/security/keymaster/KeymasterDefs.java b/core/java/android/security/keymaster/KeymasterDefs.java
index 40baf9c..0e2b8ba 100644
--- a/core/java/android/security/keymaster/KeymasterDefs.java
+++ b/core/java/android/security/keymaster/KeymasterDefs.java
@@ -194,6 +194,9 @@ 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_RESCOPABLE_KEY_NOT_USABLE = -54;
+ public static final int KM_ERROR_CALLER_NONCE_PROHIBITED = -55;
public static final int KM_ERROR_UNIMPLEMENTED = -100;
public static final int KM_ERROR_VERSION_MISMATCH = -101;
public static final int KM_ERROR_UNKNOWN_ERROR = -1000;
@@ -235,6 +238,8 @@ public final class KeymasterDefs {
sErrorCodeToString.put(KM_ERROR_UNSUPPORTED_EC_FIELD, "Unsupported EC field");
sErrorCodeToString.put(KM_ERROR_MISSING_NONCE, "Required IV missing");
sErrorCodeToString.put(KM_ERROR_INVALID_NONCE, "Invalid IV");
+ sErrorCodeToString.put(KM_ERROR_CALLER_NONCE_PROHIBITED,
+ "Caller-provided IV not permitted");
sErrorCodeToString.put(KM_ERROR_UNIMPLEMENTED, "Not implemented");
sErrorCodeToString.put(KM_ERROR_UNKNOWN_ERROR, "Unknown error");
}
diff --git a/core/java/android/service/notification/ZenModeConfig.java b/core/java/android/service/notification/ZenModeConfig.java
index 14e947c..f09f4d2 100644
--- a/core/java/android/service/notification/ZenModeConfig.java
+++ b/core/java/android/service/notification/ZenModeConfig.java
@@ -62,7 +62,7 @@ public class ZenModeConfig implements Parcelable {
Calendar.WEDNESDAY, Calendar.THURSDAY };
public static final int[] WEEKEND_DAYS = { Calendar.FRIDAY, Calendar.SATURDAY };
- public static final int[] MINUTE_BUCKETS = new int[] { 15, 30, 45, 60, 120, 180, 240, 480 };
+ public static final int[] MINUTE_BUCKETS = generateMinuteBuckets();
private static final int SECONDS_MS = 1000;
private static final int MINUTES_MS = 60 * SECONDS_MS;
private static final int ZERO_VALUE_MS = 10 * SECONDS_MS;
@@ -95,7 +95,7 @@ public class ZenModeConfig implements Parcelable {
private static final String MANUAL_TAG = "manual";
private static final String AUTOMATIC_TAG = "automatic";
- private static final String RULE_ATT_ID = "id";
+ private static final String RULE_ATT_ID = "ruleId";
private static final String RULE_ATT_ENABLED = "enabled";
private static final String RULE_ATT_SNOOZING = "snoozing";
private static final String RULE_ATT_NAME = "name";
@@ -201,6 +201,18 @@ public class ZenModeConfig implements Parcelable {
}
}
+ private static int[] generateMinuteBuckets() {
+ final int maxHrs = 12;
+ final int[] buckets = new int[maxHrs + 3];
+ buckets[0] = 15;
+ buckets[1] = 30;
+ buckets[2] = 45;
+ for (int i = 1; i <= maxHrs; i++) {
+ buckets[2 + i] = 60 * i;
+ }
+ return buckets;
+ }
+
public static String sourceToString(int source) {
switch (source) {
case SOURCE_ANYONE:
@@ -267,6 +279,15 @@ public class ZenModeConfig implements Parcelable {
}
}
+ private static long tryParseLong(String value, long defValue) {
+ if (TextUtils.isEmpty(value)) return defValue;
+ try {
+ return Long.valueOf(value);
+ } catch (NumberFormatException e) {
+ return defValue;
+ }
+ }
+
public static ZenModeConfig readXml(XmlPullParser parser, Migration migration)
throws XmlPullParserException, IOException {
int type = parser.getEventType();
@@ -298,10 +319,10 @@ public class ZenModeConfig implements Parcelable {
throw new IndexOutOfBoundsException("bad source in config:" + rt.allowFrom);
}
} else if (MANUAL_TAG.equals(tag)) {
- rt.manualRule = readRuleXml(parser);
+ rt.manualRule = readRuleXml(parser, false /*conditionRequired*/);
} else if (AUTOMATIC_TAG.equals(tag)) {
final String id = parser.getAttributeValue(null, RULE_ATT_ID);
- final ZenRule automaticRule = readRuleXml(parser);
+ final ZenRule automaticRule = readRuleXml(parser, true /*conditionRequired*/);
if (id != null && automaticRule != null) {
rt.automaticRules.put(id, automaticRule);
}
@@ -341,7 +362,7 @@ public class ZenModeConfig implements Parcelable {
out.endTag(null, ZEN_TAG);
}
- public static ZenRule readRuleXml(XmlPullParser parser) {
+ public static ZenRule readRuleXml(XmlPullParser parser, boolean conditionRequired) {
final ZenRule rt = new ZenRule();
rt.enabled = safeBoolean(parser, RULE_ATT_ENABLED, true);
rt.snoozing = safeBoolean(parser, RULE_ATT_SNOOZING, false);
@@ -355,7 +376,7 @@ public class ZenModeConfig implements Parcelable {
rt.conditionId = safeUri(parser, RULE_ATT_CONDITION_ID);
rt.component = safeComponentName(parser, RULE_ATT_COMPONENT);
rt.condition = readConditionXml(parser);
- return rt.condition != null ? rt : null;
+ return rt;
}
public static void writeRuleXml(ZenRule rule, XmlSerializer out) throws IOException {
@@ -556,10 +577,12 @@ public class ZenModeConfig implements Parcelable {
Condition.FLAG_RELEVANT_NOW);
}
- // For built-in conditions
+ // ==== Built-in system conditions ====
+
public static final String SYSTEM_AUTHORITY = "android";
- // Built-in countdown conditions, e.g. condition://android/countdown/1399917958951
+ // ==== Built-in system condition: countdown ====
+
public static final String COUNTDOWN_PATH = "countdown";
public static Uri toCountdownConditionId(long time) {
@@ -586,9 +609,43 @@ public class ZenModeConfig implements Parcelable {
return tryParseCountdownConditionId(conditionId) != 0;
}
- // built-in schedule conditions
+ // ==== Built-in system condition: schedule ====
+
public static final String SCHEDULE_PATH = "schedule";
+ public static Uri toScheduleConditionId(ScheduleInfo schedule) {
+ return new Uri.Builder().scheme(Condition.SCHEME)
+ .authority(SYSTEM_AUTHORITY)
+ .appendPath(SCHEDULE_PATH)
+ .appendQueryParameter("days", toDayList(schedule.days))
+ .appendQueryParameter("start", schedule.startHour + "." + schedule.startMinute)
+ .appendQueryParameter("end", schedule.endHour + "." + schedule.endMinute)
+ .build();
+ }
+
+ public static boolean isValidScheduleConditionId(Uri conditionId) {
+ return tryParseScheduleConditionId(conditionId) != null;
+ }
+
+ public static ScheduleInfo tryParseScheduleConditionId(Uri conditionId) {
+ final boolean isSchedule = conditionId != null
+ && conditionId.getScheme().equals(Condition.SCHEME)
+ && conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY)
+ && conditionId.getPathSegments().size() == 1
+ && conditionId.getPathSegments().get(0).equals(ZenModeConfig.SCHEDULE_PATH);
+ if (!isSchedule) return null;
+ final int[] start = tryParseHourAndMinute(conditionId.getQueryParameter("start"));
+ final int[] end = tryParseHourAndMinute(conditionId.getQueryParameter("end"));
+ if (start == null || end == null) return null;
+ final ScheduleInfo rt = new ScheduleInfo();
+ rt.days = tryParseDayList(conditionId.getQueryParameter("days"), "\\.");
+ rt.startHour = start[0];
+ rt.startMinute = start[1];
+ rt.endHour = end[0];
+ rt.endMinute = end[1];
+ return rt;
+ }
+
public static class ScheduleInfo {
public int[] days;
public int startHour;
@@ -626,39 +683,76 @@ public class ZenModeConfig implements Parcelable {
}
}
- public static Uri toScheduleConditionId(ScheduleInfo schedule) {
+ // ==== Built-in system condition: event ====
+
+ public static final String EVENT_PATH = "event";
+
+ public static Uri toEventConditionId(EventInfo event) {
return new Uri.Builder().scheme(Condition.SCHEME)
.authority(SYSTEM_AUTHORITY)
- .appendPath(SCHEDULE_PATH)
- .appendQueryParameter("days", toDayList(schedule.days))
- .appendQueryParameter("start", schedule.startHour + "." + schedule.startMinute)
- .appendQueryParameter("end", schedule.endHour + "." + schedule.endMinute)
+ .appendPath(EVENT_PATH)
+ .appendQueryParameter("calendar", Long.toString(event.calendar))
+ .appendQueryParameter("attendance", Integer.toString(event.attendance))
+ .appendQueryParameter("reply", Integer.toString(event.reply))
.build();
}
- public static boolean isValidScheduleConditionId(Uri conditionId) {
- return tryParseScheduleConditionId(conditionId) != null;
+ public static boolean isValidEventConditionId(Uri conditionId) {
+ return tryParseEventConditionId(conditionId) != null;
}
- public static ScheduleInfo tryParseScheduleConditionId(Uri conditionId) {
- final boolean isSchedule = conditionId != null
+ public static EventInfo tryParseEventConditionId(Uri conditionId) {
+ final boolean isEvent = conditionId != null
&& conditionId.getScheme().equals(Condition.SCHEME)
&& conditionId.getAuthority().equals(ZenModeConfig.SYSTEM_AUTHORITY)
&& conditionId.getPathSegments().size() == 1
- && conditionId.getPathSegments().get(0).equals(ZenModeConfig.SCHEDULE_PATH);
- if (!isSchedule) return null;
- final int[] start = tryParseHourAndMinute(conditionId.getQueryParameter("start"));
- final int[] end = tryParseHourAndMinute(conditionId.getQueryParameter("end"));
- if (start == null || end == null) return null;
- final ScheduleInfo rt = new ScheduleInfo();
- rt.days = tryParseDayList(conditionId.getQueryParameter("days"), "\\.");
- rt.startHour = start[0];
- rt.startMinute = start[1];
- rt.endHour = end[0];
- rt.endMinute = end[1];
+ && conditionId.getPathSegments().get(0).equals(EVENT_PATH);
+ if (!isEvent) return null;
+ final EventInfo rt = new EventInfo();
+ rt.calendar = tryParseLong(conditionId.getQueryParameter("calendar"), 0L);
+ rt.attendance = tryParseInt(conditionId.getQueryParameter("attendance"), 0);
+ rt.reply = tryParseInt(conditionId.getQueryParameter("reply"), 0);
return rt;
}
+ public static class EventInfo {
+ public static final int ATTENDANCE_REQUIRED_OR_OPTIONAL = 0;
+ public static final int ATTENDANCE_REQUIRED = 1;
+ public static final int ATTENDANCE_OPTIONAL = 2;
+
+ public static final int REPLY_ANY = 0;
+ public static final int REPLY_ANY_EXCEPT_NO = 1;
+ public static final int REPLY_YES = 2;
+
+ public long calendar; // CalendarContract.Calendars._ID, or 0 for any
+ public int attendance;
+ public int reply;
+
+ @Override
+ public int hashCode() {
+ return 0;
+ }
+
+ @Override
+ public boolean equals(Object o) {
+ if (!(o instanceof EventInfo)) return false;
+ final EventInfo other = (EventInfo) o;
+ return calendar == other.calendar
+ && attendance == other.attendance
+ && reply == other.reply;
+ }
+
+ public EventInfo copy() {
+ final EventInfo rt = new EventInfo();
+ rt.calendar = calendar;
+ rt.attendance = attendance;
+ rt.reply = reply;
+ return rt;
+ }
+ }
+
+ // ==== End built-in system conditions ====
+
private static int[] tryParseHourAndMinute(String value) {
if (TextUtils.isEmpty(value)) return null;
final int i = value.indexOf('.');
diff --git a/core/java/android/speech/RecognizerIntent.java b/core/java/android/speech/RecognizerIntent.java
index e991d84..ce94315 100644
--- a/core/java/android/speech/RecognizerIntent.java
+++ b/core/java/android/speech/RecognizerIntent.java
@@ -403,4 +403,12 @@ public class RecognizerIntent {
*/
public static final String EXTRA_SUPPORTED_LANGUAGES =
"android.speech.extra.SUPPORTED_LANGUAGES";
+
+ /**
+ * Optional boolean, to be used with {@link #ACTION_RECOGNIZE_SPEECH},
+ * {@link #ACTION_VOICE_SEARCH_HANDS_FREE}, {@link #ACTION_WEB_SEARCH} to indicate whether to
+ * only use an offline speech recognition engine. The default is false, meaning that either
+ * network or offline recognition engines may be used.
+ */
+ public static final String EXTRA_PREFER_OFFLINE = "android.speech.extra.PREFER_OFFLINE";
}
diff --git a/core/java/android/transition/TransitionInflater.java b/core/java/android/transition/TransitionInflater.java
index a7d9503..ca37d49 100644
--- a/core/java/android/transition/TransitionInflater.java
+++ b/core/java/android/transition/TransitionInflater.java
@@ -214,7 +214,7 @@ public class TransitionInflater {
sConstructors.put(className, constructor);
}
}
-
+ constructor.setAccessible(true);
return constructor.newInstance(mContext, attrs);
}
} catch (InstantiationException e) {
diff --git a/core/java/android/util/EventLog.java b/core/java/android/util/EventLog.java
index aefced8..558b8f5 100644
--- a/core/java/android/util/EventLog.java
+++ b/core/java/android/util/EventLog.java
@@ -74,6 +74,7 @@ public class EventLog {
private static final byte LONG_TYPE = 1;
private static final byte STRING_TYPE = 2;
private static final byte LIST_TYPE = 3;
+ private static final byte FLOAT_TYPE = 4;
/** @param data containing event, read from the system */
/*package*/ Event(byte[] data) {
@@ -106,7 +107,7 @@ public class EventLog {
return mBuffer.getInt(offset);
}
- /** @return one of Integer, Long, String, null, or Object[] of same. */
+ /** @return one of Integer, Long, Float, String, null, or Object[] of same. */
public synchronized Object getData() {
try {
int offset = mBuffer.getShort(HEADER_SIZE_OFFSET);
@@ -130,10 +131,13 @@ public class EventLog {
byte type = mBuffer.get();
switch (type) {
case INT_TYPE:
- return (Integer) mBuffer.getInt();
+ return mBuffer.getInt();
case LONG_TYPE:
- return (Long) mBuffer.getLong();
+ return mBuffer.getLong();
+
+ case FLOAT_TYPE:
+ return mBuffer.getFloat();
case STRING_TYPE:
try {
@@ -180,6 +184,14 @@ public class EventLog {
/**
* Record an event log message.
* @param tag The event type tag code
+ * @param value A value to log
+ * @return The number of bytes written
+ */
+ public static native int writeEvent(int tag, float value);
+
+ /**
+ * Record an event log message.
+ * @param tag The event type tag code
* @param str A value to log
* @return The number of bytes written
*/
diff --git a/core/java/android/view/DisplayListCanvas.java b/core/java/android/view/DisplayListCanvas.java
index eedbc70..46dd857 100644
--- a/core/java/android/view/DisplayListCanvas.java
+++ b/core/java/android/view/DisplayListCanvas.java
@@ -234,25 +234,13 @@ public class DisplayListCanvas extends Canvas {
* Draws the specified display list onto this canvas. The display list can only
* be drawn if {@link android.view.RenderNode#isValid()} returns true.
*
- * @param renderNode The RenderNode to replay.
+ * @param renderNode The RenderNode to draw.
*/
public void drawRenderNode(RenderNode renderNode) {
- drawRenderNode(renderNode, RenderNode.FLAG_CLIP_CHILDREN);
+ nDrawRenderNode(mNativeCanvasWrapper, renderNode.getNativeDisplayList());
}
- /**
- * Draws the specified display list onto this canvas.
- *
- * @param renderNode The RenderNode to replay.
- * @param flags Optional flags about drawing, see {@link RenderNode} for
- * the possible flags.
- */
- public void drawRenderNode(RenderNode renderNode, int flags) {
- nDrawRenderNode(mNativeCanvasWrapper, renderNode.getNativeDisplayList(), flags);
- }
-
- private static native void nDrawRenderNode(long renderer, long renderNode,
- int flags);
+ private static native void nDrawRenderNode(long renderer, long renderNode);
///////////////////////////////////////////////////////////////////////////
// Hardware layer
diff --git a/core/java/android/view/HapticFeedbackConstants.java b/core/java/android/view/HapticFeedbackConstants.java
index cc090ad..6651b83 100644
--- a/core/java/android/view/HapticFeedbackConstants.java
+++ b/core/java/android/view/HapticFeedbackConstants.java
@@ -52,6 +52,11 @@ public class HapticFeedbackConstants {
public static final int CALENDAR_DATE = 5;
/**
+ * The user has touched the screen with a stylus and pressed the stylus button.
+ */
+ public static final int STYLUS_BUTTON_PRESS = 6;
+
+ /**
* This is a private constant. Feel free to renumber as desired.
* @hide
*/
diff --git a/core/java/android/view/LayoutInflater.java b/core/java/android/view/LayoutInflater.java
index 457d6ad..1503728 100644
--- a/core/java/android/view/LayoutInflater.java
+++ b/core/java/android/view/LayoutInflater.java
@@ -946,25 +946,21 @@ public abstract class LayoutInflater {
attrs, R.styleable.Include);
final int id = a.getResourceId(R.styleable.Include_id, View.NO_ID);
final int visibility = a.getInt(R.styleable.Include_visibility, -1);
- final boolean hasWidth = a.hasValue(R.styleable.Include_layout_width);
- final boolean hasHeight = a.hasValue(R.styleable.Include_layout_height);
a.recycle();
- // We try to load the layout params set in the <include /> tag. If
- // they don't exist, we will rely on the layout params set in the
- // included XML file.
- // During a layoutparams generation, a runtime exception is thrown
- // if either layout_width or layout_height is missing. We catch
- // this exception and set localParams accordingly: true means we
- // successfully loaded layout params from the <include /> tag,
- // false means we need to rely on the included layout params.
+ // We try to load the layout params set in the <include /> tag.
+ // If the parent can't generate layout params (ex. missing width
+ // or height for the framework ViewGroups, though this is not
+ // necessarily true of all ViewGroups) then we expect it to throw
+ // a runtime exception.
+ // We catch this exception and set localParams accordingly: true
+ // means we successfully loaded layout params from the <include>
+ // tag, false means we need to rely on the included layout params.
ViewGroup.LayoutParams params = null;
- if (hasWidth && hasHeight) {
- try {
- params = group.generateLayoutParams(attrs);
- } catch (RuntimeException e) {
- // Ignore, just fail over to child attrs.
- }
+ try {
+ params = group.generateLayoutParams(attrs);
+ } catch (RuntimeException e) {
+ // Ignore, just fail over to child attrs.
}
if (params == null) {
params = group.generateLayoutParams(childAttrs);
diff --git a/core/java/android/view/MotionEvent.java b/core/java/android/view/MotionEvent.java
index 5e45c8f..5df596a 100644
--- a/core/java/android/view/MotionEvent.java
+++ b/core/java/android/view/MotionEvent.java
@@ -3180,6 +3180,18 @@ public final class MotionEvent extends InputEvent implements Parcelable {
return (getButtonState() & button) == button;
}
+ /**
+ * Checks if a stylus is being used and if the first stylus button is
+ * pressed.
+ *
+ * @return True if the tool is a stylus and if the first stylus button is
+ * pressed.
+ * @see #BUTTON_SECONDARY
+ */
+ public final boolean isStylusButtonPressed() {
+ return (isButtonPressed(BUTTON_SECONDARY) && getToolType(0) == TOOL_TYPE_STYLUS);
+ }
+
public static final Parcelable.Creator<MotionEvent> CREATOR
= new Parcelable.Creator<MotionEvent>() {
public MotionEvent createFromParcel(Parcel in) {
diff --git a/core/java/android/view/PhoneWindow.java b/core/java/android/view/PhoneWindow.java
index 794c8e7..a3e7a10 100644
--- a/core/java/android/view/PhoneWindow.java
+++ b/core/java/android/view/PhoneWindow.java
@@ -3599,7 +3599,7 @@ public class PhoneWindow extends Window implements MenuBuilder.Callback {
if (!mForcedNavigationBarColor) {
mNavigationBarColor = a.getColor(R.styleable.Window_navigationBarColor, 0xFF000000);
}
- if (a.getBoolean(R.styleable.Window_windowHasLightStatusBar, false)) {
+ if (a.getBoolean(R.styleable.Window_windowLightStatusBar, false)) {
decor.setSystemUiVisibility(
decor.getSystemUiVisibility() | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
}
diff --git a/core/java/android/view/TextureView.java b/core/java/android/view/TextureView.java
index ad34f02..85b22fb 100644
--- a/core/java/android/view/TextureView.java
+++ b/core/java/android/view/TextureView.java
@@ -246,6 +246,9 @@ public class TextureView extends View {
mSurface = null;
mLayer = null;
+ // Make sure if/when new layer gets re-created, transform matrix will
+ // be re-applied.
+ mMatrixChanged = true;
mHadSurface = true;
}
}
@@ -284,11 +287,6 @@ public class TextureView extends View {
return LAYER_TYPE_HARDWARE;
}
- @Override
- boolean hasStaticLayer() {
- return true;
- }
-
/**
* Calling this method has no effect.
*/
diff --git a/core/java/android/view/ThreadedRenderer.java b/core/java/android/view/ThreadedRenderer.java
index 87d5d9a..5017a38 100644
--- a/core/java/android/view/ThreadedRenderer.java
+++ b/core/java/android/view/ThreadedRenderer.java
@@ -360,7 +360,7 @@ public class ThreadedRenderer extends HardwareRenderer {
@Override
boolean copyLayerInto(final HardwareLayer layer, final Bitmap bitmap) {
return nCopyLayerInto(mNativeProxy,
- layer.getDeferredLayerUpdater(), bitmap.getSkBitmap());
+ layer.getDeferredLayerUpdater(), bitmap);
}
@Override
@@ -531,7 +531,7 @@ public class ThreadedRenderer extends HardwareRenderer {
private static native long nCreateTextureLayer(long nativeProxy);
private static native void nBuildLayer(long nativeProxy, long node);
- private static native boolean nCopyLayerInto(long nativeProxy, long layer, long bitmap);
+ private static native boolean nCopyLayerInto(long nativeProxy, long layer, Bitmap bitmap);
private static native void nPushLayerUpdate(long nativeProxy, long layer);
private static native void nCancelLayerUpdate(long nativeProxy, long layer);
private static native void nDetachSurfaceTexture(long nativeProxy, long layer);
diff --git a/core/java/android/view/View.java b/core/java/android/view/View.java
index 7da2da4..81ad5ad 100644
--- a/core/java/android/view/View.java
+++ b/core/java/android/view/View.java
@@ -30,6 +30,7 @@ import android.annotation.Nullable;
import android.annotation.Size;
import android.content.ClipData;
import android.content.Context;
+import android.content.ContextWrapper;
import android.content.Intent;
import android.content.res.ColorStateList;
import android.content.res.Configuration;
@@ -986,6 +987,17 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
*/
static final int DUPLICATE_PARENT_STATE = 0x00400000;
+ /**
+ * <p>
+ * Indicates this view can be stylus button pressed. When stylus button
+ * pressable, a View reacts to stylus button presses by notifiying
+ * the OnStylusButtonPressListener.
+ * </p>
+ * {@hide}
+ */
+ static final int STYLUS_BUTTON_PRESSABLE = 0x00800000;
+
+
/** @hide */
@IntDef({
SCROLLBARS_INSIDE_OVERLAY,
@@ -2591,7 +2603,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
* {@link android.view.WindowManager.LayoutParams#FLAG_TRANSLUCENT_STATUS
* FLAG_TRANSLUCENT_STATUS}.
*
- * @see android.R.attr#windowHasLightStatusBar
+ * @see android.R.attr#windowLightStatusBar
*/
public static final int SYSTEM_UI_FLAG_LIGHT_STATUS_BAR = 0x00002000;
@@ -3269,6 +3281,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
protected OnLongClickListener mOnLongClickListener;
/**
+ * Listener used to dispatch stylus touch and button press events. This field should be made
+ * private, so it is hidden from the SDK.
+ * {@hide}
+ */
+ protected OnStylusButtonPressListener mOnStylusButtonPressListener;
+
+ /**
* Listener used to build the context menu.
* This field should be made private, so it is hidden from the SDK.
* {@hide}
@@ -3359,6 +3378,13 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
private boolean mHasPerformedLongPress;
/**
+ * Whether the stylus button is currently pressed down. This is true when
+ * the stylus is touching the screen and the button has been pressed, this
+ * is false once the stylus has been lifted.
+ */
+ private boolean mInStylusButtonPress = false;
+
+ /**
* The minimum height of the view. We'll try our best to have the height
* of this view to at least this amount.
*/
@@ -3874,6 +3900,12 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
viewFlagMasks |= LONG_CLICKABLE;
}
break;
+ case com.android.internal.R.styleable.View_stylusButtonPressable:
+ if (a.getBoolean(attr, false)) {
+ viewFlagValues |= STYLUS_BUTTON_PRESSABLE;
+ viewFlagMasks |= STYLUS_BUTTON_PRESSABLE;
+ }
+ break;
case com.android.internal.R.styleable.View_saveEnabled:
if (!a.getBoolean(attr, true)) {
viewFlagValues |= SAVE_DISABLED;
@@ -4016,37 +4048,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
final String handlerName = a.getString(attr);
if (handlerName != null) {
- setOnClickListener(new OnClickListener() {
- private Method mHandler;
-
- public void onClick(View v) {
- if (mHandler == null) {
- try {
- mHandler = getContext().getClass().getMethod(handlerName,
- View.class);
- } catch (NoSuchMethodException e) {
- int id = getId();
- String idText = id == NO_ID ? "" : " with id '"
- + getContext().getResources().getResourceEntryName(
- id) + "'";
- throw new IllegalStateException("Could not find a method " +
- handlerName + "(View) in the activity "
- + getContext().getClass() + " for onClick handler"
- + " on view " + View.this.getClass() + idText, e);
- }
- }
-
- try {
- mHandler.invoke(getContext(), View.this);
- } catch (IllegalAccessException e) {
- throw new IllegalStateException("Could not execute non "
- + "public method of the activity", e);
- } catch (InvocationTargetException e) {
- throw new IllegalStateException("Could not execute "
- + "method of the activity", e);
- }
- }
- });
+ setOnClickListener(new DeclaredOnClickListener(this, handlerName));
}
break;
case R.styleable.View_overScrollMode:
@@ -4238,6 +4240,66 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
+ * An implementation of OnClickListener that attempts to lazily load a
+ * named click handling method from a parent or ancestor context.
+ */
+ private static class DeclaredOnClickListener implements OnClickListener {
+ private final View mHostView;
+ private final String mMethodName;
+
+ private Method mMethod;
+
+ public DeclaredOnClickListener(@NonNull View hostView, @NonNull String methodName) {
+ mHostView = hostView;
+ mMethodName = methodName;
+ }
+
+ @Override
+ public void onClick(@NonNull View v) {
+ if (mMethod == null) {
+ mMethod = resolveMethod(mHostView.getContext(), mMethodName);
+ }
+
+ try {
+ mMethod.invoke(mHostView.getContext(), v);
+ } catch (IllegalAccessException e) {
+ throw new IllegalStateException(
+ "Could not execute non-public method for android:onClick", e);
+ } catch (InvocationTargetException e) {
+ throw new IllegalStateException(
+ "Could not execute method for android:onClick", e);
+ }
+ }
+
+ @NonNull
+ private Method resolveMethod(@Nullable Context context, @NonNull String name) {
+ while (context != null) {
+ try {
+ if (!context.isRestricted()) {
+ return context.getClass().getMethod(mMethodName, View.class);
+ }
+ } catch (NoSuchMethodException e) {
+ // Failed to find method, keep searching up the hierarchy.
+ }
+
+ if (context instanceof ContextWrapper) {
+ context = ((ContextWrapper) context).getBaseContext();
+ } else {
+ // Can't search up the hierarchy, null out and fail.
+ context = null;
+ }
+ }
+
+ final int id = mHostView.getId();
+ final String idText = id == NO_ID ? "" : " with id '"
+ + mHostView.getContext().getResources().getResourceEntryName(id) + "'";
+ throw new IllegalStateException("Could not find method " + mMethodName
+ + "(View) in a parent or ancestor Context for android:onClick "
+ + "attribute defined on view " + mHostView.getClass() + idText);
+ }
+ }
+
+ /**
* Non-public constructor for use in testing
*/
View() {
@@ -4309,6 +4371,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
out.append((mViewFlags&SCROLLBARS_VERTICAL) != 0 ? 'V' : '.');
out.append((mViewFlags&CLICKABLE) != 0 ? 'C' : '.');
out.append((mViewFlags&LONG_CLICKABLE) != 0 ? 'L' : '.');
+ out.append((mViewFlags & STYLUS_BUTTON_PRESSABLE) != 0 ? 'S' : '.');
out.append(' ');
out.append((mPrivateFlags&PFLAG_IS_ROOT_NAMESPACE) != 0 ? 'R' : '.');
out.append((mPrivateFlags&PFLAG_FOCUSED) != 0 ? 'F' : '.');
@@ -4804,6 +4867,20 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
+ * Register a callback to be invoked when this view is touched with a stylus and the button is
+ * pressed.
+ *
+ * @param l The callback that will run
+ * @see #setStylusButtonPressable(boolean)
+ */
+ public void setOnStylusButtonPressListener(@Nullable OnStylusButtonPressListener l) {
+ if (!isStylusButtonPressable()) {
+ setStylusButtonPressable(true);
+ }
+ getListenerInfo().mOnStylusButtonPressListener = l;
+ }
+
+ /**
* Register a callback to be invoked when the context menu for this view is
* being built. If this view is not long clickable, it becomes long clickable.
*
@@ -4881,6 +4958,46 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
+ * Call this view's OnStylusButtonPressListener, if it is defined.
+ *
+ * @return True if there was an assigned OnStylusButtonPressListener that consumed the event,
+ * false otherwise.
+ */
+ public boolean performStylusButtonPress() {
+ sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_STYLUS_BUTTON_PRESSED);
+
+ boolean handled = false;
+ ListenerInfo li = mListenerInfo;
+ if (li != null && li.mOnStylusButtonPressListener != null) {
+ handled = li.mOnStylusButtonPressListener.onStylusButtonPress(View.this);
+ }
+ if (handled) {
+ performHapticFeedback(HapticFeedbackConstants.STYLUS_BUTTON_PRESS);
+ }
+ return handled;
+ }
+
+ /**
+ * Checks for a stylus button press and calls the listener.
+ *
+ * @param event The event.
+ * @return True if the event was consumed.
+ */
+ private boolean performStylusActionOnButtonPress(MotionEvent event) {
+ if (isStylusButtonPressable() && !mInStylusButtonPress
+ && !mHasPerformedLongPress && event.isStylusButtonPressed()) {
+ if (performStylusButtonPress()) {
+ mInStylusButtonPress = true;
+ setPressed(true, event.getX(), event.getY());
+ removeTapCallback();
+ removeLongPressCallback();
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
* Performs button-related actions during a touch down event.
*
* @param event The event.
@@ -5670,6 +5787,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
* <li>{@link AccessibilityNodeInfo#setFocused(boolean)},</li>
* <li>{@link AccessibilityNodeInfo#setLongClickable(boolean)},</li>
* <li>{@link AccessibilityNodeInfo#setSelected(boolean)},</li>
+ * <li>{@link AccessibilityNodeInfo#setStylusButtonPressable(boolean)}</li>
* </ul>
* <p>
* Subclasses should override this method, call the super implementation,
@@ -5821,6 +5939,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
structure.setChecked(true);
}
}
+ if (isStylusButtonPressable()) {
+ structure.setStylusButtonPressable(true);
+ }
structure.setClassName(getAccessibilityClassName().toString());
structure.setContentDescription(getContentDescription());
}
@@ -5878,6 +5999,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
structure.setChecked(true);
}
}
+ if (info.isStylusButtonPressable()) {
+ structure.setStylusButtonPressable(true);
+ }
CharSequence cname = info.getClassName();
structure.setClassName(cname != null ? cname.toString() : null);
structure.setContentDescription(info.getContentDescription());
@@ -6007,6 +6131,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
info.setAccessibilityFocused(isAccessibilityFocused());
info.setSelected(isSelected());
info.setLongClickable(isLongClickable());
+ info.setStylusButtonPressable(isStylusButtonPressable());
info.setLiveRegion(getAccessibilityLiveRegion());
// TODO: These make sense only if we are in an AdapterView but all
@@ -6037,6 +6162,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
info.addAction(AccessibilityNodeInfo.ACTION_LONG_CLICK);
}
+ if (isStylusButtonPressable() && isEnabled()) {
+ info.addAction(AccessibilityAction.ACTION_STYLUS_BUTTON_PRESS);
+ }
+
CharSequence text = getIterableTextForAccessibility();
if (text != null && text.length() > 0) {
info.setTextSelection(getAccessibilitySelectionStart(), getAccessibilitySelectionEnd());
@@ -7411,6 +7540,31 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
+ * Indicates whether this view reacts to stylus button press events or not.
+ *
+ * @return true if the view is stylus button pressable, false otherwise
+ * @see #setStylusButtonPressable(boolean)
+ * @attr ref android.R.styleable#View_stylusButtonPressable
+ */
+ public boolean isStylusButtonPressable() {
+ return (mViewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE;
+ }
+
+ /**
+ * Enables or disables stylus button press events for this view. When a view is stylus button
+ * pressable it reacts to the user touching the screen with a stylus and pressing the first
+ * stylus button. This event can launch the listener.
+ *
+ * @param stylusButtonPressable true to make the view react to a stylus button press, false
+ * otherwise
+ * @see #isStylusButtonPressable()
+ * @attr ref android.R.styleable#View_stylusButtonPressable
+ */
+ public void setStylusButtonPressable(boolean stylusButtonPressable) {
+ setFlags(stylusButtonPressable ? STYLUS_BUTTON_PRESSABLE : 0, STYLUS_BUTTON_PRESSABLE);
+ }
+
+ /**
* Sets the pressed state for this view and provides a touch coordinate for
* animation hinting.
*
@@ -7825,7 +7979,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
public void addTouchables(ArrayList<View> views) {
final int viewFlags = mViewFlags;
- if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
+ if (((viewFlags & CLICKABLE) == CLICKABLE || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
+ || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE)
&& (viewFlags & ENABLED_MASK) == ENABLED) {
views.add(this);
}
@@ -8540,6 +8695,12 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
return requestRectangleOnScreen(r, true);
}
} break;
+ case R.id.accessibilityActionStylusButtonPress: {
+ if (isStylusButtonPressable()) {
+ performStylusButtonPress();
+ return true;
+ }
+ } break;
}
return false;
}
@@ -9697,7 +9858,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
return (viewFlags & CLICKABLE) == CLICKABLE
- || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE;
+ || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE
+ || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE;
}
/**
@@ -9780,15 +9942,17 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
final float x = event.getX();
final float y = event.getY();
final int viewFlags = mViewFlags;
+ final int action = event.getAction();
if ((viewFlags & ENABLED_MASK) == DISABLED) {
- if (event.getAction() == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
+ if (action == MotionEvent.ACTION_UP && (mPrivateFlags & PFLAG_PRESSED) != 0) {
setPressed(false);
}
// A disabled view that is clickable still consumes the touch
// events, it just doesn't respond to them.
- return (((viewFlags & CLICKABLE) == CLICKABLE ||
- (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE));
+ return (((viewFlags & CLICKABLE) == CLICKABLE
+ || (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)
+ || (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE);
}
if (mTouchDelegate != null) {
@@ -9798,9 +9962,14 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
if (((viewFlags & CLICKABLE) == CLICKABLE ||
- (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE)) {
- switch (event.getAction()) {
+ (viewFlags & LONG_CLICKABLE) == LONG_CLICKABLE) ||
+ (viewFlags & STYLUS_BUTTON_PRESSABLE) == STYLUS_BUTTON_PRESSABLE) {
+ switch (action) {
case MotionEvent.ACTION_UP:
+ if (mInStylusButtonPress) {
+ mInStylusButtonPress = false;
+ mHasPerformedLongPress = false;
+ }
boolean prepressed = (mPrivateFlags & PFLAG_PREPRESSED) != 0;
if ((mPrivateFlags & PFLAG_PRESSED) != 0 || prepressed) {
// take focus if we don't have it already and we should in
@@ -9854,6 +10023,11 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
case MotionEvent.ACTION_DOWN:
mHasPerformedLongPress = false;
+ mInStylusButtonPress = false;
+
+ if (performStylusActionOnButtonPress(event)) {
+ break;
+ }
if (performButtonActionOnTouchDown(event)) {
break;
@@ -9883,6 +10057,10 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
setPressed(false);
removeTapCallback();
removeLongPressCallback();
+ if (mInStylusButtonPress) {
+ mInStylusButtonPress = false;
+ mHasPerformedLongPress = false;
+ }
break;
case MotionEvent.ACTION_MOVE:
@@ -9898,6 +10076,9 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
setPressed(false);
}
+ } else if (performStylusActionOnButtonPress(event)) {
+ // Check for stylus button press if we're within the view.
+ break;
}
break;
}
@@ -10185,7 +10366,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
if (accessibilityEnabled) {
if ((changed & FOCUSABLE_MASK) != 0 || (changed & VISIBILITY_MASK) != 0
- || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0) {
+ || (changed & CLICKABLE) != 0 || (changed & LONG_CLICKABLE) != 0
+ || (changed & STYLUS_BUTTON_PRESSABLE) != 0) {
if (oldIncludeForAccessibility != includeForAccessibility()) {
notifySubtreeAccessibilityStateChangedIfNeeded();
} else {
@@ -14342,15 +14524,6 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
- * Indicates whether this view has a static layer. A view with layer type
- * {@link #LAYER_TYPE_NONE} is a static layer. Other types of layers are
- * dynamic.
- */
- boolean hasStaticLayer() {
- return true;
- }
-
- /**
* Indicates what type of layer is currently associated with this view. By default
* a view does not have a layer, and the layer type is {@link #LAYER_TYPE_NONE}.
* Refer to the documentation of {@link #setLayerType(int, android.graphics.Paint)}
@@ -15468,12 +15641,8 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
if (drawingWithRenderNode) {
renderNode.setAlpha(alpha * getAlpha() * getTransitionAlpha());
} else if (layerType == LAYER_TYPE_NONE) {
- int layerFlags = Canvas.HAS_ALPHA_LAYER_SAVE_FLAG;
- if ((parentFlags & ViewGroup.FLAG_CLIP_CHILDREN) != 0) {
- layerFlags |= Canvas.CLIP_TO_LAYER_SAVE_FLAG;
- }
canvas.saveLayerAlpha(sx, sy, sx + getWidth(), sy + getHeight(),
- multipliedAlpha, layerFlags);
+ multipliedAlpha);
}
} else {
// Alpha is handled by the child directly, clobber the layer's alpha
@@ -15509,7 +15678,7 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
if (!drawingWithDrawingCache) {
if (drawingWithRenderNode) {
mPrivateFlags &= ~PFLAG_DIRTY_MASK;
- ((DisplayListCanvas) canvas).drawRenderNode(renderNode, parentFlags);
+ ((DisplayListCanvas) canvas).drawRenderNode(renderNode);
} else {
// Fast path for layouts with no backgrounds
if ((mPrivateFlags & PFLAG_SKIP_DRAW) == PFLAG_SKIP_DRAW) {
@@ -20764,6 +20933,20 @@ public class View implements Drawable.Callback, KeyEvent.Callback,
}
/**
+ * Interface definition for a callback to be invoked when a view is touched with a stylus while
+ * the stylus button is pressed.
+ */
+ public interface OnStylusButtonPressListener {
+ /**
+ * Called when a view is touched with a stylus while the stylus button is pressed.
+ *
+ * @param v The view that was touched.
+ * @return true if the callback consumed the stylus button press, false otherwise.
+ */
+ boolean onStylusButtonPress(View v);
+ }
+
+ /**
* Interface definition for a callback to be invoked when the context menu
* for this view is being built.
*/
diff --git a/core/java/android/view/ViewAssistStructure.java b/core/java/android/view/ViewAssistStructure.java
index 346b8ec..fccfbb8 100644
--- a/core/java/android/view/ViewAssistStructure.java
+++ b/core/java/android/view/ViewAssistStructure.java
@@ -40,6 +40,8 @@ public abstract class ViewAssistStructure {
public abstract void setLongClickable(boolean state);
+ public abstract void setStylusButtonPressable(boolean state);
+
public abstract void setFocusable(boolean state);
public abstract void setFocused(boolean state);
diff --git a/core/java/android/view/ViewGroup.java b/core/java/android/view/ViewGroup.java
index 4324e75..d0d4201 100644
--- a/core/java/android/view/ViewGroup.java
+++ b/core/java/android/view/ViewGroup.java
@@ -3505,8 +3505,7 @@ public abstract class ViewGroup extends View implements ViewParent, ViewManager
final View[] children = mChildren;
for (int i = 0; i < count; i++) {
final View child = children[i];
- if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null) &&
- child.hasStaticLayer()) {
+ if (((child.mViewFlags & VISIBILITY_MASK) == VISIBLE || child.getAnimation() != null)) {
recreateChildDisplayList(child);
}
}
diff --git a/core/java/android/view/accessibility/AccessibilityEvent.java b/core/java/android/view/accessibility/AccessibilityEvent.java
index 417e22c..b0dbeca 100644
--- a/core/java/android/view/accessibility/AccessibilityEvent.java
+++ b/core/java/android/view/accessibility/AccessibilityEvent.java
@@ -684,6 +684,11 @@ public final class AccessibilityEvent extends AccessibilityRecord implements Par
public static final int TYPE_WINDOWS_CHANGED = 0x00400000;
/**
+ * Represents the event of a stylus button press on a {@link android.view.View}.
+ */
+ public static final int TYPE_VIEW_STYLUS_BUTTON_PRESSED = 0x00800000;
+
+ /**
* Change type for {@link #TYPE_WINDOW_CONTENT_CHANGED} event:
* The type of change is not defined.
*/
@@ -731,6 +736,7 @@ public final class AccessibilityEvent extends AccessibilityRecord implements Par
* @see #TYPE_TOUCH_INTERACTION_START
* @see #TYPE_TOUCH_INTERACTION_END
* @see #TYPE_WINDOWS_CHANGED
+ * @see #TYPE_VIEW_STYLUS_BUTTON_PRESSED
*/
public static final int TYPES_ALL_MASK = 0xFFFFFFFF;
@@ -1396,6 +1402,14 @@ public final class AccessibilityEvent extends AccessibilityRecord implements Par
builder.append("TYPE_WINDOWS_CHANGED");
eventTypeCount++;
} break;
+ case TYPE_VIEW_STYLUS_BUTTON_PRESSED: {
+ if (eventTypeCount > 0) {
+ builder.append(", ");
+ }
+ builder.append("TYPE_VIEW_STYLUS_BUTTON_PRESSED");
+ eventTypeCount++;
+ }
+ break;
}
}
if (eventTypeCount > 1) {
diff --git a/core/java/android/view/accessibility/AccessibilityNodeInfo.java b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
index 0736ed8..bf4b7ae 100644
--- a/core/java/android/view/accessibility/AccessibilityNodeInfo.java
+++ b/core/java/android/view/accessibility/AccessibilityNodeInfo.java
@@ -520,6 +520,8 @@ public class AccessibilityNodeInfo implements Parcelable {
private static final int BOOLEAN_PROPERTY_CONTENT_INVALID = 0x00010000;
+ private static final int BOOLEAN_PROPERTY_STYLUS_BUTTON_PRESSABLE = 0x00020000;
+
/**
* Bits that provide the id of a virtual descendant of a view.
*/
@@ -1930,6 +1932,30 @@ public class AccessibilityNodeInfo implements Parcelable {
}
/**
+ * Gets whether this node is stylus button pressable.
+ *
+ * @return True if the node is stylus button pressable.
+ */
+ public boolean isStylusButtonPressable() {
+ return getBooleanProperty(BOOLEAN_PROPERTY_STYLUS_BUTTON_PRESSABLE);
+ }
+
+ /**
+ * Sets whether this node is stylus button pressable.
+ * <p>
+ * <strong>Note:</strong> Cannot be called from an
+ * {@link android.accessibilityservice.AccessibilityService}. This class is made immutable
+ * before being delivered to an AccessibilityService.
+ * </p>
+ *
+ * @param stylusButtonPressable True if the node is stylus button pressable.
+ * @throws IllegalStateException If called from an AccessibilityService.
+ */
+ public void setStylusButtonPressable(boolean stylusButtonPressable) {
+ setBooleanProperty(BOOLEAN_PROPERTY_STYLUS_BUTTON_PRESSABLE, stylusButtonPressable);
+ }
+
+ /**
* Gets the node's live region mode.
* <p>
* A live region is a node that contains information that is important for
@@ -3117,6 +3143,7 @@ public class AccessibilityNodeInfo implements Parcelable {
builder.append("; selected: ").append(isSelected());
builder.append("; clickable: ").append(isClickable());
builder.append("; longClickable: ").append(isLongClickable());
+ builder.append("; stylusButtonPressable: ").append(isStylusButtonPressable());
builder.append("; enabled: ").append(isEnabled());
builder.append("; password: ").append(isPassword());
builder.append("; scrollable: ").append(isScrollable());
@@ -3472,6 +3499,12 @@ public class AccessibilityNodeInfo implements Parcelable {
public static final AccessibilityAction ACTION_SCROLL_TO_POSITION =
new AccessibilityAction(R.id.accessibilityActionScrollToPosition, null);
+ /**
+ * Action that stylus button presses the node.
+ */
+ public static final AccessibilityAction ACTION_STYLUS_BUTTON_PRESS =
+ new AccessibilityAction(R.id.accessibilityActionStylusButtonPress, null);
+
private static final ArraySet<AccessibilityAction> sStandardActions = new ArraySet<>();
static {
sStandardActions.add(ACTION_FOCUS);
@@ -3498,6 +3531,7 @@ public class AccessibilityNodeInfo implements Parcelable {
sStandardActions.add(ACTION_SET_TEXT);
sStandardActions.add(ACTION_SHOW_ON_SCREEN);
sStandardActions.add(ACTION_SCROLL_TO_POSITION);
+ sStandardActions.add(ACTION_STYLUS_BUTTON_PRESS);
}
private final int mActionId;
diff --git a/core/java/android/widget/DayPickerPagerAdapter.java b/core/java/android/widget/DayPickerPagerAdapter.java
index 478fa00..d271af2 100644
--- a/core/java/android/widget/DayPickerPagerAdapter.java
+++ b/core/java/android/widget/DayPickerPagerAdapter.java
@@ -286,14 +286,10 @@ class DayPickerPagerAdapter extends PagerAdapter {
return null;
}
- private boolean isCalendarInRange(Calendar value) {
- return value.compareTo(mMinDate) >= 0 && value.compareTo(mMaxDate) <= 0;
- }
-
private final OnDayClickListener mOnDayClickListener = new OnDayClickListener() {
@Override
public void onDayClick(SimpleMonthView view, Calendar day) {
- if (day != null && isCalendarInRange(day)) {
+ if (day != null) {
setSelectedDay(day);
if (mOnDaySelectedListener != null) {
diff --git a/core/java/android/widget/DayPickerView.java b/core/java/android/widget/DayPickerView.java
index 113e597..334afab 100644
--- a/core/java/android/widget/DayPickerView.java
+++ b/core/java/android/widget/DayPickerView.java
@@ -178,6 +178,13 @@ class DayPickerView extends ViewGroup {
});
}
+ private void updateButtonVisibility(int position) {
+ final boolean hasPrev = position > 0;
+ final boolean hasNext = position < (mAdapter.getCount() - 1);
+ mPrevButton.setVisibility(hasPrev ? View.VISIBLE : View.INVISIBLE);
+ mNextButton.setVisibility(hasNext ? View.VISIBLE : View.INVISIBLE);
+ }
+
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final ViewPager viewPager = mViewPager;
@@ -218,12 +225,6 @@ class DayPickerView extends ViewGroup {
final int height = bottom - top;
mViewPager.layout(0, 0, width, height);
- if (mViewPager.getChildCount() < 1) {
- leftButton.setVisibility(View.INVISIBLE);
- rightButton.setVisibility(View.INVISIBLE);
- return;
- }
-
final SimpleMonthView monthView = (SimpleMonthView) mViewPager.getChildAt(0);
final int monthHeight = monthView.getMonthHeight();
final int cellWidth = monthView.getCellWidth();
@@ -235,7 +236,6 @@ class DayPickerView extends ViewGroup {
final int leftIconTop = monthView.getPaddingTop() + (monthHeight - leftDH) / 2;
final int leftIconLeft = monthView.getPaddingLeft() + (cellWidth - leftDW) / 2;
leftButton.layout(leftIconLeft, leftIconTop, leftIconLeft + leftDW, leftIconTop + leftDH);
- leftButton.setVisibility(View.VISIBLE);
final int rightDW = rightButton.getMeasuredWidth();
final int rightDH = rightButton.getMeasuredHeight();
@@ -243,7 +243,6 @@ class DayPickerView extends ViewGroup {
final int rightIconRight = width - monthView.getPaddingRight() - (cellWidth - rightDW) / 2;
rightButton.layout(rightIconRight - rightDW, rightIconTop,
rightIconRight, rightIconTop + rightDH);
- rightButton.setVisibility(View.VISIBLE);
}
public void setDayOfWeekTextAppearance(int resId) {
@@ -399,10 +398,7 @@ class DayPickerView extends ViewGroup {
@Override
public void onPageSelected(int position) {
- mPrevButton.setVisibility(
- position > 0 ? View.VISIBLE : View.INVISIBLE);
- mNextButton.setVisibility(
- position < (mAdapter.getCount() - 1) ? View.VISIBLE : View.INVISIBLE);
+ updateButtonVisibility(position);
}
};
diff --git a/core/java/android/widget/Editor.java b/core/java/android/widget/Editor.java
index 39b9907..35e7389 100644
--- a/core/java/android/widget/Editor.java
+++ b/core/java/android/widget/Editor.java
@@ -62,7 +62,6 @@ import android.text.TextUtils;
import android.text.method.KeyListener;
import android.text.method.MetaKeyKeyListener;
import android.text.method.MovementMethod;
-import android.text.method.PasswordTransformationMethod;
import android.text.method.WordIterator;
import android.text.style.EasyEditSpan;
import android.text.style.SuggestionRangeSpan;
@@ -145,16 +144,16 @@ public class Editor {
InputContentType mInputContentType;
InputMethodState mInputMethodState;
- private static class TextDisplayList {
- RenderNode displayList;
+ private static class TextRenderNode {
+ RenderNode renderNode;
boolean isDirty;
- public TextDisplayList(String name) {
+ public TextRenderNode(String name) {
isDirty = true;
- displayList = RenderNode.create(name, null);
+ renderNode = RenderNode.create(name, null);
}
- boolean needsRecord() { return isDirty || !displayList.isValid(); }
+ boolean needsRecord() { return isDirty || !renderNode.isValid(); }
}
- TextDisplayList[] mTextDisplayLists;
+ TextRenderNode[] mTextRenderNodes;
boolean mFrozenWithFocus;
boolean mSelectionMoved;
@@ -360,10 +359,10 @@ public class Editor {
}
private void destroyDisplayListsData() {
- if (mTextDisplayLists != null) {
- for (int i = 0; i < mTextDisplayLists.length; i++) {
- RenderNode displayList = mTextDisplayLists[i] != null
- ? mTextDisplayLists[i].displayList : null;
+ if (mTextRenderNodes != null) {
+ for (int i = 0; i < mTextRenderNodes.length; i++) {
+ RenderNode displayList = mTextRenderNodes[i] != null
+ ? mTextRenderNodes[i].renderNode : null;
if (displayList != null && displayList.isValid()) {
displayList.destroyDisplayListData();
}
@@ -682,34 +681,6 @@ public class Editor {
}
}
- /**
- * Unlike {@link TextView#textCanBeSelected()}, this method is based on the <i>current</i> state
- * of the TextView. textCanBeSelected() has to be true (this is one of the conditions to have
- * a selection controller (see {@link #prepareCursorControllers()}), but this is not sufficient.
- */
- private boolean canSelectText() {
- return hasSelectionController() && mTextView.getText().length() != 0;
- }
-
- /**
- * It would be better to rely on the input type for everything. A password inputType should have
- * a password transformation. We should hence use isPasswordInputType instead of this method.
- *
- * We should:
- * - Call setInputType in setKeyListener instead of changing the input type directly (which
- * would install the correct transformation).
- * - Refuse the installation of a non-password transformation in setTransformation if the input
- * type is password.
- *
- * However, this is like this for legacy reasons and we cannot break existing apps. This method
- * is useful since it matches what the user can see (obfuscated text or not).
- *
- * @return true if the current transformation method is of the password type.
- */
- private boolean hasPasswordTransformationMethod() {
- return mTextView.getTransformationMethod() instanceof PasswordTransformationMethod;
- }
-
private int getWordStart(int offset) {
// FIXME - For this and similar methods we're not doing anything to check if there's
// a LocaleSpan in the text, this may be something we should try handling or checking for.
@@ -758,11 +729,11 @@ public class Editor {
* successfully performed.
*/
private boolean selectCurrentWord() {
- if (!canSelectText()) {
+ if (!mTextView.canSelectText()) {
return false;
}
- if (hasPasswordTransformationMethod()) {
+ if (mTextView.hasPasswordTransformationMethod()) {
// Always select all on a password field.
// Cut/copy menu entries are not available for passwords, but being able to select all
// is however useful to delete or paste to replace the entire content.
@@ -1467,8 +1438,8 @@ public class Editor {
firstLine, lastLine);
if (layout instanceof DynamicLayout) {
- if (mTextDisplayLists == null) {
- mTextDisplayLists = ArrayUtils.emptyArray(TextDisplayList.class);
+ if (mTextRenderNodes == null) {
+ mTextRenderNodes = ArrayUtils.emptyArray(TextRenderNode.class);
}
DynamicLayout dynamicLayout = (DynamicLayout) layout;
@@ -1489,19 +1460,19 @@ public class Editor {
searchStartIndex);
// Note how dynamic layout's internal block indices get updated from Editor
blockIndices[i] = blockIndex;
- if (mTextDisplayLists[blockIndex] != null) {
- mTextDisplayLists[blockIndex].isDirty = true;
+ if (mTextRenderNodes[blockIndex] != null) {
+ mTextRenderNodes[blockIndex].isDirty = true;
}
searchStartIndex = blockIndex + 1;
}
- if (mTextDisplayLists[blockIndex] == null) {
- mTextDisplayLists[blockIndex] =
- new TextDisplayList("Text " + blockIndex);
+ if (mTextRenderNodes[blockIndex] == null) {
+ mTextRenderNodes[blockIndex] =
+ new TextRenderNode("Text " + blockIndex);
}
- final boolean blockDisplayListIsInvalid = mTextDisplayLists[blockIndex].needsRecord();
- RenderNode blockDisplayList = mTextDisplayLists[blockIndex].displayList;
+ final boolean blockDisplayListIsInvalid = mTextRenderNodes[blockIndex].needsRecord();
+ RenderNode blockDisplayList = mTextRenderNodes[blockIndex].renderNode;
if (i >= indexFirstChangedBlock || blockDisplayListIsInvalid) {
final int blockBeginLine = endOfPreviousBlock + 1;
final int top = layout.getLineTop(blockBeginLine);
@@ -1528,7 +1499,7 @@ public class Editor {
// brings this range of text back to the top left corner of the viewport
displayListCanvas.translate(-left, -top);
layout.drawText(displayListCanvas, blockBeginLine, blockEndLine);
- mTextDisplayLists[blockIndex].isDirty = false;
+ mTextRenderNodes[blockIndex].isDirty = false;
// No need to untranslate, previous context is popped after
// drawDisplayList
} finally {
@@ -1543,8 +1514,7 @@ public class Editor {
blockDisplayList.setLeftTopRightBottom(left, top, right, bottom);
}
- ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList,
- 0 /* no child clipping, our TextView parent enforces it */);
+ ((DisplayListCanvas) canvas).drawRenderNode(blockDisplayList);
endOfPreviousBlock = blockEndLine;
}
@@ -1558,7 +1528,7 @@ public class Editor {
private int getAvailableDisplayListIndex(int[] blockIndices, int numberOfBlocks,
int searchStartIndex) {
- int length = mTextDisplayLists.length;
+ int length = mTextRenderNodes.length;
for (int i = searchStartIndex; i < length; i++) {
boolean blockIndexFound = false;
for (int j = 0; j < numberOfBlocks; j++) {
@@ -1572,7 +1542,7 @@ public class Editor {
}
// No available index found, the pool has to grow
- mTextDisplayLists = GrowingArrayUtils.append(mTextDisplayLists, length, null);
+ mTextRenderNodes = GrowingArrayUtils.append(mTextRenderNodes, length, null);
return length;
}
@@ -1589,7 +1559,7 @@ public class Editor {
* Invalidates all the sub-display lists that overlap the specified character range
*/
void invalidateTextDisplayList(Layout layout, int start, int end) {
- if (mTextDisplayLists != null && layout instanceof DynamicLayout) {
+ if (mTextRenderNodes != null && layout instanceof DynamicLayout) {
final int firstLine = layout.getLineForOffset(start);
final int lastLine = layout.getLineForOffset(end);
@@ -1609,7 +1579,7 @@ public class Editor {
while (i < numberOfBlocks) {
final int blockIndex = blockIndices[i];
if (blockIndex != DynamicLayout.INVALID_BLOCK_INDEX) {
- mTextDisplayLists[blockIndex].isDirty = true;
+ mTextRenderNodes[blockIndex].isDirty = true;
}
if (blockEndLines[i] >= lastLine) break;
i++;
@@ -1618,9 +1588,9 @@ public class Editor {
}
void invalidateTextDisplayList() {
- if (mTextDisplayLists != null) {
- for (int i = 0; i < mTextDisplayLists.length; i++) {
- if (mTextDisplayLists[i] != null) mTextDisplayLists[i].isDirty = true;
+ if (mTextRenderNodes != null) {
+ for (int i = 0; i < mTextRenderNodes.length; i++) {
+ if (mTextRenderNodes[i] != null) mTextRenderNodes[i].isDirty = true;
}
}
}
@@ -1718,7 +1688,7 @@ public class Editor {
return false;
}
- if (!canSelectText() || !mTextView.requestFocus()) {
+ if (!mTextView.canSelectText() || !mTextView.requestFocus()) {
Log.w(TextView.LOG_TAG,
"TextView does not support text selection. Action mode cancelled.");
return false;
@@ -3090,7 +3060,7 @@ public class Editor {
MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
}
- if (canSelectText() && !hasPasswordTransformationMethod()) {
+ if (mTextView.canSelectAllText()) {
menu.add(0, TextView.ID_SELECT_ALL, 0, com.android.internal.R.string.selectAll).
setAlphabeticShortcut('a').
setShowAsAction(
@@ -3847,6 +3817,10 @@ public class Editor {
startSelectionActionModeWithoutSelection();
}
}
+ } else {
+ if (mSelectionActionMode != null) {
+ mSelectionActionMode.invalidateContentRect();
+ }
}
hideAfterDelay();
break;
@@ -4491,7 +4465,7 @@ public class Editor {
private class CorrectionHighlighter {
private final Path mPath = new Path();
- private final Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ private final Paint mPaint = new Paint();
private int mStart, mEnd;
private long mFadingStartTime;
private RectF mTempRectF;
diff --git a/core/java/android/widget/SearchView.java b/core/java/android/widget/SearchView.java
index bbf120a..088adbb 100644
--- a/core/java/android/widget/SearchView.java
+++ b/core/java/android/widget/SearchView.java
@@ -18,6 +18,7 @@ package android.widget;
import static android.widget.SuggestionsAdapter.getColumnString;
+import android.annotation.Nullable;
import android.app.PendingIntent;
import android.app.SearchManager;
import android.app.SearchableInfo;
@@ -120,6 +121,8 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
private final Intent mVoiceWebSearchIntent;
private final Intent mVoiceAppSearchIntent;
+ private final CharSequence mDefaultQueryHint;
+
private OnQueryTextListener mOnQueryChangeListener;
private OnCloseListener mOnCloseListener;
private OnFocusChangeListener mOnQueryTextFocusChangeListener;
@@ -329,10 +332,8 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
setMaxWidth(maxWidth);
}
- final CharSequence queryHint = a.getText(R.styleable.SearchView_queryHint);
- if (!TextUtils.isEmpty(queryHint)) {
- setQueryHint(queryHint);
- }
+ mDefaultQueryHint = a.getText(R.styleable.SearchView_defaultQueryHint);
+ mQueryHint = a.getText(R.styleable.SearchView_queryHint);
final int imeOptions = a.getInt(R.styleable.SearchView_imeOptions, -1);
if (imeOptions != -1) {
@@ -570,36 +571,48 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
}
/**
- * Sets the hint text to display in the query text field. This overrides any hint specified
- * in the SearchableInfo.
- *
- * @param hint the hint text to display
+ * Sets the hint text to display in the query text field. This overrides
+ * any hint specified in the {@link SearchableInfo}.
+ * <p>
+ * This value may be specified as an empty string to prevent any query hint
+ * from being displayed.
*
+ * @param hint the hint text to display or {@code null} to clear
* @attr ref android.R.styleable#SearchView_queryHint
*/
- public void setQueryHint(CharSequence hint) {
+ public void setQueryHint(@Nullable CharSequence hint) {
mQueryHint = hint;
updateQueryHint();
}
/**
- * Gets the hint text to display in the query text field.
- * @return the query hint text, if specified, null otherwise.
+ * Returns the hint text that will be displayed in the query text field.
+ * <p>
+ * The displayed query hint is chosen in the following order:
+ * <ol>
+ * <li>Non-null value set with {@link #setQueryHint(CharSequence)}
+ * <li>Value specified in XML using
+ * {@link android.R.styleable#SearchView_queryHint android:queryHint}
+ * <li>Valid string resource ID exposed by the {@link SearchableInfo} via
+ * {@link SearchableInfo#getHintId()}
+ * <li>Default hint provided by the theme against which the view was
+ * inflated
+ * </ol>
*
+ * @return the displayed query hint text, or {@code null} if none set
* @attr ref android.R.styleable#SearchView_queryHint
*/
+ @Nullable
public CharSequence getQueryHint() {
+ final CharSequence hint;
if (mQueryHint != null) {
- return mQueryHint;
- } else if (mSearchable != null) {
- CharSequence hint = null;
- int hintId = mSearchable.getHintId();
- if (hintId != 0) {
- hint = getContext().getString(hintId);
- }
- return hint;
+ hint = mQueryHint;
+ } else if (mSearchable != null && mSearchable.getHintId() != 0) {
+ hint = getContext().getText(mSearchable.getHintId());
+ } else {
+ hint = mDefaultQueryHint;
}
- return null;
+ return hint;
}
/**
@@ -1113,20 +1126,8 @@ public class SearchView extends LinearLayout implements CollapsibleActionView {
}
private void updateQueryHint() {
- if (mQueryHint != null) {
- mSearchSrcTextView.setHint(getDecoratedHint(mQueryHint));
- } else if (mSearchable != null) {
- CharSequence hint = null;
- int hintId = mSearchable.getHintId();
- if (hintId != 0) {
- hint = getContext().getString(hintId);
- }
- if (hint != null) {
- mSearchSrcTextView.setHint(getDecoratedHint(hint));
- }
- } else {
- mSearchSrcTextView.setHint(getDecoratedHint(""));
- }
+ final CharSequence hint = getQueryHint();
+ mSearchSrcTextView.setHint(getDecoratedHint(hint == null ? "" : hint));
}
/**
diff --git a/core/java/android/widget/SimpleMonthView.java b/core/java/android/widget/SimpleMonthView.java
index 2778f0f..acf1df9 100644
--- a/core/java/android/widget/SimpleMonthView.java
+++ b/core/java/android/widget/SimpleMonthView.java
@@ -31,6 +31,7 @@ import android.text.TextPaint;
import android.text.format.DateFormat;
import android.util.AttributeSet;
import android.util.IntArray;
+import android.util.MathUtils;
import android.util.StateSet;
import android.view.MotionEvent;
import android.view.View;
@@ -422,7 +423,8 @@ class SimpleMonthView extends View {
int stateMask = 0;
- if (day >= mEnabledDayStart && day <= mEnabledDayEnd) {
+ final boolean isDayEnabled = isDayEnabled(day);
+ if (isDayEnabled) {
stateMask |= StateSet.VIEW_STATE_ENABLED;
}
@@ -435,8 +437,11 @@ class SimpleMonthView extends View {
} else if (mTouchedItem == day) {
stateMask |= StateSet.VIEW_STATE_PRESSED;
- // Adjust the circle to be centered on the row.
- canvas.drawCircle(colCenterRtl, rowCenter, mDaySelectorRadius, mDayHighlightPaint);
+ if (isDayEnabled) {
+ // Adjust the circle to be centered on the row.
+ canvas.drawCircle(colCenterRtl, rowCenter,
+ mDaySelectorRadius, mDayHighlightPaint);
+ }
}
final boolean isDayToday = mToday == day;
@@ -460,6 +465,14 @@ class SimpleMonthView extends View {
}
}
+ private boolean isDayEnabled(int day) {
+ return day >= mEnabledDayStart && day <= mEnabledDayEnd;
+ }
+
+ private boolean isValidDayOfMonth(int day) {
+ return day >= 1 && day <= mDaysInMonth;
+ }
+
private static boolean isValidDayOfWeek(int day) {
return day >= Calendar.SUNDAY && day <= Calendar.SATURDAY;
}
@@ -536,13 +549,6 @@ class SimpleMonthView extends View {
mWeekStart = mCalendar.getFirstDayOfWeek();
}
- if (enabledDayStart > 0 && enabledDayEnd < 32) {
- mEnabledDayStart = enabledDayStart;
- }
- if (enabledDayEnd > 0 && enabledDayEnd < 32 && enabledDayEnd >= enabledDayStart) {
- mEnabledDayEnd = enabledDayEnd;
- }
-
// Figure out what day today is.
final Calendar today = Calendar.getInstance();
mToday = -1;
@@ -554,6 +560,9 @@ class SimpleMonthView extends View {
}
}
+ mEnabledDayStart = MathUtils.constrain(enabledDayStart, 1, mDaysInMonth);
+ mEnabledDayEnd = MathUtils.constrain(enabledDayEnd, mEnabledDayStart, mDaysInMonth);
+
// Invalidate the old title.
mTitle = null;
@@ -694,7 +703,7 @@ class SimpleMonthView extends View {
final int col = (paddedXRtl * DAYS_IN_WEEK) / mPaddedWidth;
final int index = col + row * DAYS_IN_WEEK;
final int day = index + 1 - findDayOffset();
- if (day < 1 || day > mDaysInMonth) {
+ if (!isValidDayOfMonth(day)) {
return -1;
}
@@ -708,7 +717,7 @@ class SimpleMonthView extends View {
* @param outBounds the rect to populate with bounds
*/
private boolean getBoundsForDay(int id, Rect outBounds) {
- if (id < 1 || id > mDaysInMonth) {
+ if (!isValidDayOfMonth(id)) {
return false;
}
@@ -742,7 +751,7 @@ class SimpleMonthView extends View {
* @param day the day that was clicked
*/
private boolean onDayClicked(int day) {
- if (day < 0 || day > mDaysInMonth) {
+ if (!isValidDayOfMonth(day) || !isDayEnabled(day)) {
return false;
}
@@ -774,7 +783,7 @@ class SimpleMonthView extends View {
@Override
protected int getVirtualViewAt(float x, float y) {
final int day = getDayAtLocation((int) (x + 0.5f), (int) (y + 0.5f));
- if (day >= 0) {
+ if (day != -1) {
return day;
}
return ExploreByTouchHelper.INVALID_ID;
@@ -808,7 +817,13 @@ class SimpleMonthView extends View {
node.setText(getDayText(virtualViewId));
node.setContentDescription(getDayDescription(virtualViewId));
node.setBoundsInParent(mTempRect);
- node.addAction(AccessibilityAction.ACTION_CLICK);
+
+ final boolean isDayEnabled = isDayEnabled(virtualViewId);
+ if (isDayEnabled) {
+ node.addAction(AccessibilityAction.ACTION_CLICK);
+ }
+
+ node.setEnabled(isDayEnabled);
if (virtualViewId == mActivatedDay) {
// TODO: This should use activated once that's supported.
@@ -835,7 +850,7 @@ class SimpleMonthView extends View {
* @return a description of the virtual view
*/
private CharSequence getDayDescription(int id) {
- if (id >= 1 && id <= mDaysInMonth) {
+ if (isValidDayOfMonth(id)) {
mTempCalendar.set(mYear, mMonth, id);
return DateFormat.format(DATE_FORMAT, mTempCalendar.getTimeInMillis());
}
@@ -850,7 +865,7 @@ class SimpleMonthView extends View {
* @return the visible text of the virtual view
*/
private CharSequence getDayText(int id) {
- if (id >= 1 && id <= mDaysInMonth) {
+ if (isValidDayOfMonth(id)) {
return Integer.toString(id);
}
diff --git a/core/java/android/widget/Switch.java b/core/java/android/widget/Switch.java
index ae779fe..f94f97c 100644
--- a/core/java/android/widget/Switch.java
+++ b/core/java/android/widget/Switch.java
@@ -216,7 +216,7 @@ public class Switch extends CompoundButton {
public Switch(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
- mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
+ mTextPaint = new TextPaint();
final Resources res = getResources();
mTextPaint.density = res.getDisplayMetrics().density;
diff --git a/core/java/android/widget/TextView.java b/core/java/android/widget/TextView.java
index 3e8df08..774a864 100644
--- a/core/java/android/widget/TextView.java
+++ b/core/java/android/widget/TextView.java
@@ -668,11 +668,11 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
final Resources res = getResources();
final CompatibilityInfo compat = res.getCompatibilityInfo();
- mTextPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG);
+ mTextPaint = new TextPaint();
mTextPaint.density = res.getDisplayMetrics().density;
mTextPaint.setCompatibilityScaling(compat.applicationScale);
- mHighlightPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
+ mHighlightPaint = new Paint();
mHighlightPaint.setCompatibilityScaling(compat.applicationScale);
mMovement = getDefaultMovementMethod();
@@ -4569,7 +4569,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
*
* @return true if the current transformation method is of the password type.
*/
- private boolean hasPasswordTransformationMethod() {
+ boolean hasPasswordTransformationMethod() {
return mTransformation instanceof PasswordTransformationMethod;
}
@@ -8583,7 +8583,7 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
* a selection controller (see {@link Editor#prepareCursorControllers()}), but this is not
* sufficient.
*/
- private boolean canSelectText() {
+ boolean canSelectText() {
return mText.length() != 0 && mEditor != null && mEditor.hasSelectionController();
}
@@ -9199,6 +9199,10 @@ public class TextView extends View implements ViewTreeObserver.OnPreDrawListener
return false;
}
+ boolean canSelectAllText() {
+ return canSelectText() && !hasPasswordTransformationMethod();
+ }
+
boolean selectAllText() {
// Need to hide insert point cursor controller before settings selection, otherwise insert
// point cursor controller obtains cursor update event and update cursor with cancelling