Every Year in September/October, Google holds the Android Dev Summit for about two days, where Google’s technical experts share some of the latest developments and developments in the Android space.

The Android Dev Summit 2021: developer.android.com/events/dev-…

This year’s event went ahead as planned online. This year’s Slogan is “Excellent Apps, Across Devices”, that is to use Jetpack and MAD Skill (Moden Android Development) to develop better applications, And through the Android system landing to more kinds of intelligent devices. More than 30 technical sharing sessions (videos) were held around this theme, covering multiple directions:

  • Android 12
  • 12L
  • Building across screens
  • Kotlin
  • Jetpack
  • Jetpack Compose
  • Android Studio
  • AGP


Android 12


Material You

Android12 had an official push in October. The highlight of Android12 is the redesign of the native OS UI based on the Material You design language. Material You is the third version of Material Design, four years after the previous generation M2

Compared with the previous generation M2, M3 has a larger element area and is more convenient for users to click. At the same time, the rounded corners make the spacing between the side-by-side elements clearer. Personalization is the biggest feature of M3, and this is where the name “You” comes from. Android12 follows the Dynamic Color design principle of M3, the system can grab the colors from the user’s wallpaper, and then apply the Color gradation to the application you develop, the application follows the theme of the different and change the Color, thousands of faces.

Stretch OverScroll

Developer.android.com/training/ge…

Android12 added the Stretch OverScroll Effect, compared with the previous water ripple Effect, scrolling feedback is more real and natural. Developers can use the new getDistance() and onPullDistance() apis to control the strength of OverScoll, You can also override this effect by setting Android :overScrollMode=”never” in the XML.

App Splash Screen

Developer.android.com/guide/topic…

Android12 has added the Splash Screen API, which can automatically insert the Splash Screen before entering the App home page. Of course, its purpose is to reduce the waiting time of the white Screen rather than the advertisement placement. Spash Screen uses the Icon of App as the opening Screen pattern by default. Developers can also customize the opening Screen pattern or even animation by using the API provided by the system. If you want to use SplashScreen on non-Android 12 devices, you can use Jetpack, which also provides the SplashScreen library of the same name, for devices as low as Android 6 (APP 23). Note that if you have custom open screens in your project using Android :windowBackground or CustomActivity, you need to adapt them to avoid double open screens in Android12

Foreground service restrictions

Developer.android.com/guide/compo…

For privacy protection, The background start of Service is prohibited by Android8. The restrictions in Android12 are further strengthened. Except for some special cases, the background start of Service is not allowed. Otherwise it will throw ForegroundServiceStartNotAllowedException anomalies. Services are becoming obsolete and will be replaced by WorkManager

Compatibility Test

Every new Android update brings a number of API behavior changes, and Android12 is no exception. To ensure that your APP behaves properly under these changes, you will generally need to modify targetSDKVersion for targeted testing. Android11 provides compatibility testing tools that can be used to test against changing apis without recompiling APK.

The test tool can be found in Developer Options > App Compatibility Changes


(Android 12 Large Screens)


Developer.android.com/about/versi…

In recent years, Android has seen a rapid growth in large-screen devices, and a new category of foldable phones has emerged in addition to tablets, with Android now running on more than 2.5 million large-screen devices. To improve the use experience of large-screen devices. Android12 is coming with a version optimized for larger screens, named 12L. 12L optimizes the interface for large-screen devices and fold-down screens. For example, it displays two columns of content by default when the screen width is larger than 600DP, introduces a Dock bar similar to Chrome OS, and supports drag-and-drop split-screen functions, as well as launching multiple apps in different Windows at the same time

WindowManager

Medium.com/androiddeve…

To cope with the wider variety of screens, Jetpack provides a WindowManager library that makes it easier for apps to adapt to different screen sizes. Apps in multi-window mode can no longer rely on display.getrealmetrics () to obtain window size. OnConfigurationChanged when screen state changes. Use Windows Manager’s WindoeMetrics to get the exact window size, and then display the current UI in the most appropriate layout according to Windows Class.

Jetpack Compose handles UI changes when OnConfigurationChanged in a more responsive manner, making it ideal for use on 12L devices.

enum class WindowSizeClass { COMPACT, MEDIUM, EXPANDED }

@Composable
fun Activity.rememberWindowSizeClass(a) {
    val configuration = LocalConfiguration.current
    val windowMetrics = remember(configuration) {
        WindowMetricsCalculator.getOrCreate()
            .computeCurrentWindowMetrics(this)}val windowDpSize = with(LocalDensity.current) {
        windowMetrics.bounds.toComposeRect().size.toDpSize()
    }
    val widthWindowSizeClass = when {
        windowDpSize.width < 600.dp -> WindowSizeClass.COMPACT
        windowDpSize.width < 840.dp -> WindowSizeClass.MEDIUM
        else -> WindowSizeClass.EXPANDED
    }

    val heightWindowSizeClass = when {
        windowDpSize.height < 480.dp -> WindowSizeClass.COMPACT
        windowDpSize.height < 900.dp -> WindowSizeClass.MEDIUM
        else -> WindowSizeClass.EXPANDED
    }

    // Use widthWindowSizeClass and heightWindowSizeClass
}
Copy the code

Many of the new technologies shared at the event lost out to Compose in the first place, reflecting Android’s determination to make Compose its preferred UI solution.

Activity embedding

In addition to opening multiple applications in multiple Windows, 12L can also display multiple activities side by side in the same application using XML configuration or by calling the API provided by WindowManager.


Building across screens


Android Ware

The Compose stack uses the idea of a layered design that allows users to migrate to different platforms by replacing local components. For example, in WareOs, only Material and Navigation need to be replaced to achieve wearable DEVICE UI development.

A card, for example, is written in the same way as a mobile phone, except for the addition of a Composable element

AppCard(
    appImage = {        
        Image(painter = painterResource(id = R.drawable.ic_message), ... )        
     },    
     appName = { Text("Messages") },
     time = { Text("12m") },    
     title = { Text("Kim Green") },    
     onClick = { ... },    
     content = {        
        Column(modifier = Modifier.fillMaxWidth()) { 
               Text("On my way!")}},Copy the code

Android for Cars

Android provides two sets of vehicle system Android Auto and Android Automotive OS.

  • Android Auto offers an app experience optimized for drivers. Users create services that connect to their phones on Android Auto, and apps can be displayed on the car in a more optimized interface.
  • Android Automotive OS is an Android-based in-car infotainment system. The in-car system is a standalone Android device optimized for improving the driving experience. Unlike Android Auto, it eliminates the need for a phone and allows users to install apps directly into the car’s system.

Developers can develop automotive applications with cross-platform engineering structures:

  • car_app_commonIt’s a shared part
  • automotive_osandorid_autoThere are two build targets


Kotlin


Kotlin Flow

Medium.com/androiddeve…

In terms of Kotlin, the application of Kotlin Flow in MVVM architecture was recommended in this event. Jetpack-based Lifecycle – KTX extension Flow can be transformed into a Lifeycle-aware component, a good alternative to existing LiveData usage scenarios.

You can only use Flow in the Model layer and still use LiveData in the View layer. Convert Flow to LiveData with flow.asliveData:

// import androidx.lifecycle.asLiveData
class MessagesViewModel(repository: MessageRepository) : ViewModel() {
     val userMessage = repository.userMessage.asLiveData()
     ...   
}
Copy the code

Also can be used directly, of course, the View layer Flow in lifecycleScope. Launch. {} or lifecycleScope launchWheStart {} to collect data to avoid leakage Flow, RepeatOnLifecycle is recommended for performance reasons:

//imprort androidx.lifecycle.repeatOnLifecycle

class MessagesActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?{... lifecycleScope.launch { repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.userMessages.collect { messages -> Listadapter. submitList (messages)}}}}}Copy the code

When the MessagesActivity leaves the STARTED, the coroutine cancels to save resources.

In addition, using stateIn, you can turn a Flow into a StateFlow to ensure downstream sharing of data in the form of heat Flow. During the event, some netizens asked whether there were any scenarios where Flow could not replace LiveData. The official answer was that LiveData could be completely replaced by Flow in addition to its simpler API (and weaker corresponding functions).

KSP

Android-developers.googleblog.com/2021/09/acc…

KSP (Kotlin Symbol Processing) released official version 1.0 in September. Compared with the process of generating Java stubs and then processing annotations based on APT, the underlying KSP is based on Kotlin Compiler Plugin, which eliminates the generation of Java stubs and improves the compilation speed by more than two times. It will also be available in the Kotlin Multiplatform Project in the future. If your Project code has been migrated to Kotlin, then KSP should be preferred for annotation processing in the future.

apply plugin: 'com.google.devtools.ksp'

dependencies {
  ...
  implementation "androidx.room:room-runtime:$room_version"
  kapt "androidx.room:room-compiler:$room_version"
  ksp "androidx.room:room-compiler:$room_version"
}
Copy the code

The configuration of replacing KAPT with KSP is very simple, KSP is already supported by many common frameworks including Room, and Dagger, Hilt, etc will plug into KSP in the future to speed annotation processing.


Jetpack


Room

Medium.com/androiddeve…

In October, Room released 2.4.0 Beta 01, which mainly added two new Features, Auto Migratioins and Multi-Map Relations, and supported annotation processing using KSP.

When the table structure of a database changes, data is not lost through database migration, such as field name changes. Handwritten SQL is required to complete the upgrade. Auto Migrations detects the differences between two table structures to complete the automatic upgrade.

 @Database( version = MusicDatabase.LATEST_VERSION, entities = { Song.class, Artist.class }, autoMigrations = { @AutoMigration ( from = 1, to = 2 )
      },
      exportSchema = true
 )
 public abstract class MusicDatabase extends RoomDatabase {... }Copy the code

In the previous version, Room used @relatioin for the foreign key association. You need to define a Relatioin Class so that you don’t have to write more SQL. Using SQL properly can make it easier to define one-to-many entity relationships.

//Room Relations

data class ArtistAndSongs(`@Embedded
    valArtist: artist,@Relation(...)
    valSongs: List < Song >)@Query("SELECT * FROM Artist")
fun getArtistAndSongs(a): List<ArtistAndSongs>

//Room Multimap

@Query("SELECT * FROM Artist JOIN Song ON Artist.artistName = Song.songArtistName")
fun getAllArtistAndTheirSongsList(a): Map<Artist, List<Song>>
Copy the code

Data structures such as Map

> are also simpler to use
,>

WorkManager

Medium.com/androiddeve…

WorkManager is not only a simple asynchronous task processing framework, but also a complete set of powerful task scheduling solutions, which can effectively replace Service and run long-duration tasks more reliably. The minimum backward compatibility to 6.0, covering a large number of models in the market.

WorkManager 2.6 supports multi-process. With the help of RemoteListenableWorker or RemoteCoroutineWorker, tasks can be run in any specified Process to achieve cross-process monitoring. To cope with the restricted start of Foreground Service of Android12, The setExpedited API is added in WorkManager 2.7, which can start relevant tasks immediately with high quality and is not restricted by background start.

val request = OneTimeWorkRequestBuilder<HighPriorityWorker>()       
   .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)   
   .build() WorkManager.getInstance(context).enqueue(request)
Copy the code

Because CoroutineWorker. SetForeground () and ListenableWorker setForegroundAsync () method provided by the Foreground Service support, In some background to start the ban once invoked, ForegroundServiceStartNotAllowedException abnormal happens, it is need to pay special attention to in the development.

More Components

In addition, Jetpack’s other libraries have recently been released with new versions. Navigation 2.4.0 beta adds support for multiple stack returns, the return stacks of different NavhostFragments can be managed separately; DataStore releases 1.0 as a more secure alternative to using SharedPreferences; CameraX 1.1.0-alpha10 adds utility features such as VideoCapture VideoCapture and exposure compensation; Benchmark 1.1.0- Alpha11 adds Frame Timing, more accurate performance testing, and backward compatibility to API 23.


Jetpack Compose


Compose new androidx.com pose. Material3 library, support the development of the Material You UI theme style.

Material3

Compose.M3 customizes color scheme through ColorScheme, which supports Material You color Scheme design specification.

private val Blue40 = Color(0xff1e40ff)
private val DarkBlue40 = Color(0xff3e41f4)
private val Yellow40 = Color(0xff7d5700)

// Remaining colors from tonal palettes
private val LightColorScheme = lightColorScheme(
    primary = Blue40,    
    secondary = DarkBlue40,    
    tertiary = Yellow40,    
    // error, primaryContainer, onSecondary, etc.
)

private val DarkColorScheme = darkColorScheme(
    primary = Blue80,    
    secondary = DarkBlue80,    
    tertiary = Yellow80,    
    // error, primaryContainer, onSecondary, etc.
)
Copy the code

As above, the light and dark schemes are defined, and the arguments are passed to the MaterialTheme

val darkTheme = isSystemInDarkTheme()

MaterialTheme(
    colorScheme = if (darkTheme) DarkColorScheme else LightColorScheme
) {
    // M3 app content
}
Copy the code

Dynamic Color

Dynamic color is the main feature of Material You, and Dynamic ColoScheme is available on Android12 and subsequent devices:

// Dynamic color is available on Android 12+

val dynamicColor = Build.VERSION.SDK_INT >= Build.VERSION_CODES.S
val colorScheme = when{ dynamicColor && darkTheme -> dynamicDarkColorScheme(LocalContext.current) dynamicColor && ! darkTheme -> dynamicLightColorScheme(LocalContext.current) darkTheme -> DarkColorSchemeelse -> LightColorScheme
}
Copy the code

As shown above, when Dynamic ColorScheme is applied, the UI of App will display the corresponding theme color after selecting red or blue wallpaper


Android Studio


  • Android Studio Arctic Fox is officially available
  • Ancroid Studio Bumblebe is in Beta
  • The latest version of Canary is Chipmunk.

In recent iterations Android Studio has added a number of new features to improve developer coding and debugging efficiency.

Compose @review

A number of enhancements have been made to the Compose preview feature in recent Andorid Studio releases: support for a 3D preview of the Compose UI layout, just like the native view; Changes to some literal variables can be updated in real time without recompiling:

The Preview Configuration panel is added to make it easier to modify the parameters in the @Preview annotation.

Jank Detection

The Frames view has been added to the Performance Profile to monitor the time spent on each frame for better debugging and detection of Jank problems.

In addition, Android Studio has enhanced the emulator to simulate more real-world scenarios, such as gravity sensing.


AGP (Android Gradle Plugin)


Non-transitive R class

Since AGP 7.0, a number of improvements have been made to build speed, such as support for KSP and non-transitive R class. Non-transitive R class avoids implicit transitive dependencies and improves compilation speed by displaying the full package name of the specified resource file. AGP with the new Androi Studio enables one-click refactoring of non-transitive R classes for projects

Incremental Lint

AGP 7.0 introduced Lint incremental checking to greatly improve Lint checking speed

Configuration cache

Medium.com/androiddeve…

With Gradle configuration cache enabled, AGP can significantly improve compilation speed in various situations

To start the Configuration Cache, add a Configuration to gradle.properties in Android Studio

org.gradle.unsafe.configuration-cache=true
Copy the code


Summary


The Android Dev Summit shared topics on all aspects of the Android space that developers don’t need to know about, but more importantly, insights into the future of the technology. For example, future apps may need to adapt to more screen sizes, and Jetpack Compose is becoming increasingly advanced in UI development. The e trend of Kotlin Flow replacing LiveData and WorkManager replacing Service is also becoming clear.