Oct 17

Modern background execution in Android


Posted by Luiz Gustavo Martins, Partner Developer Advocate, Partner DevRel

This is the third in a series of blog posts in which outline strategies and guidance in Android with regard to power.

Over the years, executing background tasks on Android has evolved. To write modern apps, it’s important to learn how to run your background tasks in modern fashion.

When is an app in the background?

Before understanding what background execution is, we need to have a clear view of when Android understands an app to be in the foreground. An app is considered to be in the foreground if any of the following is true:

  • The app has a visible activity, whether the activity is started or paused.
  • The app has a foreground service.
  • Another foreground app is connected to the app, either by binding to one of its services, or using one of its content providers. For example, an app is in the foreground if another app or the system binds to its:
    • IME
    • Wallpaper service
    • Notification listener
    • Voice or text service
    • Music app when streaming music to your car. (Android Auto-specific case)

If none of those conditions is true, the app is considered to be in the background.

Background execution changes

Running tasks in the background consumes a device’s limited resources, like RAM and battery. This might result in a bad user experience. For example, background tasks may degrade the battery life of the device or the user may experience poor device performance at times such as watching a video, playing a game, using the camera.

To improve battery life and give a better user experience, Android has evolved over several releases to establish limits on background execution. These limits include:

  • Doze and App Standby, which restricts app behavior when the screen is off, and the device is idle and not charging.
  • Background Location restrictions, limits how frequently background apps can retrieve the user’s current location.
  • Background Service Limits, that restrict background services from being run and consuming CPU/network in a hidden/non-visible way.
  • Most recently, App Standby Buckets that can limit the device resources available to apps that aren’t used by users, and App Restrictions where the system will prompt the user to restrict the app’s access to system resources in the background if the app exhibits bad behaviors, and several Battery Saver improvements.

Use cases and solutions

Deciding which tools to use to implement background execution requires the developer to have a clear understanding of what they want to accomplish, and under which restrictions. This flowchart can help you make a decision:

  • WorkManager is the recommended solution for background execution, taking into account all OS background execution limits. If you need to guarantee that a task will run even if it is deferred, you should use WorkManager. This API allows you to schedule jobs (one-off or repeating) and chain and combine jobs. You can also apply execution constraints to them such as triggering when the device is idle or charging, or executing when a content provider changes.

    One example is if you need to compress logs to upload them to your server. To do this you can create two work requests:

    • First: compress the file. On this step you may add the constraint that the device should be charging.
    • Second: upload it to the server. For this request you should add a network connectivity constraint so that the work only gets triggered when you have a valid connection.

    After enqueuing both tasks, WorkManager will take care of executing them when your app has access to the resources you need.

    Another nice feature of WorkManager is that it respects power-management features, so that if a job is scheduled to run at a defined time and the device is in Doze at that time, WorkManager will try to run the task during a maintenance window if the constraints are met or after Doze is lifted.

  • If a long-running task is to be scheduled in response to an external event like syncing for new online content, use Firebase Cloud Messaging to notify your app and then create a work request with WorkManager to sync the content. You can learn more about this in “Notifying your users with FCM”.
  • If the app needs to complete a user-initiated task without deferring even if the user leaves the app or turns off the screen, such as in the case of music/video playback or navigation, you should use a Foreground service. (The next blog post in this series dives deeper into this use case.)
  • If you need to run a task at an exact time that triggers actions, involves user interactions, and cannot be deferred, use AlarmManager (more specifically the method setExactAndAllowWhileIdle). Examples of time alarms include:
    • a reminder to take medicine
    • a notification that a TV show is about to start.

    When the alarm is triggered, you have very few seconds to finish the work and your app may not have access to the network (for example during Doze or due to App Standby buckets). If you really need network or to do a long task, use WorkManager. Every time a wakeup alarm is triggered, the device comes out of low-power mode and holds a partial wake lock which can significantly impact the battery life over time. This can be monitored via excessive wakeups stats highlighted on Android Vitals, provided via Google Play Console.

In Summary:

Use Case Examples Solution
Guaranteed execution of deferrable work
  • Upload logs to your server
  • Encrypt/Decrypt content to upload/download
WorkManager
A task initiated in response to an external event
  • Syncing new online content like email
FCM + WorkManager
Continue user-initiated work that needs to run immediately even if the user leaves the app
  • Music player
  • Tracking activity
  • Transit navigation
Foreground Service
Trigger actions that involve user interactions, like notifications at an exact time.
  • Alarm clock
  • Medicine reminder
  • Notification about a TV show that is about to start
AlarmManager

Use background execution judiciously so that you can build cool apps that delight users while saving their battery. If you need more information on executing background tasks on Android, there’s great content at the Android developer site.

Note: WorkManager is still in public preview. If you need an alternative solution right now, you should use JobScheduler, although it has limitations that don’t apply to WorkManager. JobScheduler is part of the Android Framework, and only available for Android API 21 and above; WorkManager works on API 14 and above.

Acknowledgements: This series of blog posts is produced in collaboration between the Android Framework and DevRel teams


Android Developers Blog

Oct 16

Final Android Wear 2.0 Developer Preview: iOS support. Time to upload your apps to the Play Store!

Posted by Hoi Lam, Developer
Advocate 

Cross platform support by Telegram Messenger

Today, we are releasing the fifth and final developer preview for Android Wear
2.0. In this release, we have added iOS support and included a number of bug
fixes and enhancements. Apps compiled with this preview are now ready for final
submission to the Google Play Store, so it’s time to publish
your apps. As Android Wear 2.0 approaches its final release in early
February, we would like to thank you for your continued feedback during the
developer preview program. Your input has helped us uncover bugs as well as
drive critical product decisions. Thank you!

iOS Support

Since 2015,
you’ve been able to pair Android Wear watches with iPhones, and now you can
distribute your apps to iPhone-paired watches as well. To do so, just set the standalone=true
flag in your watch app manifest. This lets the Play Store know that your watch
app doesn’t require an Android phone app, and therefore can appear in the Play
Store on watches paired to iPhones. To pair your watch to an iPhone and
test, just follow these
steps.

The available network bandwidth for standalone apps can be lower than expected,
as the platform balances battery savings vs network bandwidth. Make sure to
check out these guidelines
for accessing the network, including accessing Wi-Fi and cellular networks on
watches paired with iPhones.

Also with this developer preview release, Android Wear apps running on watches
paired with iOS devices will be able to perform phone hand-off flows such as OAuth
and RemoteIntent
for launching a web page on a paired iOS device.

Uploading Your App to the Google Play Store

The final developer preview includes an update to the Wearable Support Library.
Apps compiled with API level 25 and this support library are considered ready
for deployment in the Google Play Store. Please note that there are no updates
to the preview watch image or emulator in this developer preview release.


Other Enhancement and Bug Fixes

  • Navigation Drawer: Flip
    a flag to toggle to the single-page, icon-only action drawer, which provides
    faster, more streamlined navigation to different views in your app.
  • NFC HCE support: NFC
    Host Card Emulation FEATURE_NFC_HOST_CARD_EMULATION is now
    supported.
  • ProGuard and Complication API: New ProGuard configuration
    means complication data container classes will no longer be obfuscated. This
    fixes a ClassNotFoundException when watch faces are trying to access data supplied
    by a complication data provider.

Countdown to Launch

Thank you for the fantastic level of feedback we have gotten from you as
developers. Check out g.co/wearpreview for
the latest builds and documentation, and be sure to publish
your apps before the Android Wear 2.0 consumer launch in early February. As
we work towards the consumer launch and beyond, please continue filing bugs or posting comments in our Android Wear
Developers community. We can’t wait to see your Android Wear 2.0 apps!


Android Developers Blog

Oct 15

Android Instant Apps starts initial live testing

Posted by Aurash Mahbod, Software Engineer, Google Play

Android Instant Apps was previewed at Google I/O last year as a new way to run Android apps without requiring installation. Instant Apps is an important part of our effort to help users discover and run apps with minimal friction.


We’ve been working with a small number of developers to refine the user and developer experiences. Today, a few of these Instant Apps will be available to Android users for the first time in a limited test, including apps from BuzzFeed, Wish, Periscope, and Viki. By collecting user feedback and iterating on the product, we’ll be able to expand the experience to more apps and more users.



To develop an instant app, you’ll need to update your existing Android app to take advantage of Instant Apps functionality and then modularize your app so part of it can be downloaded and run on-the-fly. You’ll use the same Android APIs and Android Studio project. Today, you can also take some important steps to be ready for Instant Apps development. The full SDK will be available in the coming months.

There has already been a tremendous amount of interest in Instant Apps from thousands of developers. We can’t wait to hear your feedback and share more awesome experiences later this year. Stay tuned!






Android Developers Blog

Oct 11

Control Flow Integrity in the Android kernel


Posted by Sami Tolvanen, Staff Software Engineer, Android Security

Android’s security model is enforced by the Linux kernel, which makes it a tempting target for attackers. We have put a lot of effort into hardening the kernel in previous Android releases and in Android 9, we continued this work by focusing on compiler-based security mitigations against code reuse attacks.

Google’s Pixel 3 will be the first Android device to ship with LLVM’s forward-edge Control Flow Integrity (CFI) enforcement in the kernel, and we have made CFI support available in Android kernel versions 4.9 and 4.14. This post describes how kernel CFI works and provides solutions to the most common issues developers might run into when enabling the feature.

Protecting against code reuse attacks

A common method of exploiting the kernel is using a bug to overwrite a function pointer stored in memory, such as a stored callback pointer or a return address that had been pushed to the stack. This allows an attacker to execute arbitrary parts of the kernel code to complete their exploit, even if they cannot inject executable code of their own. This method of gaining code execution is particularly popular with the kernel because of the huge number of function pointers it uses, and the existing memory protections that make code injection more challenging.

CFI attempts to mitigate these attacks by adding additional checks to confirm that the kernel’s control flow stays within a precomputed graph. This doesn’t prevent an attacker from changing a function pointer if a bug provides write access to one, but it significantly restricts the valid call targets, which makes exploiting such a bug more difficult in practice.

Figure 1. In an Android device kernel, LLVM’s CFI limits 55% of indirect calls to at most 5 possible targets and 80% to at most 20 targets.

Gaining full program visibility with Link Time Optimization (LTO)

In order to determine all valid call targets for each indirect branch, the compiler needs to see all of the kernel code at once. Traditionally, compilers work on a single compilation unit (source file) at a time and leave merging the object files to the linker. LLVM’s solution to CFI is to require the use of LTO, where the compiler produces LLVM-specific bitcode for all C compilation units, and an LTO-aware linker uses the LLVM back-end to combine the bitcode and compile it into native code.

Figure 2. A simplified overview of how LTO works in the kernel. All LLVM bitcode is combined, optimized, and generated into native code at link time.

Linux has used the GNU toolchain for assembling, compiling, and linking the kernel for decades. While we continue to use the GNU assembler for stand-alone assembly code, LTO requires us to switch to LLVM’s integrated assembler for inline assembly, and either GNU gold or LLVM’s own lld as the linker. Switching to a relatively untested toolchain on a huge software project will lead to compatibility issues, which we have addressed in our arm64 LTO patch sets for kernel versions 4.9 and 4.14.

In addition to making CFI possible, LTO also produces faster code due to global optimizations. However, additional optimizations often result in a larger binary size, which may be undesirable on devices with very limited resources. Disabling LTO-specific optimizations, such as global inlining and loop unrolling, can reduce binary size by sacrificing some of the performance gains. When using GNU gold, the aforementioned optimizations can be disabled with the following additions to LDFLAGS:

LDFLAGS += -plugin-opt=-inline-threshold=0 \
           -plugin-opt=-unroll-threshold=0

Note that flags to disable individual optimizations are not part of the stable LLVM interface and may change in future compiler versions.

Implementing CFI in the Linux kernel

LLVM’s CFI implementation adds a check before each indirect branch to confirm that the target address points to a valid function with a correct signature. This prevents an indirect branch from jumping to an arbitrary code location and even limits the functions that can be called. As C compilers do not enforce similar restrictions on indirect branches, there were several CFI violations due to function type declaration mismatches even in the core kernel that we have addressed in our CFI patch sets for kernels 4.9 and 4.14.

Kernel modules add another complication to CFI, as they are loaded at runtime and can be compiled independently from the rest of the kernel. In order to support loadable modules, we have implemented LLVM’s cross-DSO CFI support in the kernel, including a CFI shadow that speeds up cross-module look-ups. When compiled with cross-DSO support, each kernel module contains information about valid local branch targets, and the kernel looks up information from the correct module based on the target address and the modules’ memory layout.

Figure 3. An example of a cross-DSO CFI check injected into an arm64 kernel. Type information is passed in X0 and the target address to validate in X1.

CFI checks naturally add some overhead to indirect branches, but due to more aggressive optimizations, our tests show that the impact is minimal, and overall system performance even improved 1-2% in many cases.

Enabling kernel CFI for an Android device

CFI for arm64 requires clang version >= 5.0 and binutils >= 2.27. The kernel build system also assumes that the LLVMgold.so plug-in is available in LD_LIBRARY_PATH. Pre-built toolchain binaries for clang and binutils are available in AOSP, but upstream binaries can also be used.

The following kernel configuration options are needed to enable kernel CFI:

CONFIG_LTO_CLANG=y
CONFIG_CFI_CLANG=y

Using CONFIG_CFI_PERMISSIVE=y may also prove helpful when debugging a CFI violation or during device bring-up. This option turns a violation into a warning instead of a kernel panic.

As mentioned in the previous section, the most common issue we ran into when enabling CFI on Pixel 3 were benign violations caused by function pointer type mismatches. When the kernel runs into such a violation, it prints out a runtime warning that contains the call stack at the time of the failure, and the call target that failed the CFI check. Changing the code to use a correct function pointer type fixes the issue. While we have fixed all known indirect branch type mismatches in the Android kernel, similar problems may be still found in device specific drivers, for example.

CFI failure (target: [<fffffff3e83d4d80>] my_target_function+0x0/0xd80):
------------[ cut here ]------------
kernel BUG at kernel/cfi.c:32!
Internal error: Oops - BUG: 0 [#1] PREEMPT SMP
…
Call trace:
…
[<ffffff8752d00084>] handle_cfi_failure+0x20/0x28
[<ffffff8752d00268>] my_buggy_function+0x0/0x10
…

Figure 4. An example of a kernel panic caused by a CFI failure.

Another potential pitfall are address space conflicts, but this should be less common in driver code. LLVM’s CFI checks only understand kernel virtual addresses and any code that runs at another exception level or makes an indirect call to a physical address will result in a CFI violation. These types of failures can be addressed by disabling CFI for a single function using the __nocfi attribute, or even disabling CFI for entire code files using the $ (DISABLE_CFI) compiler flag in the Makefile.

static int __nocfi address_space_conflict()
{
      void (*fn)(void);
 …
/* branching to a physical address trips CFI w/o __nocfi */
 fn = (void *)__pa_symbol(function_name);
      cpu_install_idmap();
      fn();
      cpu_uninstall_idmap();
 …
}

Figure 5. An example of fixing a CFI failure caused by an address space conflict.

Finally, like many hardening features, CFI can also be tripped by memory corruption errors that might otherwise result in random kernel crashes at a later time. These may be more difficult to debug, but memory debugging tools such as KASAN can help here.

Conclusion

We have implemented support for LLVM’s CFI in Android kernels 4.9 and 4.14. Google’s Pixel 3 will be the first Android device to ship with these protections, and we have made the feature available to all device vendors through the Android common kernel. If you are shipping a new arm64 device running Android 9, we strongly recommend enabling kernel CFI to help protect against kernel vulnerabilities.

LLVM’s CFI protects indirect branches against attackers who manage to gain access to a function pointer stored in kernel memory. This makes a common method of exploiting the kernel more difficult. Our future work involves also protecting function return addresses from similar attacks using LLVM’s Shadow Call Stack, which will be available in an upcoming compiler release.


Android Developers Blog

Oct 10

Android Developer Story: Wallapop improves user conversions with store listing experiments on Google Play

Posted by Lily Sheringham, Developer Marketing, Google Play

Wallapop
is a mobile app developer based in Barcelona, Spain. The app provides a platform
to users for selling and buying things to others nearby in a virtual flea market
by using geolocalization. Wallapop now has over 70% of their user base on
Android.

Watch Agus Gomez, Co-Founder & CEO, and Marta Gui, Growth Hacking Manager,
explain how using store listing experiments has increased their conversion rate
by 17%, and has allowed them to optimize organic installs.

Learn
more about store listing experiments. Get the Playbook for
Developers app to stay up-to-date with more features and best practices that
will help you grow a successful business on Google Play.

How useful did you find this blogpost?
                                                                              


Android Developers Blog

Oct 09

Adding a Backend to Your App In Android Studio

Posted by Sachin Kotwani, Google Cloud Platform team

Android Studio lets you easily add a cloud backend to your application, right from your IDE. A backend allows you to implement functionality such as backing up user data to the cloud, serving content to client apps, real-time interactions, sending push notifications through Google Cloud Messaging for Android (GCM), and more. Additionally, having your application’s backend hosted on Google App Engine means that you can focus on what the cloud application does, without having to worry about administration, reliability or scalability.

When you create a backend using Android Studio, it generates a new App Engine application under the same project, and gives your Android application the necessary libraries and a sample activity to interact with that backend. Support for GCM is built-in, making it easy to sync data across multiple devices. Once you’ve generated the project, you can build and run your client and server code together, in a single environment, and even deploy your backend code right from Android Studio.

In this post we’ll focus on how to get started with the basic setup. From there it’s easy to extend the basic setup to meet your needs.

Preliminary setup

Before you get started, make sure you take care of these tasks first:

  • Download Android Studio if you haven’t done so already and set it up.
  • Make sure you have an application project set up in Android Studio. You can use any working app that you want to integrate with your backend, even a sample app.
  • If you’ll be running the app on an emulator, download the Google APIs Addon from the SDK Manager and run your app on that image.
  • Create a Google Cloud Platform project: In the Cloud Console, create a new project (or reuse an old one) and make note of the Project ID. Click on the words “Project ID” on the top left to toggle to the Project Number. Copy this as well.
  • Enable GCM and obtain API Key: In the Cloud Console, click on APIs and turn on the Google Cloud Messaging for Android API. Then, click on the “Register App” button on the top left, enter a name for the app, then select “Android” and “Accessing APIs via a web server”. In the resulting screen, expand the “Server Key” box and copy the API key.

1. Generate an App Engine project

In Android Studio, open an existing Android application that you want to modify, or create a new one. Select the Android app module under the Project node. Then click Tools > Google Cloud Endpoints > Create App Engine Backend.

In the wizard, enter the Project ID, Project Number, and API Key of your Cloud project.

This will create:

  • An App Engine project which contains the backend application source
  • An endpoints module with a RegisterActivity class, related resources, and client libraries for the Android app to communicate with the backend

The generated App Engine application (<app_name>-AppEngine) is an Apache Maven-based project. The Maven pom.xml file takes care of downloading all the dependencies, including the App Engine SDK. This module also contains the following:

  • A Google Cloud Endpoint (DeviceInfoEndpoint.java, auto-generated from DeviceInfo.java) that your Android app will “register” itself through. Your backend will use that registration info to send a push notification to the device.
  • A sample endpoint, MessageEndpoint.java, to list previously sent GCM messages and send new ones.
  • A starter web frontend application (index.html in webapp directory) that will show all the devices that have registered with your service, and a form to send them a GCM notification.

The endpoints module (<app_name>-endpoints) generated for you contains the classes and libraries needed by the Android application to interact with the backend:

  • A RegisterActivity.java class that, when invoked, will go through the GCM registration flow and also register itself with the recently created backend through DeviceInfoEndpoint.
  • Client libraries, so that the application can talk to the backend using an object rather than directly using raw REST calls.
  • XML files related to the newly created activity.

2. Add GCM registration to your app

In your Android application, you can call RegisterActivity whenever you want the registration to take place (for example, from within the onCreate() method of your main activity.

...
import android.content.Intent;
...

@Override
    protected void onCreate(Bundle savedInstanceState) {
        ...
        Intent intent = new Intent(this, RegisterActivity.class);
        startActivity(intent);
    }

3. Deploy the sample backend server

When you’re ready to deploy an update to your ( the sample ) production backend in the cloud, you can do that easily from the IDE. Click on the “Maven Projects” button on the right edge of the IDE, under Plugins > App Engine, right-click and run the appengine:update goal.

As soon as the update is deployed, you can also access your endpoints through the APIs Explorer at http://<project-id>.appspot.com/_ah/api/explorer.

For testing and debugging, you can also run your backend server locally without having to deploy your changes to the production backend. To run the backend locally, just set the value of LOCAL_ANDROID_RUN to true in CloudEndpointUtils.java in the App Engine module.

4. Build and run the Android app

Now build and run your Android app. If you called RegisterActivity from within your main activity, the device will register itself with the GCM service and the App Engine app you just deployed. If you are running the app on an emulator, note that GCM functionality requires the Google APIs Addon image, which you can download from the SDK Manager.

You can access your sample web console on any browser at http://<project-id>.appspot.com. There, you will see that the app you just started has registered with the backend. Fill out the form and send a message to see GCM in action!

Extending the basic setup

It’s easy to expand your cloud services right in Android Studio. You can add new server-side code and through Android Studio instantly generate your own custom endpoints to access those services from your Android app.

Join the discussion on

+Android Developers


Android Developers Blog

Oct 08

New Course: Android Design for Developers

Posted by Nick Butcher, pixel pusher

What makes an app intuitive and easy to use? What makes it hard or frustrating? How can your app stand out in a competitive market? Learn the fundamentals of good Android design and the patterns that have proven to work on Android to help you to build better apps.

This 5-lesson series, available on Udacity, begins with a crash course on the fundamentals of Android UI design. It helps you to sort your DIPs from your pixels, to pick the right layouts and navigation structures and shows you how to style your app to match your brand. The rest of the course is a deep dive into the principles and implementation of material design to show you how to build beautiful consistent experiences that are right at home on Android.


Lesson 2 dives into the concept of tangible surfaces, and how they establish hierarchy to make your UI more understandable. Lesson 3 looks at applying bold graphic design, or how the principles of space, color, typography and imagery help you to create a beautiful, branded experience. Lesson 4 studies the use of meaningful motion to bring your apps to life and create a seamless and more intuitive experience. Finally, lesson 5 shows how adaptive design makes your app shine on any screen size.

This course is aimed at developers familiar with Android who want to boost their design skills or designers who want to understand more about the platform they’re creating for. The full course is available for free or you can enroll in Udacity’s Android Nanodegree for extra help and support. So sign up for the Android design for developers course and go build something brilliant!


Android Developers Blog

Oct 05

Kotlin Momentum for Android and Beyond


Posted by James Lau (@jmslau), Product Manager

Today marks the beginning of KotlinConf 2018 – the largest in-person gathering of the Kotlin community annually. 2018 has been a big year for Kotlin, as the language continues to gain adoption and earn the love of developers. In fact, 27% of the top 1000 Android apps on Google Play already use Kotlin. More importantly, Android developers are loving the language with over 97% satisfaction in our most recent survey. It’s no surprise that Kotlin was voted as the #2 most-loved language in the 2018 StackOverflow survey.

Google supports Kotlin as a first-class programming language for Android development. In the past 12 months, we have delivered a number of important improvements to the Kotlin developer experience. This includes the Kotlin-friendly SDK, Android KTX, new Lint checks and various Kotlin support improvements in Android Studio. We have also launched Kotlin support in our official documentation, new flagship samples in Kotlin, a new Kotlin Bootcamp Udacity course, #31DaysOfKotlin and other deep dive content. We are committed to continuing to improve the Kotlin developer experience.

As the language continues to advance, more developers are discovering the benefits of Kotlin across the globe. Recently, we traveled to India and worked with local developers like Zomato to better understand how adopting Kotlin has benefited their Android development. Zomato is a leading restaurant search & discovery service that operates in 24 countries, with over 150 million monthly users. Kotlin helped Zomato reduce the number of lines of code in their app significantly, and it has also helped them find important defects in their app at compile time. You can watch their Kotlin adoption story in the video below.

Android Developer Story: Zomato uses Kotlin to write safer, more concise code.

Going beyond Android, we are happy to announce that the Google Cloud Platform team is launching a dedicated Kotlin portal today. This will help developers more easily find resources related to Kotlin on Google Cloud. We want to make it as easy as possible for you to use Kotlin, whether it’s on mobile or in the Cloud.

Google Cloud Platform’s Kotlin Homepage

Adopting a new language is a major decision for most companies, and you need to be confident that the language you choose will have a bright future. That’s why Google has joined forces with JetBrains and established the Kotlin Foundation. The Foundation will ensure that Kotlin continues to advance rapidly, remain free and stay open. You can learn more about the Kotlin Foundation here.

It’s an exciting time to be a Kotlin developer. If you haven’t tried Kotlin yet, we encourage you to join this growing global community. You can get started by visiting kotlinlang.org or the Android Developer Kotlin page.


Android Developers Blog

Sep 27

Announcing the Android Auto Desktop Head Unit

Posted by Josh Gordon, Developer Advocate

Today we’re releasing the Desktop Head Unit (DHU), a new testing tool for Android Auto developers. The DHU enables your workstation to act as an Android Auto head unit that emulates the in-car experience for testing purposes. Once you’ve installed the DHU, you can test your Android Auto apps by connecting your phone and workstation via USB. Your phone will behave as if it’s connected to a car. Your app is displayed on the workstation, the same as it’s displayed on a car.


The DHU runs on your workstation. Your phone runs the Android Auto companion app.


Now you can test pre-released versions of your app in a production-like environment, without having to work from your car. With the release of the DHU, the previous simulators are deprecated, but will be supported for a short period prior to being officially removed.

Getting started

You’ll need an Android phone running Lollipop or higher, with the Android Auto companion app installed. Compile your Auto app and install it on your phone.

Install the DHU

Install the DHU on your workstation by opening the SDK Manager and downloading it from Extras > Android Auto Desktop Head Unit emulator. The DHU will be installed in the <sdk>/extras/google/auto/ directory.

Running the DHU

Be sure your phone and workstation are connected via USB.

  1. Enable Android Auto developer mode by starting the Android Auto companion app and tapping on the header image 10 times. This is a one-time step.
  2. Start the head unit server in the companion app by clicking on the context menu, and selecting “Start head unit server”. This option only appears after developer mode is enabled. A notification appears to show the server is running.

  3. Start the head unit server in the Android Auto companion app before starting the DHU on your workstation. You’ll see a notification when the head unit server is running.


  4. On your workstation, set up port forwarding using ADB to allow the DHU to connect to the head unit server running on your phone. Open a terminal and type adb forward tcp:5277 tcp:5277. Don’t forget this step!
  5. Start the DHU.

      cd <sdk>/extras/google/auto/

      On Linux or OSX: ./desktop-head-unit

      On Windows, desktop-head-unit.exe

At this point the DHU will launch on your workstation, and your phone will enter Android Auto mode. Check out the developer guide for more info. We hope you enjoy using the DHU!

Join the discussion on

+Android Developers


Android Developers Blog

Sep 25

Android Studio 3.2


Posted by Jamal Eason, Product Manager, Android

Today, Android Studio 3.2 is available for download. Android Studio 3.2 is the best way for app developers to cut into the latest Android 9 Pie release and build the new Android App bundle. Since announcing this update of Android Studio at Google I/O ’18, we have refined and polished 20+ new features and focused our efforts on improving the quality for this stable release of Android Studio 3.2.

Every developer should use Android Studio 3.2 to transition to using an Android App Bundle, the new app publishing format. With very minimal work, you can generate an app bundle with Android Studio. Once you upload your app bundle to Google Play you can distribute smaller, optimized apps to your users. Early adopters have already seen between 11% – 64% in app size savings with app bundles over the legacy APK app size.

Another feature you do not want to miss is the Energy Profiler. This new profiler gives you a set of tools that will help you diagnose and improve the energy impact of your app. Better device battery life is one of the top most user requests, and with the Energy Profiler in Android Studio 3.2, you can do your part in improving device battery life by making sure your app is using the right amount of energy at the right time.

Lastly, you should also check out the new Android Emulator Snapshots feature. By using this feature, you can quickly take a snapshot of the current state of your emulator which includes the current state of the screen, apps, and settings. You can resume or boot into your emulator snapshot in under 2 seconds. For any app developer looking for super- fast boot times, or seeking to run tests in a predictable Android environment, Android Emulator Snapshots is a game changing feature for app development

On top of these major features, there are 20 new features plus many under-the-hood quality refinements in Android Studio 3.2. By using Android Studio 3.2, you can also develop for the latest technologies ranging from Android Jetpack, to the latest in Google Artificial Intelligence (AI) APIs with Android Slices.

Thank you to those who gave your early feedback on both the canary and beta releases. Your feedback helped us improve the quality and features in Android Studio 3.2. If you are ready for the next stable release, and want to use a new set of productivity features, Android Studio 3.2 is ready to download for you to get started.

Below is a full list of new features in Android Studio 3.2, organized by key developer flows.

Develop

  • Slices support – Slices is a new way to tap into the built-in Android AI capabilities by surfacing app content in Google Search suggestions and the Google Assistant. Android Studio 3.2 has a built-in template to help you extend your app with the new Slice Provider APIs as well as new lint checks to ensure that you’re following best practices when constructing the slices. To use, right-click on a project folder, and navigate to NewOtherSlice Provider. Learn more.

Slices Provider Template

  • Sample Data – This feature allows you to use placeholder data to aid in the design of your app. This will help you visualize layouts that depend on runtime data. You can add built-in sample data to populate views such as RecyclerViews, ImageViews, and TextViews via a popup-window in the Layout Editor. Learn more.
  • Material Design Update – When you start migrating from the Android Design support library to the new MaterialComponents app theme and library, Android Studio 3.2 will offer you access to new and updated widgets such as BottomAppBar, buttons, cards, text fields, new font styles and more. Learn more.
  • CMakeList Editing Support - For those using C/C++ in their app, Android Studio has better support for CMake. With this release of Android Studio 3.2, code completion and syntax highlighting now works on common CMakeList build script commands.
  • What’s New Assistant - Android Studio 3.2 has a new assistant panel that opens automatically after an update to inform you about the latest changes to the IDE. You can also open the panel by navigating to Help → What’s New in Android Studio.
  • AndroidX Refactoring Support – One of the components of Android Jetpack is the introduction of the Android extension libraries (AndroidX) as a replacement for the Android Support Libraries. To add AndroidX to a new project you just need to add android.useAndroidX=true to your gradle.properties file. Additionally, Android Studio 3.2 has a new built-in refactoring action to help migrate your project the new namespace and dependencies. Also if you have any Maven dependencies that have not migrated to the AndroidX namespace, the Android Studio build system will automatically convert those project dependencies as well. Learn more.
  • IntelliJ Platform Update - Android Studio 3.2 includes the IntelliJ 2018.1.6 platform release. This IntelliJ release adds many improvements to dataflow analysis, debugging, new inspections, inline external annotations, partial Git commits, plus much more. Learn more.
  • Kotlin Update – Android Studio 3.2 bundles Kotlin 1.2.61, with support for the Kotlin-friendly Android 9 Pie SDK. Learn more.

Build

  • Android App Bundle - The Android App Bundle is the new app publishing format designed to help you deliver smaller APKs to your users and reduce download size of your app. Google Play’s new app serving model, called Dynamic Delivery, processes your app bundle to generate and serve optimized APKs for each user’s device configuration, so they download only the code and resources they need to run your app. With Android Studio 3.2 or via the command line, you can easily build your code as an app bundle and get the benefit of smaller APKs based on language, screen density, and ABIs with no changes to your app code. Learn more.

Build Android App Bundle

  • D8 Desugaring – In some cases, new Java Language features require new bytecodes and language APIs. However, older Android devices may not support these features. Desugaring allows you to use these features on older devices by replacing new bytecodes and language APIs with older ones during the build process. D8 desugaring is turned on by default for Android Studio 3.2 and you can now use most of the latest language changes while targeting older devices.
  • R8 Optimizer - Starting with Android Studio 3.2, we are starting the transition to use R8 as a replacement for ProGuard to optimize and shrink Java language bytecode. R8 is still experimental, so we do not recommend publishing your app using R8 yet, but it is a good time to give the Android Studio team early feedback so we can make any adjustments before R8 fully replaces ProGuard. Learn more.

Test

  • Emulator Snapshots - The latest release of the Android Emulator allows you to create a snapshot of the current state of your emulator and boot up and switch into any snapshot in under 2 seconds. Built upon the Android Emulator Quickboot feature, Android Snapshots are even faster to save and load with this stable release due to under-the-hood speed enhancements. When testing and developing your app, Android snapshots allow you to pre-configure an Android Virtual Device (AVD) snapshot with the presets, apps, data and settings that you want in-place, and repeatedly go back to the same snapshot. Learn more.

Android Emulator Snapshots

  • Microsoft® Hyper-V™ Support - You can now run the Android Emulator on Windows® 10 computers that have Hyper-V enabled. Intel HAXM is still the default hypervisor for the fastest Android Emulator experience. However,thanks to recent open source contributions by Microsoft, and the addition of the new Windows Hypervisor Platform (WHPX) API, the Android Emulator can coexist with other Hyper-V-backed applications, like local Virtual Machines, using the new Hyper-V Support. Learn more.
  • AMD® Processor Support - AMD Processors are now supported by the Android Emulator on Windows 10. Previously running the Android Emulator was limited to slow software emulation when running Windows, but developers who have an AMD processor can now have hardware accelerated performance. Learn more.
  • Screen Record in Android Emulator - You can now record both screen and audio on any Android API level with the new screen record feature in the Android Emulator. In the past, screen recording on a physical Android device only worked on Android 4.4 KitKat (API 19) and above with no audio, with limited Android Emulator support. With the latest Android Emulator (v28.0.+) you no longer have this restriction. As an added bonus, there is a built-in conversion to output to GIF and WebM. You can trigger the new screen record feature via the Android Emulator Extended Controls panel, command line and from Android Studio. Lean more
  • Virtual Scene Camera for Android Emulator – The new Virtual Scene camera in the Android Emulator helps you to develop for ARCore, Google’s platform for building augmented reality experiences. The emulator is calibrated to work with ARCore APIs for AR apps and also allows you to inject virtual scene bitmap images. The virtual scene camera can also be used as a regular HAL3 compatible camera. Learn more.
  • ADB Connection Assistant - Android Studio 3.2 has a new assistant system to help troubleshoot your Android ADB device connections issues. The ADB Connection Assistant walks you through common troubleshooting steps to connect your Android device to your development machine. You can trigger the assistant from the Run dialog box or by navigating to ToolsConnection Assistant . Learn more.

Optimize

  • Energy Profiler - Battery life is a key concern for many phone users, and your app may impact battery life more than you realize. The new Energy Profiler in the Android Studio performance profiler suite can help you understand the energy impact of your app on an Android device. You can now visualize the estimated energy usage of system components, plus inspect background events that may contribute to battery drain. To use the energy profiler, ensure you are connected to an Android device or emulator running Android 8.0 Oreo (API 26) or higher. Learn more.

Energy Profiler

  • System Trace - The new System Trace feature in the CPU Profiler allows you to inspect how your app interacts with system resources in fine-grained detail. Inspect exact timings and durations of your thread states, visualize where your CPU bottlenecks are across all cores, and add custom trace events to analyze. To use system trace, start profiling your app, click into the CPU Profiler, and then choose the System Trace recording configuration. Learn more.
  • Profiler Sessions - We now automatically save Profiler data as “sessions” to revisit and inspect later while you have Android Studio open. We’ve also added the ability to import and export your CPU recordings and heap dumps for later analysis or inspection with other tools. Learn more.
  • Automatic CPU Recording – You can now automatically record CPU activity using the Debug API. After you deploy your app to a device, the profiler automatically starts recording CPU activity when your app calls startMethodTracing(String tracePath), and stops recording when your app calls stopMethodTracing(). Similarly, you can also now automatically start recording CPU activity on app start-up by enabling Start Recording a Method Trace on Startup option in your run configuration. Learn more.
  • JNI Reference Tracking – For those of you who have C/C++ code in your Android app, Android Studio 3.2 now allows you to inspect the memory allocations of your JNI code in the Memory Profiler. As long as you deploy your app to a device running Android 8.0 Oreo (API 26) and higher, you can drill down into the allocation call stack from your JNI reference. To use the feature, start a memory profiler session, and select the JNI Heap from the Live Allocation drop-down menu. Learn more.

To recap, the latest canary of Android Studio 3.2 includes these new major features:

Develop

  • AndroidX Refactoring
  • Sample Data
  • Material Design Update
  • Android Slices
  • CMakeList editing
  • What’s New Assistant
  • New Lint Checks
  • Intellij Platform Update
  • Kotlin Update

Build

  • Android App Bundle
  • D8 Desugaring
  • R8 Optimizer

Test

  • Android Emulator Snapshots
  • Screen Record in Android Emulator
  • Virtual Scene Android Emulator Camera
  • AMD Processor Support
  • Hyper-V Support
  • ADB Connection Assistant

Optimize

  • Energy Profiler
  • System Trace
  • Profiler Sessions
  • Automatic CPU Recording
  • JNI Reference Tracking

Check out the release notes for more details.

Getting Started

Download the latest version of Android Studio 3.2 from the download page. If you are using a previous canary release of Android Studio, make sure you update to Android Studio Canary 14 or higher. If you want to maintain a stable version of Android Studio, you can run the stable release version and canary release versions of Android Studio at the same time. Learn more.

To use the mentioned Android Emulator features make sure you are running at least Android Emulator v28.0.7+ downloaded via the Android Studio SDK Manager.

We appreciate any feedback on things you like, and issues or features you would like to see. Please note, to maintain high product quality, a couple features (e.g. Navigation Editor) you saw in earlier release channels are not enabled by default in the stable release channel. If you find a bug or issue, feel free to file an issue. Connect with us — the Android Studio development team ‐ on our Google+ page or on Twitter.


Android Developers Blog