Assim como nas versões anteriores, o Android 15 inclui mudanças de comportamento que podem afetar seu app. As mudanças de comportamento a seguir se aplicam exclusivamente a apps destinados ao Android 15 ou versões mais recentes. Caso seu app seja direcionado ao Android 15 ou a versões mais recentes, faça modificações para oferecer suporte a esses comportamentos de forma adequada, quando aplicável.
Consulte também a lista de mudanças de comportamento que afetam todos os apps
executados no Android 15, independente da targetSdkVersion do seu app.
Principal recurso
O Android 15 modifica ou expande vários recursos principais do sistema Android.
Mudanças nos serviços em primeiro plano
Estamos fazendo as seguintes mudanças nos serviços em primeiro plano com o Android 15.
- Comportamento de tempo limite do serviço em primeiro plano de sincronização de dados
- Novo tipo de serviço em primeiro plano de processamento de mídia
- Restrições para broadcast receivers
BOOT_COMPLETEDque iniciam serviços em primeiro plano - Restrições para iniciar serviços em primeiro plano enquanto um app tem a permissão
SYSTEM_ALERT_WINDOW
Comportamento de tempo limite do serviço em primeiro plano da sincronização de dados
Android 15 introduces a new timeout behavior to dataSync for apps targeting
Android 15 (API level 35) or higher. This behavior also applies to the new
mediaProcessing foreground service type.
The system permits an app's dataSync services to run for a total of 6 hours
in a 24-hour period, after which the system calls the running service's
Service.onTimeout(int, int) method (introduced in Android
15). At this time, the service has a few seconds to call
Service.stopSelf(). When Service.onTimeout() is called, the
service is no longer considered a foreground service. If the service does not
call Service.stopSelf(), the system throws an internal exception. The
exception is logged in Logcat with the following message:
Fatal Exception: android.app.RemoteServiceException: "A foreground service of
type dataSync did not stop within its timeout: [component name]"
To avoid problems with this behavior change, you can do one or more of the following:
- Have your service implement the new
Service.onTimeout(int, int)method. When your app receives the callback, make sure to callstopSelf()within a few seconds. (If you don't stop the app right away, the system generates a failure.) - Make sure your app's
dataSyncservices don't run for more than a total of 6 hours in any 24-hour period (unless the user interacts with the app, resetting the timer). - Only start
dataSyncforeground services as a result of direct user interaction; since your app is in the foreground when the service starts, your service has the full six hours after the app goes to the background. - Instead of using a
dataSyncforeground service, use an alternative API.
If your app's dataSync foreground services have run for 6 hours in the last
24, you cannot start another dataSync foreground service unless the user
has brought your app to the foreground (which resets the timer). If you try to
start another dataSync foreground service, the system throws
ForegroundServiceStartNotAllowedException
with an error message like "Time limit already exhausted for foreground service
type dataSync".
Testing
To test your app's behavior, you can enable data sync timeouts even if your app
is not targeting Android 15 (as long as the app is running on an Android 15
device). To enable timeouts, run the following adb command:
adb shell am compat enable FGS_INTRODUCE_TIME_LIMITS your-package-name
You can also adjust the timeout period, to make it easier to test how your
app behaves when the limit is reached. To set a new timeout period, run the
following adb command:
adb shell device_config put activity_manager data_sync_fgs_timeout_duration duration-in-milliseconds
Novo tipo de serviço em primeiro plano de processamento de mídia
Android 15 introduces a new foreground service type, mediaProcessing. This
service type is appropriate for operations like transcoding media files. For
example, a media app might download an audio file and need to convert it to a
different format before playing it. You can use a mediaProcessing foreground
service to make sure the conversion continues even while the app is in the
background.
The system permits an app's mediaProcessing services to run for a total of 6
hours in a 24-hour period, after which the system calls the running service's
Service.onTimeout(int, int) method (introduced in Android
15). At this time, the service has a few seconds to call
Service.stopSelf(). If the service does not
call Service.stopSelf(), the system throws an internal exception. The
exception is logged in Logcat with the following message:
Fatal Exception: android.app.RemoteServiceException: "A foreground service of
type mediaProcessing did not stop within its timeout: [component name]"
To avoid having the exception, you can do one of the following:
- Have your service implement the new
Service.onTimeout(int, int)method. When your app receives the callback, make sure to callstopSelf()within a few seconds. (If you don't stop the app right away, the system generates a failure.) - Make sure your app's
mediaProcessingservices don't run for more than a total of 6 hours in any 24-hour period (unless the user interacts with the app, resetting the timer). - Only start
mediaProcessingforeground services as a result of direct user interaction; since your app is in the foreground when the service starts, your service has the full six hours after the app goes to the background. - Instead of using a
mediaProcessingforeground service, use an alternative API, like WorkManager.
If your app's mediaProcessing foreground services have run for 6 hours in the
last 24, you cannot start another mediaProcessing foreground service unless
the user has brought your app to the foreground (which resets the timer). If you
try to start another mediaProcessing foreground service, the system throws
ForegroundServiceStartNotAllowedException
with an error message like "Time limit already exhausted for foreground service
type mediaProcessing".
For more information about the mediaProcessing service type, see Changes to
foreground service types for Android 15: Media processing.
Testing
To test your app's behavior, you can enable media processing timeouts even if
your app is not targeting Android 15 (as long as the app is running on an
Android 15 device). To enable timeouts, run the following adb command:
adb shell am compat enable FGS_INTRODUCE_TIME_LIMITS your-package-name
You can also adjust the timeout period, to make it easier to test how your
app behaves when the limit is reached. To set a new timeout period, run the
following adb command:
adb shell device_config put activity_manager media_processing_fgs_timeout_duration duration-in-milliseconds
Restrições em broadcast receivers BOOT_COMPLETED que iniciam serviços em primeiro plano
Há novas restrições para inicialização de broadcast receivers BOOT_COMPLETED
serviços em primeiro plano. Receptores BOOT_COMPLETED não têm permissão para iniciar o
seguintes tipos de serviços em primeiro plano:
dataSynccameramediaPlaybackphoneCallmediaProjectionmicrophone(esta restrição está em vigor paramicrophonedesde o Android 14)
Se um receptor BOOT_COMPLETED tentar iniciar qualquer um desses tipos de primeiro plano
serviços, o sistema gera ForegroundServiceStartNotAllowedException.
Teste
Para testar o comportamento do app, ative essas novas restrições mesmo que seu
O app não é destinado ao Android 15, desde que seja executado em um Android 15
dispositivo). Execute o seguinte comando adb:
adb shell am compat enable FGS_BOOT_COMPLETED_RESTRICTIONS your-package-name
Para enviar uma transmissão BOOT_COMPLETED sem reiniciar o dispositivo:
Execute o seguinte comando adb:
adb shell am broadcast -a android.intent.action.BOOT_COMPLETED your-package-name
Restrições para iniciar serviços em primeiro plano enquanto um app tem a permissão SYSTEM_ALERT_WINDOW
Anteriormente, se um app tivesse a permissão SYSTEM_ALERT_WINDOW, ele poderia iniciar
um serviço em primeiro plano mesmo que estivesse em segundo plano (conforme
discutido em isenção de restrições de início em segundo plano).
Se um app for destinado ao Android 15, essa isenção será mais restrita. Agora o app precisa
ter a permissão SYSTEM_ALERT_WINDOW e também ter uma janela de sobreposição
visível. Ou seja, o app precisa primeiro abrir uma
janela TYPE_APPLICATION_OVERLAY e a janela
precisa estar visível antes de iniciar um serviço em primeiro plano.
Se o app tentar iniciar um serviço em primeiro plano em segundo plano sem
atender a esses novos requisitos (e não tiver outra isenção), o
sistema vai gerar uma ForegroundServiceStartNotAllowedException.
Se o app declarar a permissão SYSTEM_ALERT_WINDOW
e iniciar serviços em primeiro plano em segundo plano, ele poderá ser afetado por essa
mudança. Se o app receber uma ForegroundServiceStartNotAllowedException, verifique
a ordem das operações e verifique se ele já tem uma janela de sobreposição
ativa antes de tentar iniciar um serviço em primeiro plano em segundo
plano. Você pode conferir se a janela de sobreposição está visível
chamando View.getWindowVisibility() ou
substituir View.onWindowVisibilityChanged()
para receber uma notificação sempre que a visibilidade mudar.
Teste
Para testar o comportamento do app, ative essas novas restrições mesmo que ele
não seja direcionado ao Android 15, desde que esteja sendo executado em um dispositivo
Android 15. Para ativar essas novas restrições na inicialização de serviços em primeiro plano
em segundo plano, execute este comando adb:
adb shell am compat enable FGS_SAW_RESTRICTIONS your-package-name
Mudanças em quando os apps podem modificar o estado global do modo Não perturbe
以 Android 15(API 级别 35)及更高版本为目标平台的应用无法再更改设备上的勿扰 (DND) 功能的全局状态或政策(无论是通过修改用户设置还是关闭勿扰模式)。相反,应用必须提供 AutomaticZenRule,系统会将其与现有的“最严格的政策优先”方案合并为一个全局政策。对之前会影响全局状态的现有 API 的调用(setInterruptionFilter、setNotificationPolicy)会导致创建或更新隐式 AutomaticZenRule,该 AutomaticZenRule 会根据这些 API 调用的调用周期开启和关闭。
请注意,只有当应用调用 setInterruptionFilter(INTERRUPTION_FILTER_ALL) 并希望该调用停用之前由其所有者激活的 AutomaticZenRule 时,此更改才会影响可观察到的行为。
Mudanças na API OpenJDK
Android 15 continues the work of refreshing Android's core libraries to align with the features in the latest OpenJDK LTS releases.
Some of these changes can affect app compatibility for apps targeting Android 15 (API level 35):
Changes to string formatting APIs: Validation of argument index, flags, width, and precision are now more strict when using the following
String.format()andFormatter.format()APIs:String.format(String, Object[])String.format(Locale, String, Object[])Formatter.format(String, Object[])Formatter.format(Locale, String, Object[])
For example, the following exception is thrown when an argument index of 0 is used (
%0in the format string):IllegalFormatArgumentIndexException: Illegal format argument index = 0In this case, the issue can be fixed by using an argument index of 1 (
%1in the format string).Changes to component type of
Arrays.asList(...).toArray(): When usingArrays.asList(...).toArray(), the component type of the resulting array is now anObject—not the type of the underlying array's elements. So the following code throws aClassCastException:String[] elements = (String[]) Arrays.asList("one", "two").toArray();For this case, to preserve
Stringas the component type in the resulting array, you could useCollection.toArray(Object[])instead:String[] elements = Arrays.asList("two", "one").toArray(new String[0]);Changes to language code handling: When using the
LocaleAPI, language codes for Hebrew, Yiddish, and Indonesian are no longer converted to their obsolete forms (Hebrew:iw, Yiddish:ji, and Indonesian:in). When specifying the language code for one of these locales, use the codes from ISO 639-1 instead (Hebrew:he, Yiddish:yi, and Indonesian:id).Changes to random int sequences: Following the changes made in https://bugs.openjdk.org/browse/JDK-8301574, the following
Random.ints()methods now return a different sequence of numbers than theRandom.nextInt()methods do:Generally, this change shouldn't result in app-breaking behavior, but your code shouldn't expect the sequence generated from
Random.ints()methods to matchRandom.nextInt().
The new SequencedCollection API can affect your app's compatibility
after you update compileSdk in your app's build configuration to use
Android 15 (API level 35):
Collision with
MutableList.removeFirst()andMutableList.removeLast()extension functions inkotlin-stdlibThe
Listtype in Java is mapped to theMutableListtype in Kotlin. Because theList.removeFirst()andList.removeLast()APIs have been introduced in Android 15 (API level 35), the Kotlin compiler resolves function calls, for examplelist.removeFirst(), statically to the newListAPIs instead of to the extension functions inkotlin-stdlib.If an app is re-compiled with
compileSdkset to35andminSdkset to34or lower, and then the app is run on Android 14 and lower, a runtime error is thrown:java.lang.NoSuchMethodError: No virtual method removeFirst()Ljava/lang/Object; in class Ljava/util/ArrayList;The existing
NewApilint option in Android Gradle Plugin can catch these new API usages../gradlew lintMainActivity.kt:41: Error: Call requires API level 35 (current min is 34): java.util.List#removeFirst [NewApi] list.removeFirst()To fix the runtime exception and lint errors, the
removeFirst()andremoveLast()function calls can be replaced withremoveAt(0)andremoveAt(list.lastIndex)respectively in Kotlin. If you're using Android Studio Ladybug | 2024.1.3 or higher, it also provides a quick fix option for these errors.Consider removing
@SuppressLint("NewApi")andlintOptions { disable 'NewApi' }if the lint option has been disabled.Collision with other methods in Java
New methods have been added into the existing types, for example,
ListandDeque. These new methods might not be compatible with the methods with the same name and argument types in other interfaces and classes. In the case of a method signature collision with incompatibility, thejavaccompiler outputs a build-time error. For example:Example error 1:
javac MyList.javaMyList.java:135: error: removeLast() in MyList cannot implement removeLast() in List public void removeLast() { ^ return type void is not compatible with Object where E is a type-variable: E extends Object declared in interface ListExample error 2:
javac MyList.javaMyList.java:7: error: types Deque<Object> and List<Object> are incompatible; public class MyList implements List<Object>, Deque<Object> { both define reversed(), but with unrelated return types 1 errorExample error 3:
javac MyList.javaMyList.java:43: error: types List<E#1> and MyInterface<E#2> are incompatible; public static class MyList implements List<Object>, MyInterface<Object> { class MyList inherits unrelated defaults for getFirst() from types List and MyInterface where E#1,E#2 are type-variables: E#1 extends Object declared in interface List E#2 extends Object declared in interface MyInterface 1 errorTo fix these build errors, the class implementing these interfaces should override the method with a compatible return type. For example:
@Override public Object getFirst() { return List.super.getFirst(); }
Segurança
O Android 15 inclui mudanças que promovem a segurança do sistema para proteger apps e usuários contra apps maliciosos.
Versões TLS restritas
Android 15 限制了对 TLS 版本 1.0 和 1.1 的使用。这些版本之前已在 Android 中被弃用,但现在不允许面向 Android 15 的应用使用。
Início de atividades em segundo plano seguras
O Android 15 protege os usuários contra apps maliciosos e oferece mais controle sobre os dispositivos, adicionando mudanças que impedem que apps maliciosos em segundo plano tragam outros apps para o primeiro plano, elevando os privilégios e abusando da interação do usuário. Os lançamentos de atividades em segundo plano estão restritos desde Android 10 (nível 29 da API)
Outras mudanças
Além da restrição para correspondência de UID, estas outras mudanças também foram incluídas:
- Os criadores de
PendingIntentvão bloquear o início de atividades em segundo plano por padrão. Isso ajuda a evitar que os apps criem acidentalmente umPendingIntentque podem ser usados indevidamente por usuários maliciosos. - Não levar um app para o primeiro plano, a menos que o remetente
PendingIntentpermite. Essa mudança tem como objetivo impedir que apps maliciosos abusem da capacidade de iniciar atividades em segundo plano. Por padrão, os apps não podem trazer a pilha de tarefas para o primeiro plano, a menos que o criador permita privilégios de inicialização de atividades em segundo plano ou que o remetente tenha privilégios de inicialização de atividades em segundo plano. - Controlar como a principal atividade de uma pilha de tarefas pode concluir a tarefa. Se o principal atividade finaliza uma tarefa, o Android volta para a tarefa que ativo pela última vez. Além disso, se uma atividade não principal terminar a tarefa, o Android voltar para a tela inicial não vai bloquear o final desse objeto atividades.
- Impedir o lançamento de atividades arbitrárias de outros apps na sua própria tarefa. Essa mudança impede que apps maliciosos façam phishing pelos usuários criando atividades que parecem ser de outros apps.
- Impeça que janelas não visíveis sejam consideradas para atividades em segundo plano é lançado. Isso ajuda a evitar que apps maliciosos abusem de inicializações de atividade em segundo plano para mostrar conteúdo indesejado ou malicioso aos usuários.
Intents mais seguras
O Android 15 apresenta novas medidas de segurança opcionais para tornar as intents mais seguras e mais robusto. Essas mudanças têm como objetivo evitar possíveis vulnerabilidades e o uso indevido de intents que podem ser exploradas por apps maliciosos. Existem duas Principais melhorias na segurança de intents no Android 15:
- Combinar filtros de intent de destino:as intents que visam componentes específicos precisam corresponder com precisão às especificações do filtro de intent do destino. Se você enviar uma intent para iniciar a atividade de outro app, o componente de intent de destino precisa estar alinhado com os filtros de intent declarados da atividade de recebimento.
- As intents precisam ter ações: as intents sem uma ação não vão mais corresponder a nenhum filtro de intent. Isso significa que as intents usadas para iniciar atividades ou serviços precisam ter uma ação claramente definida.
Para verificar como o app responde a essas mudanças, use
StrictMode no app. Para conferir registros detalhados
sobre violações de uso de Intent, adicione o seguinte método:
Kotlin
fun onCreate() { StrictMode.setVmPolicy(VmPolicy.Builder() .detectUnsafeIntentLaunch() .build() ) }
Java
public void onCreate() { StrictMode.setVmPolicy(new VmPolicy.Builder() .detectUnsafeIntentLaunch() .build()); }
Experiência do usuário e interface do sistema
O Android 15 inclui algumas mudanças que visam criar uma experiência do usuário mais consistente e intuitiva.
Mudanças no encarte da janela
There are two changes related to window insets in Android 15: edge-to-edge is enforced by default, and there are also configuration changes, such as the default configuration of system bars.
全面实施政策
Apps are edge-to-edge by default on devices running Android 15 if the app is targeting Android 15 (API level 35).
This is a breaking change that might negatively impact your app's UI. The changes affect the following UI areas:
- Gesture handle navigation bar
- Transparent by default.
- Bottom offset is disabled so content draws behind the system navigation bar unless insets are applied.
setNavigationBarColorandR.attr#navigationBarColorare deprecated and don't affect gesture navigation.setNavigationBarContrastEnforcedandR.attr#navigationBarContrastEnforcedcontinue to have no effect on gesture navigation.
- 3-button navigation
- Opacity set to 80% by default, with color possibly matching the window background.
- Bottom offset disabled so content draws behind the system navigation bar unless insets are applied.
setNavigationBarColorandR.attr#navigationBarColorare set to match the window background by default. The window background must be a color drawable for this default to apply. This API is deprecated but continues to affect 3-button navigation.setNavigationBarContrastEnforcedandR.attr#navigationBarContrastEnforcedis true by default, which adds an 80% opaque background across 3-button navigation.
- Status bar
- Transparent by default.
- The top offset is disabled so content draws behind the status bar unless insets are applied.
setStatusBarColorandR.attr#statusBarColorare deprecated and have no effect on Android 15.setStatusBarContrastEnforcedandR.attr#statusBarContrastEnforcedare deprecated but still have an effect on Android 15.
- Display cutout
layoutInDisplayCutoutModeof non-floating windows must beLAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS.SHORT_EDGES,NEVER, andDEFAULTare interpreted asALWAYSso that users don't see a black bar caused by the display cutout and appear edge-to-edge.
The following example shows an app before and after targeting Android 15 (API level 35), and before and after applying insets. This example is not comprehensive, this might appear differently on Android Auto.
What to check if your app is already edge-to-edge
If your app is already edge-to-edge and applies insets, you are mostly unimpacted, except in the following scenarios. However, even if you think you aren't impacted, we recommend you test your app.
- You have a non-floating window, such as an
Activitythat usesSHORT_EDGES,NEVERorDEFAULTinstead ofLAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS. If your app crashes on launch, this might be due to your splashscreen. You can either upgrade the core splashscreen dependency to 1.2.0-alpha01 or later or setwindow.attributes.layoutInDisplayCutoutMode = WindowManager.LayoutInDisplayCutoutMode.always. - There might be lower-traffic screens with occluded UI. Verify these
less-visited screens don't have occluded UI. Lower-traffic screens include:
- Onboarding or sign-in screens
- Settings pages
What to check if your app is not already edge-to-edge
If your app is not already edge-to-edge, you are most likely impacted. In addition to the scenarios for apps that are already edge-to-edge, you should consider the following:
- If your app uses Material 3 Components (
androidx.compose.material3) in compose, such asTopAppBar,BottomAppBar, andNavigationBar, these components are likely not impacted because they automatically handle insets. - If your app is using Material 2 Components (
androidx.compose.material) in Compose, these components don't automatically handle insets. However, you can get access to the insets and apply them manually. In androidx.compose.material 1.6.0 and later, use thewindowInsetsparameter to apply the insets manually forBottomAppBar,TopAppBar,BottomNavigation, andNavigationRail. Likewise, use thecontentWindowInsetsparameter forScaffold. - If your app uses views and Material Components
(
com.google.android.material), most views-based Material Components such asBottomNavigationView,BottomAppBar,NavigationRailView, orNavigationView, handle insets and require no additional work. However, you need to addandroid:fitsSystemWindows="true"if usingAppBarLayout. - For custom composables, apply the insets manually as padding. If your
content is within a
Scaffold, you can consume insets using theScaffoldpadding values. Otherwise, apply padding using one of theWindowInsets. - If your app is using views and
BottomSheet,SideSheetor custom containers, apply padding usingViewCompat.setOnApplyWindowInsetsListener. ForRecyclerView, apply padding using this listener and also addclipToPadding="false".
What to check if your app must offer custom background protection
If your app must offer custom background protection to 3-button navigation or
the status bar, your app should place a composable or view behind the system bar
using WindowInsets.Type#tappableElement() to get the 3-button
navigation bar height or WindowInsets.Type#statusBars.
Additional edge-to-edge resources
See the Edge to Edge Views and Edge to Edge Compose guides for additional considerations on applying insets.
Deprecated APIs
The following APIs are deprecated but not disabled:
R.attr#enforceStatusBarContrastR.attr#navigationBarColor(for 3 button navigation, with 80% alpha)Window#isStatusBarContrastEnforcedWindow#setNavigationBarColor(for 3 button navigation, with 80% alpha)Window#setStatusBarContrastEnforced
The following APIs are deprecated and disabled:
R.attr#navigationBarColor(for gesture navigation)R.attr#navigationBarDividerColorR.attr#statusBarColorWindow#setDecorFitsSystemWindowsWindow#getNavigationBarColorWindow#getNavigationBarDividerColorWindow#getStatusBarColorWindow#setNavigationBarColor(for gesture navigation)Window#setNavigationBarDividerColorWindow#setStatusBarColor
稳定配置
如果您的应用以 Android 15(API 级别 35)或更高版本为目标平台,Configuration 不再排除系统栏。如果您在 Configuration 类中使用屏幕尺寸进行布局计算,则应根据需要将其替换为更好的替代方案,例如适当的 ViewGroup、WindowInsets 或 WindowMetricsCalculator。
Configuration 自 API 1 起便已开始提供。它通常从 Activity.onConfigurationChanged 中获取。它提供窗口密度、方向和大小等信息。从 Configuration 返回的窗口大小的一个重要特征是,它之前排除了系统栏。
配置大小通常用于资源选择,例如 /res/layout-h500dp,这仍然是一个有效的使用情形。不过,我们一直不建议使用它进行布局计算。如果您正在这样做,请立即远离该设备。您应根据自己的使用场景,将 Configuration 的使用替换为更合适的用法。
如果您使用它来计算布局,请使用适当的 ViewGroup,例如 CoordinatorLayout 或 ConstraintLayout。如果您使用它来确定系统导航栏的高度,请使用 WindowInsets。如果您想知道应用窗口的当前大小,请使用 computeCurrentWindowMetrics。
以下列表介绍了受此变更影响的字段:
Configuration.screenWidthDp和screenHeightDp尺寸不再排除系统栏。Configuration.smallestScreenWidthDp会受到screenWidthDp和screenHeightDp更改的间接影响。Configuration.orientation会受到近乎正方形的设备上screenWidthDp和screenHeightDp更改的间接影响。Display.getSize(Point)间接受到Configuration中的更改影响。此方法已从 API 级别 30 开始弃用。- 自 API 级别 33 以来,
Display.getMetrics()一直以这种方式运行。
O atributo "elegantTextHeight" tem o valor padrão "true".
对于以 Android 15(API 级别 35)为目标平台的应用,elegantTextHeight TextView 属性默认会变为 true,将默认使用的紧凑字体替换为一些具有较大垂直测量的脚本,使其更易于阅读。紧凑字体旨在防止布局中断;Android 13(API 级别 33)允许文本布局利用 fallbackLineSpacing 属性拉伸垂直高度,从而防止许多此类中断。
在 Android 15 中,系统中仍保留了紧凑字体,因此您的应用可以将 elegantTextHeight 设置为 false 以获得与之前相同的行为,但即将发布的版本不太可能支持此字体。因此,如果您的应用支持以下脚本:阿拉伯语、老挝语、缅甸语、泰米尔语、古吉拉特语、卡纳达语、马拉雅拉姆语、奥里亚语、泰卢固语或泰语,请将 elegantTextHeight 设置为 true 以测试您的应用。
elegantTextHeight 行为。
elegantTextHeight 行为。A largura da TextView muda para formas de letras complexas
Nas versões anteriores do Android, algumas fontes cursivas ou linguagens que têm
modelagem complexa podiam desenhar as letras na área do caractere anterior ou seguinte.
Em alguns casos, essas letras eram cortadas na posição inicial ou final.
No Android 15 e versões mais recentes, uma TextView aloca largura para desenhar espaço suficiente
para essas letras e permite que os apps solicitem mais paddings à esquerda para
evitar recortes.
Como essa mudança afeta a forma como um TextView decide a largura, o TextView
aloca mais largura por padrão se o app for destinado ao Android 15 (nível 35 da API) ou
mais recente. Para ativar ou desativar esse comportamento, chame a
API setUseBoundsForWidth em TextView.
Como adicionar o padding à esquerda pode causar um desalinhamento nos layouts atuais, ele
não é adicionado por padrão nem mesmo para apps direcionados ao Android 15 ou mais recente.
No entanto, é possível adicionar um padding extra para evitar o corte chamando
setShiftDrawingOffsetForStartOverhang.
Os exemplos a seguir mostram como essas mudanças podem melhorar o layout de texto para algumas fontes e idiomas.
<TextView android:fontFamily="cursive" android:text="java" />
<TextView android:fontFamily="cursive" android:text="java" android:useBoundsForWidth="true" android:shiftDrawingOffsetForStartOverhang="true" />
<TextView android:text="คอมพิวเตอร์" />
<TextView android:text="คอมพิวเตอร์" android:useBoundsForWidth="true" android:shiftDrawingOffsetForStartOverhang="true" />
Altura da linha padrão sensível à localidade para EditText
在较低版本的 Android 中,文本布局会拉伸文本的高度,以满足与当前语言区域匹配的字体的行高。例如,如果内容是日语,由于日语字体的行高略高于拉丁字体,因此文本的高度会略高。不过,尽管行高存在这些差异,但无论使用的是哪种语言区域,EditText 元素的大小都是统一的,如下图所示:
EditText 元素。EditText 的高度相同,即使这些语言的行高各不相同。对于以 Android 15(API 级别 35)为目标平台的应用,现在为 EditText 预留了最小行高,以匹配指定语言区域的参考字体,如下图所示:
EditText 元素。EditText 的高度现在包含足够的空间来容纳这些语言字体的默认行高。如有需要,您的应用可以将 useLocalePreferredLineHeightForMinimum 属性指定为 false,以恢复之前的行为;您的应用还可以在 Kotlin 和 Java 中使用 setMinimumFontMetrics API 设置自定义最小垂直指标。
Câmera e mídia
O Android 15 faz as seguintes mudanças no comportamento de mídia e câmera para apps direcionados a ele ou a versões mais recentes.
Restrições ao solicitar o foco de áudio
Apps that target Android 15 (API level 35) must be the top app or running a
foreground service in order to request audio focus. If an app
attempts to request focus when it does not meet one of these requirements, the
call returns AUDIOFOCUS_REQUEST_FAILED.
You can learn more about audio focus at Manage audio focus.
Atualização das restrições não SDK
O Android 15 inclui listas atualizadas de interfaces não SDK restritas com base na colaboração com desenvolvedores Android e nos testes internos mais recentes. Antes de restringirmos interfaces não SDK, sempre que possível, garantimos que haja alternativas públicas disponíveis.
Caso seu app não seja destinado ao Android 15, é possível que algumas dessas mudanças não afetem você imediatamente. No entanto, embora seja possível que seu app acesse algumas interfaces não SDK dependendo do nível da API de destino do app, o uso de qualquer método ou campo não SDK sempre apresenta um alto risco de corromper o app.
Se você não souber se seu app usa interfaces não SDK, poderá testá-lo para descobrir. Se ele depende de interfaces não SDK, comece a planejar uma migração para alternativas SDK. No entanto, entendemos que alguns apps têm casos de uso válidos para interfaces não SDK. Se você não encontrar uma alternativa para deixar de usar uma interface não SDK em um recurso no seu app, solicite uma nova API pública.
To learn more about the changes in this release of Android, see Updates to non-SDK interface restrictions in Android 15. To learn more about non-SDK interfaces generally, see Restrictions on non-SDK interfaces.