Como nas versões anteriores, o Android 17 inclui mudanças de comportamento que podem afetar seu app. As mudanças de comportamento abaixo se aplicam exclusivamente a apps destinados ao Android 17 ou versões mais recentes. Caso seu app seja direcionado ao Android 17 ou a versões mais recentes, faça modificações para oferecer suporte a esses comportamentos, quando aplicável.
Consulte também a lista de mudanças de comportamento que afetam todos os apps
executados no Android 17, independente da targetSdkVersion do app.
Experiência do usuário e interface do sistema
O Android 17 inclui as mudanças a seguir, que têm como objetivo criar uma experiência do usuário mais consistente e intuitiva.
Widget de limite de memória
从 Android 17 开始,系统会对以 Android 17(API 级别 37)或更高版本为目标平台的应用的 RemoteViews 更新强制执行严格的内存限制。当应用将 RemoteViews 对象传递给 AppWidgetManager.updateAppWidget 时,system_server 会计算载荷中每个方向和大小存储桶中所有图片数据的总内存占用。如果总内存超出系统上限 (mMaxWidgetBitmapMemory),系统会拒绝更新并抛出 IllegalArgumentException:
java.lang.IllegalArgumentException: RemoteViews for widget update exceeds maximum bitmap memory usage (used: XXXXX, max: YYYYY)
对于以 API 级别 36 或更低级别为目标平台的应用,系统会将此内存违规行为记录为警告 (Slog.w),而不会抛出异常。
Android skills
在 GitHub 上查看管理 AppWidget 更新和位图内存
android skills add glance-appwidget-updates-and-memory系统如何计算内存上限
系统会将活跃显示配置的 widget 位图内存预算设置为 6 * width * height 字节(1.5 * 4 * width * height,相当于全屏 ARGB_8888 缓冲区大小的 1.5 倍)。在 API 级别 37 及更高级别下,此计算包括以下两项:
- 存储在
RemoteViews.mBitmapCache中的内存中Bitmap和位图支持的Icon对象(Icon.TYPE_BITMAP和Icon.TYPE_ADAPTIVE_BITMAP),例如对setImageViewBitmap、Icon.createWithBitmap、Icon.createWithAdaptiveBitmap或 Jetpack GlanceImageProvider(bitmap)的调用。mBitmapCache中每个唯一的Bitmap或位图支持的Icon实例在每个RemoteViews层次结构中都会被计数一次。 - URI 支持的图片(
Icon.createWithContentUri、setImageViewUri或 GlanceImageProvider(uri))不计入system_server中的RemoteViewsIPC 字节上限,但 widget 宿主进程会以完整分辨率将引用的content://文件解码到其自己的堆中。在通过FileProviderURI 公开降采样图片之前,请务必先将其写入context.cacheDir。
缓解步骤
为了确保在手机、平板电脑和可折叠设备上,微件更新不会超出内存上限,请执行以下操作:
根据
WindowMetrics计算运行时内存预算:在 API 级别 30 及更高级别,从WindowManager.currentWindowMetrics.bounds而不是resources.displayMetrics读取活动窗口边界。在多分辨率设备和可折叠设备上,displayMetrics可能会报告非活动显示屏尺寸。将总微件图片预算估算为6L * bounds.width() * bounds.height(),如以下示例所示:private const val FALLBACK_MAX_BYTES = 15_000_000L fun calculateWidgetMemoryCapBytes(context: Context): Long { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) { val wm = context.getSystemService(WindowManager::class.java) ?: return FALLBACK_MAX_BYTES val bounds = wm.currentWindowMetrics.bounds return 6L * bounds.width().toLong() * bounds.height().toLong() } val dm = context.resources.displayMetrics return 6L * dm.widthPixels.toLong() * dm.heightPixels.toLong() }将图片降采样到微件的可查看尺寸,并使用
RGB_565:使用 2 的幂BitmapFactory.Options.inSampleSize值(大小为微件的最大显示尺寸 [maxWidthDpxmaxHeightDp])解码位图,并对不透明的照片和缩略图使用Bitmap.Config.RGB_565(每个像素2字节)而不是ARGB_8888(每个像素4字节)。在 Jetpack Glance 中,将位图解码提升到
provideContent之外:使用SizeMode.Responsive或SizeMode.Exact时,Glance 会针对每个尺寸分桶调用一次provideContentlambda。在调用provideContent之前,在provideGlance中对每个共享的Bitmap解码一次,以便所有大小存储桶都引用RemoteViews.mBitmapCache中的同一Bitmap实例。替换图片时使用完整的
updateAppWidget调用:在传统AppWidgetProvider实现中,避免调用AppWidgetManager.partiallyUpdateAppWidget来交换Bitmap或Icon视图。部分更新会将新操作合并到system_server中的现有RemoteViews树中,而不会逐出之前缓存的映像操作。构建完整的RemoteViews布局,并改为调用updateAppWidget。提供错误后备布局:在 Jetpack Glance 中,替换
onCompositionError,以便在更新失败时呈现零位图RemoteViews后备。
您可以通过运行以下命令,在已连接的设备上检查微件当前的序列化位图内存用量:
adb shell dumpsys appwidget
Principal recurso
O Android 17 inclui as mudanças abaixo, que modificam ou ampliam vários recursos principais do sistema Android.
Nova implementação sem bloqueio de MessageQueue
A partir do Android 17, os apps destinados ao Android 17 (nível 37 da API)
ou mais recente recebem uma nova implementação sem bloqueio de
android.os.MessageQueue. A nova implementação melhora o desempenho e
reduz os frames perdidos, mas pode causar falhas em clientes que refletem em campos e métodos particulares
de MessageQueue.
Para mais informações, incluindo estratégias de mitigação, consulte as orientações sobre mudanças de comportamento da MessageQueue.
Os campos finais estáticos agora não podem ser modificados
在 Android 17 或更高版本上运行且以 Android 17(API 级别 37)或更高版本为目标平台的应用无法更改 static final 字段。如果应用尝试使用反射来更改 static final 字段,则会导致 IllegalAccessException。尝试通过 JNI API(例如 SetStaticLongField())修改其中一个字段会导致应用崩溃。
Acessibilidade
O Android 17 faz as mudanças abaixo para melhorar a acessibilidade.
Suporte de acessibilidade para digitação complexa em teclado físico com IME
This feature introduces new AccessibilityEvent and TextAttribute
APIs to enhance screen reader spoken feedback for CJKV language input. CJKV IME
apps can now signal whether a text conversion candidate has been selected during
text composition. Apps with edit fields can specify text change types when
sending text changed accessibility events.
For example, apps can specify that a text change occurred during text
composition, or that a text change resulted from a commit.
Doing this enables accessibility
services such as screen readers to deliver more precise feedback based on the
nature of the text modification.
App adoption
IME Apps: When setting composing text in edit fields, IMEs can use
TextAttribute.Builder.setTextSuggestionSelected()to indicate whether a specific conversion candidate was selected.Apps with Edit Fields: Apps that maintain a custom
InputConnectioncan retrieve candidate selection data by callingTextAttribute.isTextSuggestionSelected(). These apps should then callAccessibilityEvent.setTextChangeTypes()when dispatchingTYPE_VIEW_TEXT_CHANGEDevents. Apps targeting Android 17 (API level 37) that use the standardTextViewwill have this feature enabled by default. (That is,TextViewwill handle retrieving data from the IME and setting text change types when sending events to accessibility services).Accessibility Services: Accessibility services that process
TYPE_VIEW_TEXT_CHANGEDevents can callAccessibilityEvent.getTextChangeTypes()to identify the nature of the modification and adjust their feedback strategies accordingly.
Privacidade
O Android 17 inclui as mudanças abaixo para melhorar a privacidade do usuário.
ECH (Encrypted Client Hello) ativado
Android 17 引入了对加密客户端问候 (ECH) 的平台支持,这是一种 TLS 扩展,可通过在 TLS 握手中加密服务器名称指示 (SNI) 来增强用户隐私。这种加密有助于防止网络观察者轻易识别出应用连接到的特定网域。
对于以 Android 17(API 级别 37)或更高版本为目标平台的应用,ECH 用于 TLS 连接。只有在应用使用的网络库(例如 HttpEngine、WebView 或 OkHttp)集成了 ECH 支持,并且远程服务器也支持 ECH 协议时,ECH 才会处于活跃状态。如果无法协商 ECH,客户端会发送包含随机内容的 ECH 扩展程序(一种称为 ECH GREASE 的机制)。如需详细了解 ECH GREASE 的运作方式,请参阅 RFC 9849。
为了允许应用自定义此行为,Android 17 向网络安全配置文件添加了新的 <domainEncryption> 元素。开发者可以在 <base-config> 或 <domain-config> 标记中使用 <domainEncryption>,以全局或按网域选择 ECH 模式(例如 "enabled" 或 "disabled")。
如需了解详情,请参阅加密客户端问候文档。
Permissão de rede local necessária para apps destinados ao Android 17
Android 17 introduces the ACCESS_LOCAL_NETWORK runtime permission
to protect users from unauthorized local network access. Because this falls
under the existing NEARBY_DEVICES permission group, users who have already
granted other NEARBY_DEVICES permissions aren't prompted again. This new
requirement prevents malicious apps from exploiting unrestricted local network
access for covert user tracking and fingerprinting. By declaring and requesting
this permission, your app can discover and connect to devices on the local area
network (LAN), such as smart home devices or casting receivers.
Apps targeting Android 17 (API level 37) or higher now have two paths to maintain communication with LAN devices: Adopt system-mediated, privacy-preserving device pickers to skip the permission prompt, or explicitly request this new permission at runtime to maintain local network communication.
For more information, see the Local network permission documentation.
Ocultar senhas de dispositivos físicos
如果应用以 Android 17(API 级别 37)或更高版本为目标平台,并且用户使用的是实体输入设备(例如外接键盘),则 Android 操作系统会将新的 show_passwords_physical 设置应用于密码字段中的所有字符。默认情况下,该设置会隐藏所有密码字符。
Android 系统会显示最后输入的密码字符,以帮助用户查看是否输错了密码。不过,对于较大的外接键盘,这种需求要小得多。此外,配备外接键盘的设备通常具有更大的显示屏,这会增加他人看到所输入密码的风险。
如果用户使用的是设备的触摸屏,系统会应用新的 show_passwords_touch 设置。
Proteção de OTP para mensagens SMS padrão
Beginning with Android 17, Android is extending its SMS OTP protection
to apply to standard SMS messages (SMS messages containing an OTP that do not
use the WebOTP or SMS Retriever formats). For most apps targeting
Android 17 (API level 37) or higher, these SMS messages do not become
available until three hours after receipt. This delay is intended to help
prevent OTP hijacking. During this three hour delay, the
SMS_RECEIVED_ACTION broadcast is withheld and
SMS provider database queries are filtered. The SMS message is
available to these apps after the delay.
Certain apps such as the default SMS assistant app, connected device companion apps, etc., are exempted from this delay. All apps that rely on reading SMS messages for OTP extraction should transition to using SMS Retriever or SMS User Consent APIs to ensure continued functionality.
Segurança
O Android 17 traz as seguintes melhorias para a segurança de dispositivos e apps.
Segurança de atividades
No Android 17, a plataforma continua a transição para uma arquitetura "segura por padrão", introduzindo um conjunto de melhorias projetadas para mitigar exploits de alta gravidade, como phishing, sequestro de interação e ataques de deputado confuso. Essa atualização exige que os desenvolvedores aceitem explicitamente os novos padrões de segurança para manter a compatibilidade do app e a proteção do usuário.
Os principais impactos para os desenvolvedores incluem:
- Reforço da BAL e melhoria da ativação:estamos refinando as restrições de inicialização de atividades em segundo plano (BAL, na sigla em inglês) ao estender as proteções para
IntentSender. Os desenvolvedores precisam migrar da constante legadaMODE_BACKGROUND_ACTIVITY_START_ALLOWED. Em vez disso, adote controles granulares, comoMODE_BACKGROUND_ACTIVITY_START_ALLOW_IF_VISIBLE, que restringe as inicializações de atividades a cenários em que o app de ligação está visível, reduzindo significativamente a superfície de ataque. - Ferramentas de adoção:os desenvolvedores precisam usar o modo estrito e as verificações de lint atualizadas para identificar padrões legados e garantir a prontidão para os requisitos futuros do SDK de destino.
Ativar CT por padrão
Se um app for direcionado ao Android 17 (nível 37 da API) ou versões mais recentes, a transparência de certificados (CT, na sigla em inglês) será ativada por padrão. No Android 16, a CT está disponível, mas os apps precisavam ativar.
DCL nativa mais segura: C
如果您的应用以 Android 17(API 级别 37)或更高版本为目标平台,Android 14 中针对 DEX 和 JAR 文件引入的更安全的动态代码加载 (DCL) 保护机制现在也适用于原生库。
使用 System.load() 加载的所有原生文件都必须标记为只读。
否则,系统会抛出 UnsatisfiedLinkError。
我们建议应用尽可能避免动态加载代码,因为这样做会大大增加应用因代码注入或代码篡改而遭到入侵的风险。
Restringir campos de PII na visualização de dados do CP2
For apps targeting Android 17 (API level 37) and higher, Contacts Provider 2 (CP2) restricts certain columns containing Personally Identifiable Information (PII) from the data view. When this change is enabled, these columns are removed from the data view to enhance user privacy. The restricted columns include:
Apps that are using these columns from ContactsContract.Data
can extract them from ContactsContract.RawContacts
instead, by joining with RAW_CONTACT_ID.
Aplicar verificações rigorosas de SQL no CP2
对于以 Android 17(API 级别 37)及更高版本为目标平台的应用,如果在没有 READ_CONTACTS 权限的情况下访问 ContactsContract.Data 表,Contacts Provider 2 (CP2) 会强制执行严格的 SQL 查询验证。
做出此项更改后,如果应用没有 READ_CONTACTS 权限,则在查询 ContactsContract.Data 表时会设置 StrictColumns 和 StrictGrammar 选项。如果查询使用的模式与这些模式不兼容,则会被拒绝并导致抛出异常。
Inteligência
O Android 17 inclui as seguintes mudanças na inteligência do sistema.
Descontinuação de setContentCaptureEnabled
Content Capture is enabled by default on certain devices to allow on-device AI features to analyze screen contents for intelligent experiences.
Starting in Android 17, the
ContentCaptureManager.setContentCaptureEnabled(boolean)
API method is deprecated. For apps that target Android 17 (API level 37) or
higher, calling setContentCaptureEnabled(false) no longer disables Content
Capture.
If your app needs to continue disabling Content Capture or restrict screen
contents from being captured by the system, you must transition to using the
FLAG_SECURE window layout parameter.
To disable Content Capture, set the FLAG_SECURE flag on your window as shown
in the following example:
Kotlin
window.setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
)
Java
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_SECURE,
WindowManager.LayoutParams.FLAG_SECURE
);
For more details, see the
WindowManager.LayoutParams.FLAG_SECURE reference
documentation.
Mídia
O Android 17 inclui as seguintes mudanças no comportamento de mídia.
Proteção de áudio em segundo plano
A partir do Android 17, o framework de áudio aplica restrições a interações de áudio em segundo plano, incluindo reprodução de áudio, solicitações de foco de áudio e APIs de mudança de volume para garantir que essas mudanças sejam iniciadas intencionalmente pelo usuário.
Algumas restrições de áudio se aplicam a todos os apps. No entanto, as restrições são mais rigorosas se um app for direcionado ao Android 17 (nível 37 da API). Se um desses apps interagir com áudio enquanto estiver em segundo plano, ele precisará ter um serviço em primeiro plano em execução. Além disso, o app precisa atender a um ou ambos os seguintes requisitos:
- O serviço em primeiro plano precisa ter recursos de uso (WIU, na sigla em inglês).
- O app precisa ter a permissão de alarme exato e interagir com
streams de áudio
USAGE_ALARM.
Para mais informações, incluindo estratégias de mitigação, consulte Proteção de áudio em segundo plano.
Formatos de dispositivo
O Android 17 inclui as mudanças a seguir para melhorar a experiência do usuário em vários tamanhos e formatos de dispositivos.
Mudanças na API Platform para ignorar restrições de orientação, redimensionamento e proporção em telas grandes (sw>=600 dp)
Introduzimos mudanças na API Platform no Android 16 para ignorar restrições de orientação, redimensionamento e proporção em telas grandes (sw >= 600 dp) para apps destinados ao nível 36 ou mais recente da API. Os desenvolvedores têm a opção de desativar essas mudanças com o SDK 36, mas essa desativação não vai estar mais disponível para apps destinados ao Android 17 (nível 37 da API) ou mais recente.
Para mais informações, consulte As restrições de orientação e redimensionamento são ignoradas.
Conectividade
O Android 17 apresenta a mudança abaixo para melhorar a consistência e
se alinhar ao comportamento padrão do Java InputStream para soquetes RFCOMM Bluetooth.
Comportamento consistente de read() do BluetoothSocket para RFCOMM
对于以 Android 17(API 级别 37)为目标平台的应用,当套接字关闭或连接断开时,从基于 RFCOMM 的 BluetoothSocket 获取的 InputStream 的 read() 方法现在会返回 -1。
此项变更使 RFCOMM 套接字行为与 LE CoC 套接字保持一致,并与标准 InputStream.read() 文档保持一致,该文档指出,当到达数据流末尾时,会返回 -1。
仅依赖于捕获 IOException 来跳出读取循环的应用可能会受到此变更的影响,应更新 BluetoothSocket 读取循环,以明确检查返回值是否为 -1。这样可确保在远程设备断开连接或套接字关闭时,循环正确终止。如需查看推荐实现的示例,请参阅传输蓝牙数据指南中的代码段。