1 Warning: This sample is currently outdated and you should reference the Java version instead.
2 ============================================================================================
3
4 Android AutofillFramework Sample (Kotlin)
5 =========================================
6
7 This sample demonstrates the use of the Autofill Framework. It includes implementations of client
8 Activities with views that should be autofilled, and a Service that can provide autofill data to
9 client Activities.
10
11 Maintainer's Note
12 ------------------
13 **IMPORTANT:** The Kotlin version of this sample is temporarily out of date. Until this is corrected, you should reference the Java version instead.
14
15 Introduction
16 ------------
17
18 This sample demonstrates the use of the Autofill framework from the service side and the client
19 side. In practice, only a small handful of apps will develop Autofill services because a device
20 will only have one service as default at a time, and there is just a small number of 3rd-party apps
21 providing these services (typically password managers). However, all apps targeting O with any
22 autofillable fields should follow the necessary steps to 1) ensure their views can be autofilled
23 and 2) optimize their autofill performance. Most of the time, there is little to no extra code
24 involved, but the use of custom views and views with virtual child views requires more work.
25
26 The sample's Autofill service is implemented to parse the client's view hierarchy in search of
27 autofillable fields that it has data for. If such fields exist in the hierarchy, the service sends
28 data suggestions to the client to autofill those fields. The client uses the following attributes
29 to specify autofill properties: `importantForAutofill`, `autofillHints`, and `autofillType`.
30 `importantForAutofill` specifies whether the view is autofillable. `autofillHints` is a list of
31 strings that hint to the service **what** data to fill the view with. This sample service only
32 supports the hints listed [here](https://developer.android.com/reference/android/view/View.html#AUTOFILL_HINT_CREDIT_CARD_EXPIRATION_DATE)
33 with the prefix AUTOFILL_HINT_*. `autofillType` tells the service the type of data it expects to
34 receive (i.e. a list index, a date, or a string). Specifying `autofillType` is only necessary
35 when implementing a custom view since all of the provided widgets in the UI toolkit do this for you.
36
37 To set the device's default Autofill service to the one in the sample, edit **Settings** >
38 **System** > **Languages & Input** > **Advanced** > **Auto-fill service** and select the sample
39 app. To edit the service's settings, tap the settings icon next to the **Auto-fill service** list
40 item or open the **Autofill Settings** launcher icon.. Here, you can set whether you want to enable
41 authentication on the entire autofill Response or just on individual autofill datasets. You should
42 also set the master password to unlock authenticated autofill data with.
43
44 **Note:** This sample service stores all autofill data in SharedPreferences and thus is not secure.
45 Be careful about what you store when experimenting with the sample because anyone with root access
46 to your device will be able to view your autofill data.
47
48 The client side of the app has three Activities that each have autofillable fields. The first
49 Activity uses standard views to comprise a login form. Very little needs to be done by the client
50 app to ensure the views get autofilled properly. The second Activity uses a custom view with
51 virtual children, meaning some autofillable child views are not known to the View hierarchy to be
52 child views. Supporting autofill on these child views is a little more involved.
53
54 The following code snippet shows how to signal to the autofill service that a specific
55 autofillable virtual view has come into focus:
56
57 ```kotlin
58 class CustomVirtualView(context: Context, attrs: AttributeSet) : View(context, attrs) {
59 ...
60 // Cache AutofillManager system service
61 private val autofillManager: AutofillManager = context.getSystemService(AutofillManager::class.java)
62 ...
63 // Notify service which virtual view has come into focus.
64 autofillManager.notifyViewEntered(this@CustomVirtualView, id, absBounds)
65 ...
66 // Notify service that a virtual view has left focus.
67 autofillManager.notifyViewExited(this@CustomVirtualView, id)
68 }
69 ```
70
71 Now that the autofillable view has signaled to the service that it has been autofilled, it needs
72 to provide the virtual view hierarchy to the Autofill service. This is done out of the box for
73 views part of the UI toolkit, but you need to implement this yourself if you have the view has
74 virtual child views. The following code example shows the `View` method you have to override in
75 order to provide this view hierarchy data to the Autofill service.
76
77 ```kotlin
78 override fun onProvideAutofillVirtualStructure(structure: ViewStructure, flags: Int) {
79 // Build a ViewStructure to pack in AutoFillService requests.
80 structure.setClassName(javaClass.name)
81 val childrenSize = items.size()
82 Log.d(TAG, "onProvideAutofillVirtualStructure(): flags = " + flags + ", items = "
83 + childrenSize + ", extras: " + bundleToString(structure.extras))
84 var index = structure.addChildCount(childrenSize)
85 // Traverse through the view hierarchy, including virtual child views. For each view, we
86 // need to set the relevant autofill metadata and add it to the ViewStructure.
87 for (i in 0..childrenSize - 1) {
88 val item = items.valueAt(i)
89 Log.d(TAG, "Adding new child at index $index: $item")
90 val child = structure.newChild(index)
91 child.setAutofillId(structure, item.id)
92 child.setAutofillHints(item.hints)
93 child.setAutofillType(item.type)
94 child.setDataIsSensitive(!item.sanitized)
95 child.text = item.text
96 child.setAutofillValue(AutofillValue.forText(item.text))
97 child.setFocused(item.focused)
98 child.setId(item.id, context.packageName, null, item.line.idEntry)
99 child.setClassName(item.className)
100 index++
101 }
102 }
103 ```
104
105 After the service processes the Autofill request and sends back a series of Autofill `Datasets`
106 (wrapped in a `Response` object), the user can pick which `Dataset` they want to autofill their
107 views with. When a `Dataset` is selected, this method is invoked for all of the views that were
108 associated with that `Dataset` by the service. For example, the `Dataset` might contain Autofill
109 values for username, password, birthday, and address. This method would then be invoked on all
110 four of those fields. The following code example shows how the sample app implements the method
111 to deliver a UI update to the appropriate child view after the user makes their selection.
112
113 ```kotlin
114 override fun autofill(values: SparseArray<AutofillValue>) {
115 // User has just selected a Dataset from the list of autofill suggestions.
116 // The Dataset is comprised of a list of AutofillValues, with each AutofillValue meant
117 // to fill a specific autofillable view. Now we have to update the UI based on the
118 // AutofillValues in the list.
119 for (i in 0..values.size() - 1) {
120 val id = values.keyAt(i)
121 val value = values.valueAt(i)
122 items[id]?.let { item ->
123 if (item.editable) {
124 // Set the item's text to the text wrapped in the AutofillValue.
125 item.text = value.textValue
126 } else {
127 // Component not editable, so no-op.
128 }
129 }
130 }
131 postInvalidate()
132 }
133 ```
134
135 Pre-requisites
136 --------------
137
138 - Android SDK Preview O
139 - Android Studio 3.0+
140 - Android Build Tools v26+
141 - Android Support Repository v26+
142 - Gradle v3.0+
143
144 Screenshots
145 -------------
146
147 <img src="screenshots/1_MainPage.png" height="400" alt="Screenshot"/> <img src="screenshots/2_SampleLoginEditTexts.png" height="400" alt="Screenshot"/> <img src="screenshots/3_SampleLoginEditTextsAutofilled.png" height="400" alt="Screenshot"/> <img src="screenshots/4_WelcomeActivity.png" height="400" alt="Screenshot"/> <img src="screenshots/5_SampleLoginCustomVirtualView.png" height="400" alt="Screenshot"/> <img src="screenshots/6_SampleLoginCustomVirtualViewAutofilled.png" height="400" alt="Screenshot"/> <img src="screenshots/7_SampleCheckOutSpinnersAutofillable.png" height="400" alt="Screenshot"/> <img src="screenshots/8_SampleCheckOutSpinnersAutofilled.png" height="400" alt="Screenshot"/> <img src="screenshots/9_SettingsActivity.png" height="400" alt="Screenshot"/> <img src="screenshots/10_AuthNeeded.png" height="400" alt="Screenshot"/> <img src="screenshots/11_AuthActivity.png" height="400" alt="Screenshot"/>
148
149 Getting Started
150 ---------------
151
152 This sample uses the Gradle build system. To build this project, use the
153 "gradlew build" command or use "Import Project" in Android Studio.
154
155 Support
156 -------
157
158 - Google+ Community: https://plus.google.com/communities/105153134372062985968
159 - Stack Overflow: http://stackoverflow.com/questions/tagged/android
160
161 If you've found an error in this sample, please file an issue:
162 https://github.com/googlesamples/android-AutofillFramework
163
164 Patches are encouraged, and may be submitted by forking this project and
165 submitting a pull request through GitHub. Please see CONTRIBUTING.md for more details.
166
167 License
168 -------
169
170 Copyright 2017 The Android Open Source Project, Inc.
171
172 Licensed to the Apache Software Foundation (ASF) under one or more contributor
173 license agreements. See the NOTICE file distributed with this work for
174 additional information regarding copyright ownership. The ASF licenses this
175 file to you under the Apache License, Version 2.0 (the "License"); you may not
176 use this file except in compliance with the License. You may obtain a copy of
177 the License at
178
179 http://www.apache.org/licenses/LICENSE-2.0
180
181 Unless required by applicable law or agreed to in writing, software
182 distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
183 WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
184 License for the specific language governing permissions and limitations under
185 the License.
186