Showing posts with label Develop. Show all posts
Showing posts with label Develop. Show all posts

Thursday, April 14, 2016

Optimize, Develop, and Debug with Vulkan Developer Tools

Posted by Shannon Woods, Technical Program Manager



Today we're pleased to bring you a preview of Android development tools for Vulkan™. Vulkan is a new 3D rendering API which we’ve helped to develop as a member of Khronos, geared at providing explicit, low-overhead GPU (Graphics Processor Unit) control to developers. Vulkan’s reduction of CPU overhead allows some synthetic benchmarks to see as much as 10 times the draw call throughput on a single core as compared to OpenGL ES. Combined with a threading-friendly API design which allows multiple cores to be used in parallel with high efficiency, this offers a significant boost in performance for draw-call heavy applications.



Vulkan support is available now via the Android N Preview on devices which support it, including Nexus 5X and Nexus 6P. (Of course, you will still be able to use OpenGL ES as well!)




To help developers start coding quickly, we’ve put together a set of samples and guides that illustrate how to use Vulkan effectively.



You can see Vulkan in action running on an Android device with Robert Hodgin’s Fish Tornado demo, ported by Google’s Art, Copy, and Code team:






Optimization: The Vulkan API



There are many similarities between OpenGL ES and Vulkan, but Vulkan offers new features for developers who need to make every millisecond count.




  • Application control of memory allocation. Vulkan provides mechanisms for fine-grained control of how and when memory is allocated on the GPU. This allows developers to use their own allocation and recycling policies to fit their application, ultimately reducing execution and memory overhead and allowing applications to control when expensive allocations occur.

  • Asynchronous command generation. In OpenGL ES, draw calls are issued to the GPU as soon as the application calls them. In Vulkan, the application instead submits draw calls to command buffers, which allows the work of forming and recording the draw call to be separated from the act of issuing it to the GPU. By spreading command generation across several threads, applications can more effectively make use of multiple CPU cores. These command buffers can also be reused, reducing the overhead involved in command creation and issuance.

  • No hidden work. One OpenGL ES pitfall is that some commands may trigger work at points which are not explicitly spelled out in the API specification or made obvious to the developer. Vulkan makes performance more predictable and consistent by specifying which commands will explicitly trigger work and which will not.

  • Multithreaded design, from the ground up. All OpenGL ES applications must issue commands for a context only from a single thread in order to render predictably and correctly. By contrast, Vulkan doesn’t have this requirement, allowing applications to do work like command buffer generation in parallel— but at the same time, it doesn’t make implicit guarantees about the safety of modifying and reading data from multiple threads at the same time. The power and responsibility of managing thread synchronization is in the hands of the application.

  • Mobile-friendly features. Vulkan includes features particularly helpful for achieving high performance on tiling GPUs, used by many mobile devices. Applications can provide information about the interaction between separate rendering passes, allowing tiling GPUs to make effective use of limited memory bandwidth, and avoid performing off-chip reads.

  • Offline shader compilation. Vulkan mandates support for SPIR-V, an intermediate language for shaders. This allows developers to compile shaders ahead of time, and ship SPIR-V binaries with their applications. These binaries are simpler to parse than high-level languages like GLSL, which means less variance in how drivers perform this parsing. SPIR-V also opens the door for third parties to provide compilers for specialized or cross-platform shading languages.

  • Optional validation. OpenGL ES validates every command you call, checking that arguments are within expected ranges, and objects are in the correct state to be operated upon. Vulkan doesn’t perform any of this validation itself. Instead, developers can use optional debug tools to ensure their calls are correct, incurring no run-time overhead in the final product.




Debugging: Validation Layers


As noted above, Vulkan’s lack of implicit validation requires developers to make use of tools outside the API in order to validate their code. Vulkan’s layer mechanism allows validation code and other developer tools to inspect every API call during development, without incurring any overhead in the shipping version. Our guides show you how to build the validation layers for use with the Android NDK, giving you the tools necessary to build bug-free Vulkan code from start to finish.




Develop: Shader toolchain



The Shaderc collection of tools provides developers with build-time and run-time tools for compiling GLSL into SPIR-V. Shaders can be compiled at build time using glslc, a command-line compiler, for easy integration into existing build systems. Or, for shaders which are generated or edited during execution, developers can use the Shaderc library to compile GLSL shaders to SPIR-V via a C interface. Both tools are built on top of Khronos’s reference compiler.




Additional Resources


The Vulkan ecosystem is a broad one, and the resources to get you started don’t end here. There is a wealth of material to explore, including:


























Android N Developer Preview 2, out today!

Posted by Dave Burke, VP of Engineering



Last month, we released the first Developer Preview of Android N, to give you a sneak peek at our next platform. The feedback you’ve shared to-date has helped us catch bugs and improve features. Today, the second release in our series of Developer Previews is ready for you to continue testing against your apps.



This latest preview of Android N fixes a few bugs you helped us identify, such as not being able to connect to hidden Wi-Fi networks (AOSP 203116), Multiwindow pauses (AOSP 203424), and Direct Reply closing an open activity (AOSP 204411), to name just a few. We’re still on the hunt for more; please continue to share feedback, either in the N Developer Preview issue tracker or in the N preview community.




What’s new:


Last month’s Developer Preview introduced a host of new features, like Multi-window, bundled notifications and more. This preview builds on those and includes a few new ones:



  • Vulkan: Vulkan is a new 3D rendering API which we’ve helped to develop as a member of Khronos, geared at providing explicit, low-overhead GPU (Graphics Processor Unit) control to developers and offers a significant boost in performance for draw-call heavy applications. Vulkan’s reduction of CPU overhead allows some synthetic benchmarks to see as much as 10 times the draw-call throughput on a single core as compared to OpenGL ES. Combined with a threading-friendly API design which allows multiple cores to be used in parallel with high efficiency, this offers a significant boost in performance for draw-call heavy applications. With Android N, we’ve made Vulkan a part of the platform; you can try it out on supported devices running Developer Preview 2. Read more here. Vulkan Developer Tools blog here.


  • Launcher shortcuts: Now, apps can define shortcuts which users can expose in the launcher to help them perform actions quicker. These shortcuts contain an Intent into specific points within your app (like sending a message to your best friend, navigating home in a mapping app, or playing the next episode of a TV show in a media app).

    An application can publish shortcuts with ShortcutManager.setDynamicShortcuts(List) and ShortcutManager.addDynamicShortcut(ShortcutInfo), and launchers can be expected to show 3-5 shortcuts for a given app.



  • Emoji Unicode 9 support: We are introducing a new emoji design for people emoji that moves away from our generic look in favor of a more human-looking design. If you’re a keyboard or messaging app developer, you should start incorporating these emoji into your apps.
    The update also introduces support for skin tone variations and Unicode 9 glyphs, like the bacon, selfie and face palm. You can dynamically check for the new emoji characters using Paint.hasGlyph().













New human emoji











New activity emoji



  • API changes: This update includes API changes as we continue to refine features such as multi-window support (you can now specify a separate minimum height and minimum width for an activity), notifications, and others. For details, take a look at the diff reports available in the downloadable API reference package.



  • Bug fixes: We’ve resolved a number of issues throughout the system, including these fixes for issues that you’ve reported through the public issue tracker. Please continue to let us know what you find and follow along with the known issues here.




How to get the update:


The easiest way to get this and later preview updates is by enrolling your devices in the Android Beta Program. Just visit g.co/androidbeta and opt-in your eligible Android phone or tablet -- you’ll soon receive this (and later) preview updates over-the-air. If you’ve already enrolled your device, you’ll receive the update shortly, no action is needed on your part. You can also download and flash this update manually. Developer Preview 2 is intended for developers and not as a daily driver; this build is not yet optimized for performance and battery life.



The N Developer Preview is currently available for Nexus 6, Nexus 5X, Nexus 6P, Nexus 9, and Pixel C devices, as well as General Mobile 4G [Android One] devices. For Nexus Player, the update to Developer Preview 2 will follow the other devices by several days.



To build and test apps with Developer Preview 2, you need to use Android Studio 2.1 -- the same version that was required for Developer Preview 1. You’ll need to check for SDK components updates (including build tools and emulator system images) for Developer Preview 2 -- see here for details.



Thanks so much for all of your feedback so far. Please continue to share feedback, either in the N Developer Preview issue tracker or in the N preview community. The sooner we’re able to get your feedback, the more of of it we will be able to incorporate in the next release of Android.

















Friday, April 8, 2016

Android Studio 2.0

Posted by Jamal Eason, Product Manager, Android



Android Studio 2.0 is the fastest way to build high quality, performant apps for the Android platform, including phones and tablets, Android Auto, Android Wear, and Android TV. As the official IDE from Google, Android Studio includes everything you need to build an app, including a code editor, code analysis tools, emulators and more. This new and stable version of Android Studio has fast build speeds and a fast emulator with support for the latest Android version and Google Play Services.



Android Studio is built in coordination with the Android platform and supports all of the latest and greatest APIs. If you are developing for Android, you should be using Android Studio 2.0. It is available today as a easy download or update on the stable release channel.



Android Studio 2.0 includes the following new features that Android developer can use in their workflow :





  • Instant Run - For every developer who loves faster build speeds. Make changes and see them appear live in your running app. With many build/run accelerations ranging from VM hot swapping to warm swapping app resources, Instant Run will save you time every day.

  • Android Emulator - The new emulator runs ~3x faster than Android’s previous emulator, and with ADB enhancements you can now push apps and data 10x faster to the emulator than to a physical device. Like a physical device, the official Android emulator also includes Google Play Services built-in, so you can test out more API functionality. Finally, the new emulator has rich new features to manage calls, battery, network, GPS, and more.

  • Cloud Test Lab Integration - Write once, run anywhere. Improve the quality of your apps by quickly and easily testing on a wide range of physical Android devices in the Cloud Test Lab right from within Android Studio.

  • App Indexing Code Generation & Test - Help promote the visibility your app in Google Search for your users by adding auto-generated URLS with the App Indexing feature in Android Studio. With a few click you can add indexable URL links that you can test all within the IDE.

  • GPU Debugger Preview - For those of you developing OpenGL ES based games or apps, you can now see each frame and the GL state with the new GPU debugger. Uncover and diagnosis GL rendering issues by capturing and analyzing the GPU stream from your Android device.

  • IntelliJ 15 Update - Android Studio is built on the world class Intellij coding platform. Check out the latest Intellij features here.




Deeper Dive into the New Features



Instant Run


Today, mobile platforms are centered around speed and agility. And yet, building for mobile can sometimes feel clunky and slow. Instant Run in Android Studio is our solution to keep you in a fast and fluid development flow. The feature increases your developer productivity by accelerating your edit, build, run cycles. When you click on the Instant Run button (), Instant Run will analyze the changes you have made and determine how it can deploy your new code in the fastest way.




New Instant Run Buttons



Whenever possible, it will inject your code changes into your running app process, avoiding re-deployment and re-installation your APK. For some types of changes, an activity or app restart is required, but your edit, build and run cycles should still be generally much faster than before. Instant Run works with any Android Device or emulator running API 14 (Ice Cream Sandwich) or higher.



Since previewing Instant Run at the end of last year, we’ve spent countless hours incorporating your feedback and refining for the stable release. Look for even more acceleration in future releases because build speeds can never be too fast. To learn how you can make the most out of Instant Run in your app development today, please check out our Instant Run documentation.



Android Emulator


The new Android Emulator is up to 3x faster in CPU, RAM, & I/O in comparison to the previous Android emulator. And when you're ready to build, ADB push speeds are a whopping 10x faster! In most situations, developing on the official Android Emulator is faster than a real device, and new features like Instant Run will work best with the new Android emulator.



In addition to speed and performance, the Android Emulator has a brand user interface and sensor controls. Enhanced since the initial release, with the emulator you can drag and drop APKs for quick installation, resize and rescale the window, use multi-touch actions (pinch & zoom, pan, rotate, tilt) and much more.




Android Emulator User Interface: Toolbar & Extend Controls Panel



Trying out the new emulator is as easy as updating your SDK Tools to 25.1.1 or higher, create a fresh Android Virtual Device using one of the recommended x86 system images and you are ready to go. Learn more about the Android Emulator by checking out the documentation.



Cloud Test Lab


Cloud Test Lab is a new service that allows you to test your app across a wide range of devices and device configurations at scale in the cloud. Once you complete your initial testing with your Android Emulator or Android device, Cloud Test Lab is a great extension to your testing process that provides you to run through a collection of tests against a portfolio of physical devices hosted in Google’s data centers. Even if you do not have tests explicitly written, Cloud Test Lab can perform a basic set of tests to ensure that your app does not crash.



The new interface in Android Studio allows you to configure the portfolio of tests you want to run on Cloud Test Lab, and allows you to also see the results of your tests. To learn more about the service go here.




Setup for Cloud Test Lab



App Indexing


It is now easier for your users to find your app in Google Search with the App Indexing API. Android Studio 2.0 helps you to create the correct URL structure in your app code and add attributes in your AndroidManifest.xml file that will work the Google App Indexing service. After you add the URLs to your app, can you test and validate your app indexing code as shown here:



Google App Indexing Testing



Check out this link for more details about app indexing support in Android Studio.



GPU Debugger Preview


If you are developing OpenGL ES games or graphics-intensive apps, you have a new GPU debugger with Android Studio 2.0. Although the GPU debugger is a preview, you can step through your app frame by frame to identify and debug graphics rendering issues with rich information about the GL state. For more details on how to setup your Android device and app to work with the tool, check out the tech documentations here.



GPU Debugger Preview



What's Next



Update


If you are using a previous version of Android Studio, you can check for updates on the Beta channel from the navigation menu (Help → Check for Update [Windows/Linux] , Android Studio → Check for Updates [OS X]). If you need a new copy of Android Studio, you can download it here. If you developing for the N Developer Preview, check out this additional setup instructions.



Set Up Instant Run & Android Emulator


After you update to or download Android Studio 2.0, you should upgrade your projects to use Instant Run, and create a fresh Android Virtual Device (AVD) for the new Android emulator and you are on your way to a fast Android development experience.



Using Instant Run is easy. For each of your existing projects you will see a quick prompt to update your project to the new gradle plugin version (com.android.tools.build:gradle:2.0.0).




Prompt to update your gradle version in your project



For all new app projects in Android Studio 2.0, Instant Run is on by default. Check out the documentation for more details.



We are already hard at work developing the next release of Android Studio. We appreciate any feedback on things you like, issues or features you would like to see. Connect with us -- the Android Studio development team -- on our new Google+ page or on Twitter.
































Saturday, March 26, 2016

Registering OAuth clients for Google Sign-In

Posted by Isabella Chen, Software Engineer, and Laurence Moroney, Developer Advocate



Starting with Google Play services 8.3, we did a major revamp of the Google Sign-In APIs, supporting both client and server auth. Behind the scenes, these APIs use OAuth 2.0 tokens to ensure secure authentication and authorization. To maintain security, we provide tools in the Google Developers Console to register the clients using these tokens.



In this post, we’ll discuss the important task of registering OAuth clients for Google Sign-In, and the tools that we offer to make this as easy as possible.



Here are some scenarios that might apply to you:


  1. Start by creating a project in the Google Developers Console, which registers the client app on your behalf.

  2. If you have a backend server in your project, you’ll need an OAuth client ID for it, too.

  3. And don't forget to register OAuth clients for other test and release versions of your app, too!


In this post, we’ll cover some details on this process and address common pitfalls.



Getting Started - Create a Project in the Google Developers Console.



If you have not used Google Sign-In before, you can start integrating the API into your app by following the ‘Get a configuration file’ steps on this site. You’ll be taken to a setup wizard that will create an OAuth 2.0 client ID as shown in Figure 1.





Figure 1. Configuring your app



Once you’ve specified your app, you’ll be taken to a screen to choose and configure services such as Google Sign-In, Cloud Messaging or Google Analytics that you want your app to be able to use.



Choose Google Sign-In. In order to use it, you’ll need to get the SHA-1 of the signing certificate for your Android app. This can either be a debug or a release certificate, and for the purposes of this blog you’ll look at a debug one, but keep in mind that you’ll need to repeat this process for each package / certificate pair you end up using (described in the last section below).



You can get the debug SHA-1 using the keytool command like this:



keytool -list -v -keystore ~/.android/debug.keystore -alias androiddebugkey -storepass android -keypass android



Once you have your SHA-1, enter it as seen in Figure 2.





Figure 2. Enabling Google Sign-in



Now that your project is set up, you can get started with integrating the Sign-In API. But if you need to configure your project to work with a backend server or additional package name / keystores, keep reading the sections below.



Server Config - Ensure your server is registered within the same project.



If you have your own web or cloud server with data for your application, you’ll need OAuth credentials for your backend. Details on doing this can be found in the ID token and server auth code documentation.



Before using these flows, you’ll need to make sure you register your web server correctly in the Google Developers Console. Once there, you’ll be asked to select your project. See Figure 3.




Figure 3. Going directly to a project in the Google Developers Console.



Once you’ve selected your project, press the ‘Continue’ button, and you’ll go directly to the Credentials tab where all credential types are managed. Check the “OAuth 2.0 client IDs” section, and you will see the “Web client” and “Android client for com.my.package.name” that were created for you by the setup wizard. See Figure 4.




Figure 4. The Credentials Tab on the Developers Console - Web server OAuth client info



Take note of the Client ID for for your Web client, you’ll need it for both your app and server as illustrated below. (If you’ve created your project in the past and there’s no OAuth 2.0 client ID with Type “Web application”, then you will need to create one by selecting ‘New Credentials’ -> ‘OAuth client ID’.)



If you use an ID token flow for backend authentication, when you start developing your Android app, request an ID token in your GoogleSignInOptions, supplying the web client ID for your server:



GoogleSignInOptions gso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(serverClientId)
.requestEmail()
.build();


And then on your server, set the same OAuth client ID for your web application to be the audience:



GoogleIdTokenVerifier verifier =
new GoogleIdTokenVerifier.Builder(transport, jsonFactory)
.setAudience(Arrays.asList(serverClientId))
.setIssuer("https://accounts.google.com")
.build();


Successful verification will allow you to authenticate and issue a session for this newly signed-in user.



Alternatively, if you are using the server auth code flow for backend access to Google APIs, request a server auth code in your GoogleSignInOptions on Android, again supplying the web client ID for your server:



GoogleSignInOptions gso =
new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestScopes(new Scope(Scopes.DRIVE_APPFOLDER))
.requestServerAuthCode(serverClientId)
.requestEmail()
.build();


And then on the server, both the OAuth client ID and the “Client secret” will be useful. The server SDK from Google can directly consume a downloaded JSON configuration file. You can click the download icon to download the JSON file (as shown in Figure 4) and use below code to construct GoogleClientSecrets:



GoogleClientSecrets clientSecrets =
GoogleClientSecrets.load(
JacksonFactory.getDefaultInstance(),
new FileReader(PATH_TO_CLIENT_SECRET_FILE));


At which point you can access authenticated Google APIs on behalf of the signed-in user. Note that the “client secret” is really a secret that you should never reveal in your Android client.



Handling multiple environments - Registering other client IDs for your project.



Note that it can be common for apps to have different package names as well as different certificates (and thus SHA-1 keys) for various types of environment (such for different developers or test and release environments). Google uses your package name together with SHA-1 signing-certificate fingerprint to uniquely identify your Android application. It’s important to register every package name + SHA1 fingerprint pair in Google Developers Console.



For example, to register the release version of this package, you can do so by selecting ‘New Credentials’ -> ‘OAuth client ID’, shown in Figure 5 below, and then following the steps to add the package name and production keystore SHA-1.




Figure 5. The Credentials Tab on the Developers Console - create additional OAuth client ID



Now you are ready to handle the different environments where your app might be running and release to your users!



Hopefully, this has been helpful to you in understanding how to register for OAuth keys to keep your apps and servers secure. For more information, check out the Google Developers homepage for Identity.

Thursday, February 25, 2016

Android Support Library 23.2

Posted by Ian Lake, Developer Advocate

Android Support Library 23.2

When talking about the Android Support Library, it is important to realize this isn’t one monolithic library, but a whole collection of libraries that seek to provide backward-compatible versions of APIs, as well as offer unique features without requiring the latest platform version. Version 23.2 adds a few new support libraries as well as new features to many of the existing libraries.





Support Vector Drawables and Animated Vector Drawables

Vector drawables allow you to replace multiple png assets with a single vector graphic, defined in XML. While previously limited to Lollipop and higher devices, both VectorDrawable and AnimatedVectorDrawable are now available through two new Support Libraries support-vector-drawable and animated-vector-drawable, respectively.

Android Studio 1.4 introduced limited support for vector drawables by generating pngs at build time. To disable this functionality (and gain the true advantage and space savings of this Support Library), you need to add vectorDrawables.useSupportLibrary = true to your build.gradle file:



 // Gradle Plugin 2.0+  
android {
defaultConfig {
vectorDrawables.useSupportLibrary = true
}
}
You’ll note this new attribute only exists in the version 2.0 of the Gradle Plugin. If you are using Gradle 1.5 you’ll instead use

 // Gradle Plugin 1.5  
android {
defaultConfig {
generatedDensities = []
}

// This is handled for you by the 2.0+ Gradle Plugin
aaptOptions {
additionalParameters "--no-version-vectors"
}
}
If you are using AppCompat 23.2.0, setting these flags is required. This requirement has been relaxed as of AppCompat 23.2.1 and the flags are only required if you wish to use support vector drawables.

You’ll be able to use VectorDrawableCompat back to API 7 and AnimatedVectorDrawableCompat on all API 11 and higher devices. Due to how drawables are loaded by Android, not every place that accepts a drawable id (such as in an XML file) will support loading vector drawables. Thankfully, AppCompat has added a number of features to make it easy to use your new vector drawables.

Firstly, when using AppCompat with ImageView (or subclasses such as ImageButton and FloatingActionButton), you’ll be able to use the new app:srcCompat attribute to reference vector drawables (as well as any other drawable available to android:src):

 <ImageView  
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_add" />
And if you’re changing drawables at runtime, you’ll be able to use the same setImageResource() method as before - no changes there. Using AppCompat and app:srcCompat is the most foolproof method of integrating vector drawables into your app.

You’ll find directly referencing vector drawables outside of app:srcCompat will fail prior to Lollipop. However, AppCompat does support loading vector drawables when they are referenced in another drawable container such as a StateListDrawable, InsetDrawable, LayerDrawable, LevelListDrawable, and RotateDrawable. By using this indirection, you can use vector drawables in cases such as TextView’s android:drawableLeft attribute, which wouldn’t normally be able to support vector drawables.

As of Android Support Library 23.3.0, support vector drawables can only be loaded via app:srcCompat or setImageResource()..

AppCompat DayNight theme

While enabling the use of vector graphics throughout your app is already a large change to AppCompat, there’s a new theme added to AppCompat in this release: Theme.AppCompat.DayNight.



Prior to API 14, The DayNight theme and its descendents DayNight.NoActionBar, DayNight.DarkActionBar, DayNight.Dialog, etc. become their Light equivalents. But on API 14 and higher devices, this theme allows apps to easily support both a Light and Dark theme, effectively switching from a Light theme to a Dark theme based on whether it is ‘night’.

By default, whether it is ‘night’ will match the system value (from UiModeManager.getNightMode()), but you can override that value with methods in AppCompatDelegate. You’ll be able to set the default across your entire app (until process restart) with the static AppCompatDelegate.setDefaultNightMode() method or retrieve an AppCompatDelegate via getDelegate() and use setLocalNightMode() to change only the current Activity or Dialog.

When using AppCompatDelegate.MODE_NIGHT_AUTO, the time of day and your last known location (if your app has the location permissions) are used to automatically switch between day and night, while MODE_NIGHT_NO and MODE_NIGHT_YES forces the theme to never or always use a dark theme, respectively.

It is critical that you test your app thoroughly when using the DayNight themes as hardcoded colors can easily make for unreadable text or icons. If you are using the standard TextAppearance.AppCompat styles for your text or colors pulled from your theme such as android:textColorPrimary, you’ll find these automatically update for you.

However, if you’d like to customize any resources specifically for night mode, AppCompat reuses the night resource qualifier folder, making it possible customize every resource you may need. Please consider using the standard colors or taking advantage of the tinting support in AppCompat to make supporting this mode much easier.

Design Support Library: Bottom Sheets

The Design Support Library provides implementations of many patterns of material design. This release allows developers to easily add bottom sheets to their app.

By attaching a BottomSheetBehavior to a child View of a CoordinatorLayout (i.e., adding app:layout_behavior="android.support.design.widget.BottomSheetBehavior"), you’ll automatically get the appropriate touch detection to transition between five state:

  • STATE_COLLAPSED: this collapsed state is the default and shows just a portion of the layout along the bottom. The height can be controlled with the app:behavior_peekHeight attribute (defaults to 0)

  • STATE_DRAGGING: the intermediate state while the user is directly dragging the bottom sheet up or down

  • STATE_SETTLING: that brief time between when the View is released and settling into its final position

  • STATE_EXPANDED: the fully expanded state of the bottom sheet, where either the whole bottom sheet is visible (if its height is less than the containing CoordinatorLayout) or the entire CoordinatorLayout is filled

  • STATE_HIDDEN: disabled by default (and enabled with the app:behavior_hideable attribute), enabling this allows users to swipe down on the bottom sheet to completely hide the bottom sheet

Keep in mind that scrolling containers in your bottom sheet must support nested scrolling (for example, NestedScrollView, RecyclerView, or ListView/ScrollView on API 21+).

If you’d like to receive callbacks of state changes, you can add a BottomSheetCallback:

 // The View with the BottomSheetBehavior  
View bottomSheet = coordinatorLayout.findViewById(R.id.bottom_sheet);
BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
behavior.setBottomSheetCallback(new BottomSheetCallback() {
@Override
public void onStateChanged(@NonNull View bottomSheet, int newState) {
// React to state change
}
@Override
public void onSlide(@NonNull View bottomSheet, float slideOffset) {
// React to dragging events
}
});
While BottomSheetBehavior captures the persistent bottom sheet case, this release also provides a BottomSheetDialog and BottomSheetDialogFragment to fill the modal bottom sheets use case. Simply replace AppCompatDialog or AppCompatDialogFragment with their bottom sheet equivalents to have your dialog styled as a bottom sheet.

Support v4: MediaBrowserServiceCompat

The Support v4 library serves as the foundation for much of the support libraries and includes backports of many framework features introduced in newer versions of the platform (as well a number of unique features).

Adding onto the previously released MediaSessionCompat class to provide a solid foundation for media playback, this release adds MediaBrowserServiceCompat and MediaBrowserCompat providing a compatible solution that brings the latest APIs (even those added in Marshmallow) back to all API 4 and higher devices. This makes it much easier to support audio playback on Android Auto and browsing through media on Android Wear along with providing a standard interface you can use to connect your media playback service and your UI.

RecyclerView

The RecyclerView widget provides an advanced and flexible base for creating lists and grids as well as supporting animations. This release brings an exciting new feature to the LayoutManager API: auto-measurement! This allows a RecyclerView to size itself based on the size of its contents. This means that previously unavailable scenarios, such as using WRAP_CONTENT for a dimension of the RecyclerView, are now possible. You’ll find all built in LayoutManagers now support auto-measurement.

Due to this change, make sure to double check the layout parameters of your item views: previously ignored layout parameters (such as MATCH_PARENT in the scroll direction) will now be fully respected.

If you have a custom LayoutManager that does not extend one of the built in LayoutManagers, this is an opt-in API - you’ll be required to call setAutoMeasureEnabled(true) as well as make some minor changes as detailed in the Javadoc of the method.

Note that although RecyclerView animates its children, it does not animate its own bounds changes. If you would like to animate the RecyclerView bounds as they change, you can use the Transition APIs.

Custom Tabs

Custom Tabs makes it possible to seamlessly transition to web content while keeping the look and feel of your app. With this release, you’ll now be able to add actions to a bottom bar for display alongside the web content.

With the new addToolbarItem() method, you’ll be able to add up to currently 5 (MAX_TOOLBAR_ITEMS) actions to the bottom bar and update them with setToolbarItem() once the session has begun. Similar to the previous setToolbarColor() method, you’ll also find a setSecondaryToolbarColor() method for customizing the background color of the bottom bar.

Leanback for Android TV

The Leanback Library gives you the tools you need to easily bring your app to Android TV with many standard components optimized for the TV experience. The GuidedStepFragment received a significant set of improvements with this release.

The most visible change may be the introduce of a second column used for action buttons (added by overriding onCreateButtonActions() or calling setButtonActions()). This makes it much easier to reach completion actions without having to scroll through the list of available GuidedActions.

Speaking of GuidedActions, there’s a number of new features to allow richer input including editable descriptions (via descriptionEditable()), sub actions in the form of a dropdown (with subActions()), and a GuidedDatePickerAction.

These components should make it much easier for you to get information from the user when absolutely required.

Available Now

Version 23.2 of the Android Support Library is available via your SDK Manager and Android Studio. Take advantage of all of the new features as well as additional bug fixes starting now! As always, file bug reports at b.android.com and connect with other developers on the Android Development Google+ community.

Tuesday, February 2, 2016

Marshmallow and User Data



Posted by Joanna Smith, Developer Advocate and Giles Hogben, Google Privacy Team



Marshmallow introduced several changes that were designed to help your app look after user data. The goal was to make it easier for developers to do the right thing. So as Android 6.0, Marshmallow, gains traction, we challenge you to do just that.



This post highlights the key considerations for user trust when it comes to runtime permissions and hardware identifiers, and points you to new best practices documentation to clarify what to aim for in your own app.



Permission Changes


With Marshmallow, permissions have moved from install-time to runtime. This is a mandatory change for SDK 23+, meaning it will affect all developers and all applications targeting Android 6.0. Your app will need to be updated anyway, so your challenge is to do so thoughtfully.



Runtime permissions mean that your app can now request access to sensitive information in the context that it will be used. This gives you a chance to explain the need for the permission, without scaring users with a long list of requests.



Permissions are also now organized into groups, so that users can make an informed decision without needing to understand technical jargon. By allowing your users to make a decision, they may decide not to grant a permission or to revoke a previously-granted permission. So, your app needs to be thoughtful when handling API calls requiring permissions that may have been denied, and about building in graceful failure-handling so that your users can still interact with the rest of your app.



Identifier Changes



The other aspect of user trust is doing the right thing with user data. With Marshmallow, we are turning off access to some kinds of data in order to direct developers down this path.



Most notably, Local WiFi and Bluetooth MAC addresses are no longer available. The getMacAddress() method of a WifiInfo object and the BluetoothAdapter.getDefaultAdapter().getAddress() method will both return 02:00:00:00:00:00 from now on.




However, Google Play Services now provides Instance IDs, which identify an application instance running on a device. Instance IDs provide a reliable alternative to non-resettable, device-scoped hardware IDs, as they will not persist across a factory reset and are scoped to an app instance. See the Google Developer's What is Instance ID? help article for more information.



What’s Next


User trust depends largely on what users see and how they feel. Mishandling permissions and identifiers increases the risk of unwanted/unintended tracking, and can result in users feeling that your app doesn’t actually care about the user. So to help you get it right, we’ve created new documentation that should enable developers to be certain that their app is doing the right thing for their users.







So happy developing! May your apps make users happy, and may your reviews reflect that. :)


Thursday, December 31, 2015

Get ready for Javascript “Promises” with Google and Udacity

Sarah Clark, Program Manager, Google Developer Training



Front-end web developers face challenges when using common “asynchronous” requests. These requests, such as fetching a URL or reading a file, often lead to complicated code, especially when performing multiple actions in a row. How can we make this easier for developers?



Javascript Promises are a new tool that simplifies asynchronous code, converting a tangle of callbacks and event handlers into simple, straightforward code such as: fetch(url).then(decodeJSON).then(addToPage)...



Promises are used by many new web standards, including Service Worker, the Fetch API, Quota Management, Font Load Events,Web MIDI, and Streams.






We’ve just opened up a online course on Promises, built in collaboration with Udacity. This brief course, which you can finish in about a day, walks you through building an “Exoplanet Explorer” app that reads and displays live data using Promises. You’ll also learn to use the Fetch API and finally kiss XMLHttpRequest goodbye!



This short course is a prerequisite for most of the Senior Web Developer Nanodegree. Whether you are in the paid Nanodegree program or taking the course for free, won’t you come learn to make your code simpler and more reliable today?

Friday, December 11, 2015

Android Studio 2.0 Preview: Android Emulator


Posted by, Jamal Eason, Product Manager, Android




An early preview of the new Android Emulator is now available to try out. As a part of Android Studio 2.0, the latest version of the Android Emulator can help you test your app on a wide range of screens size and configurations beyond the physical Android hardware you use to test.Moreover, using the official Android emulator enables you to test with latest Android versions. Building on this foundation, the top two benefits of new Android emulator are:





  • Speed & Performance: When emulating the latest Android 6.0 release (Marshmallow), we now support Symmetric Multi-Processing and have made significant I/O improvements in both the emulator and ADB. This means you will have faster performance when you are testing your app.




  • Usability & User Interface: The new Android Emulator includes a brand new user interface to make the emulator easy to use. You no longer have to rely on command-line parameters to use the Android emulator. Common tasks and emulator features are now just a mouse click or a keyboard shortcut away.


We previewed the user interface at the Android Dev Summit. You can try it out today along with the new version of ADB for faster APK installation and file transfers to the emulator. Check out the video for a demonstration of the new Android Emulator.







Android Dev Summit 2015: Emulator Demo


We are seeking early feedback to continue to deliver the experience and features that will make you more productive.



Performance Improvements


CPU Performance



Android Studio now uses CPU acceleration on x86 emulator system images by default. Combined with new Symmetric Multi-Processor (SMP) support in Android 6.0 Marshmallow system images, the Android emulators can perform even faster than many physical Android devices. Multi-core support not only makes your apps and the emulator run faster but it provides the added advantage of speeding up common developer tasks such as installing APKs. Also, with SMP you can test apps that specifically target multi-processor Android devices.



Faster ADB



In addition to faster CPU speeds in the emulator, there are a number of under-the-hood improvements that will make the experience faster. One of the bottlenecks in the development process that we worked on is the speed of pushing data between Android Studio and your device using ADB (Android Debug Bridge). When you use Android 6.0 Marshmallow and higher system images with the new Android Emulator, you can now push files across ADB up to five times faster than a real device. This will help you if you push large APK or files during your app development cycle.




User Interface



Toolbar



The new interface exposes some of the most common emulator actions in a new toolbar and control panel instead of solely relying on command line options. For the preview, the Android Emulator toolbar enables actions, such as volume control, screen rotation, and screen-shots of the emulator window.





Window Zooming & Scaling


Now you can resize your window simply by dragging a corner. You can also zoom and scroll to get a closer look at a portion of your screen.












Left: Zooming
Right: Window Scaling



Drag & Drop


With the new emulator, you can not only drag and drop APKs for quick installation, but you can also drag and drop any file to your emulator’s internal SD card to help in testing.






Drag and Drop Files


Extended UI Controls


In the extended controls window, additional options help you validate and test features in your app. As shown below, you can initiate a range of emulator actions such as making a virtual call, sending a virtual SMS, or controlling the power level of the emulator. You can additionally send a single GPS location point to the emulator or play back a custom set of KML or GPX points as well.






Phone Controls




Battery Controls

We are continuing to add more functionality and we will keep you up to date as we add more features.



What's Next & Setup


This is just the beginning of developments on the Android Emulator, so expect more features such as support more APIs levels, and adding more sensors with future versions of Android Studio. The new emulator along with Android Studio are available today on the Android Studio canary channel and tools preview channel.



Click here for details on how to setup the preview of the new Android Emulator.


We appreciate your feedback. Connect with us, the Android Studio development team, on Google+.