Showing posts with label Android Pie. Show all posts
Showing posts with label Android Pie. Show all posts

Sunday, October 7, 2018

Android Pie Sdk Is Straightaway To A Greater Extent Than Kotlin-Friendly

Posted past times James Lau, Product Manager (@jmslau)

When using the Java programming language, i of the most mutual pitfalls is trying to access a fellow member of a null reference, causing a NullPointerException to live on thrown. Kotlin offers protection against this past times baking nullable in addition to non-nullable types into the type system. This helps eliminate NullPointerExceptions from your code in addition to amend your app's overall quality. When Kotlin code is calling into APIs written inward the Java programming language, it relies on nullability annotations inward those APIs to create upward one's hear the nullability of each parameter in addition to the render type. Unannotated parameters in addition to render types are treated equally platform types, which weakens the null-safety guarantee of Kotlin.

As purpose of yesterday's Android ix announcement, nosotros bring too released a novel Android SDK that contains nullability annotations for to a greater extent than or less of the most often used APIs. This volition save the null-safety guarantee when your Kotlin code is calling into whatsoever annotated APIs inward the SDK. Even if you lot are using the Java programming language, you lot tin yet attain goodness from these annotations past times using Android Studio to select grip of nullability contract violations.

Not a breaking change

Normally, nullability contract violations inward Kotlin trial inward compilation errors. But to ensure the newly annotated APIs are compatible amongst your existing code, nosotros are using an internal machinery provided past times the Kotlin compiler squad to grade the APIs equally lately annotated. Recently annotated APIs volition trial solely inward warnings instead of errors from the Kotlin compiler. You volition involve to usage Kotlin 1.2.60 or later.

Our invention is to bring newly added nullability annotations attain warnings only, in addition to growth the severity grade to errors starting inward the next year's Android SDK. The destination is to render you lot amongst sufficient fourth dimension to update your code.

How to usage the "Kotlin-friendly" SDK

To teach started, become to Tools > SDK Manager inward Android Studio. Select Android SDK on the left menu, in addition to brand certain the SDK Platforms tab is open.

Use SDK Manager inward Android Studio to install SDK for API Level 28 Revision 6

Check Android 8.+ (P) in addition to click OK. This volition install the Android SDK Platform 28 revision vi if it is non already installed. After that, laid your project's compile SDK version to API 28 to outset using the novel Android Pie SDK amongst nullability annotations.

Use the Project Structure Dialog to alter your project's Compile Sdk Version to API 28

You may too involve to update your Kotlin plugin inward Android Studio if it's non already up-to-date. Make certain your Kotlin plugin version is 1.2.60 or afterwards past times going to Tools > Kotlin > Configure Kotlin Plugin Updates.

Once it's laid up, your builds volition outset showing warnings if you lot bring whatsoever code that violates nullability contracts inward the Android SDK. An trial of such a alarm is shown below.

Sample alarm from the Kotlin compiler when code violates a lately added nullability contract inward the Android SDK.

You volition too outset seeing warnings inward Android Studio's code editor if you lot telephone telephone an Android API amongst the wrong nullability. An trial is shown below.

Android Studio alarm near passing a null reference to a parameter annotated equally a lately non-null type inward the android.graphics.Path API.

Leveraging nullability annotations from the Java programming language

You tin attain goodness from the novel nullability annotations fifty-fifty if your code is inward the Java programming language. By default, Android Studio volition highlight whatsoever nullability contract violations amongst a warning, similar the i below:

Android Studio showing a alarm near nullability contract violation inward code written inward the Java programming linguistic communication

To ensure that you lot bring this inspection enabled, you lot tin become to the IDE's settings page in addition to search for "Constant weather & exceptions" inspection in addition to brand certain that especial is checked.

Use the Inspections page nether Settings to ensure the Constant weather & exceptions code inspection is enabled.

If you lot are using the Java programming language, nullability contract violations volition non attain whatsoever compiler alarm or error. Only the in-IDE code inspections are available to flag these issues.

You tin too run code inspections across your entire projection in addition to run into the aggregated results. Click on Analyze > Inspect Code… to start.

What's Next

The Android SDK API surface is really large, in addition to nosotros bring solely annotated a minor percent of the APIs in addition to thus far - in that place is yet lots of move remaining. Over the side past times side several Android SDK releases, nosotros volition maintain to add together nullability annotations to the existing Android APIs, equally good equally making certain novel APIs are annotated.

With the "Kotlin-friendly" Android SDK, the nullability annotations inward AndroidX (part of the Jetpack family), in addition to Android KTX, nosotros are continuing to amend the Android APIs for developers using Kotlin. If you lot bring non yet tried Kotlin, nosotros encourage you lot to endeavour it. Not solely tin Kotlin brand your code to a greater extent than concise, it tin too amend the stability of your apps.

Happy Kotlin-ing!

Wednesday, October 3, 2018

Moar Ability Inward Android Ix Pie As Well As The Future

Posted past times Madan Ankapura, Product Manager, Android

This is the offset inward a serial of spider web log posts that outline strategies together with guidance inward Android amongst regard to power.

Your users attention a lot virtually battery -- if it runs out likewise quickly, it agency they can't usage your apps. Being a proficient steward of battery ability is an of import operate of your human relationship amongst the user, together with we're continuing to add together features to the platform that tin assistance you lot hit this.

As operate of our announced Play policy virtually improving app safety together with performance, an app's target API marking must last no to a greater extent than than ane twelvemonth older than the electrical flow Android release. Keeping the target API marking electrical flow volition ensure that apps tin conduct maintain payoff of safety together with functioning enhancements offered inward the latest platform releases. When you lot update your app's target API level, it's of import that you lot evaluate your background together with foreground needs, which could conduct maintain a pregnant deport upon on ability & performance.

Past releases of Android included a issue of features that helped grapple battery life better, like:

  • Job Scheduler inward Android 5.0 Lollipop, which allows deferring piece of work
  • Doze together with App Standby inward Android 6.0 Marshmallow, which disables network access together with suspends syncs together with background piece of work - when device or apps are unused for a prolonged period.
  • Doze improvements inward Android 7.0 Nougat, which applies a subset of Doze restrictions when the hide is off together with non stationary.
  • Background limits inward Android 8.0 Oreo, which forbid background services together with throttle place updates.

In Android ix Pie, nosotros made farther improvements based on these iii principles:

  1. Developers desire to construct cool apps
  2. Apps demand to last power-efficient
  3. Users don't desire to last bothered to configure app settings

This agency that the OS needs to last smarter together with arrange to user preferences piece improving the battery life of the device. To address these needs, nosotros conduct maintain introduced App Standby Buckets, Background Restrictions, together with improved Battery Saver. Please exam your app amongst these features enabled on a device running Android ix Pie.

Battery Saver together with Doze operate on a device-wide level, piece Adaptive Battery (app standby buckets powered past times a Deepmind ML model) together with background restrictions operate on a per-app basis. The diagram below helps empathize when a scheduled piece of work volition run.

As you lot update your apps to target Oreo or above, delight review this checklist together with follow the below tabular array for background piece of work

Currently Using Porting to Oreo
JobScheduler JobScheduler
Firebase JobDispatcher Firebase JobDispatcher
Background Service Jobscheduler
Foreground Service Foreground Service amongst activeness to STOP service

Note: when the WorkManager API becomes stable, nosotros volition last recommending WorkManager for most of these usage cases

We recommend the next strategy given the importance for app developers to invest inward the correct pattern patterns together with architecture:

  1. Do the needed piece of work when the user is actively using the app
  2. Make whatever work/task that is done inward the background deferrable
  3. Use foreground services precisely render an activeness inward the notification then user tin halt the foreground service

Similarly, other OS primitives similar alarms, network, together with FCM messages also conduct maintain constraints that are described inward the developer documentation on power-management restrictions. You tin larn to a greater extent than virtually each of these features via Google I/O presentation, DevByte together with additional power optimization developer documentation.

We volition last publishing a serial of pattern pattern guidances inward the upcoming weeks. Stay tuned.

Acknowledgements: This serial of spider web log posts is inward articulation collaboration amongst Android Framework together with DevRel teams.

Notifying Your Users Alongside Fcm

Posted past times Jingyu Shi, Developer Advocate, Partner DevRel

This is the minute inwards a serial of weblog posts inwards which outline strategies as well as guidance inwards Android amongst regard to power.

Notifications are a powerful channel y'all tin utilization to dice on your app's users connected as well as updated. Android provides Notification APIs to do as well as postal service notifications on the device, only quite oftentimes these notifications are triggered past times external events as well as sent to your app from your app server.

In this weblog post, we'll explicate when as well as how to generate these remote notifications to furnish timely updates to users as well as minimize battery drain.

Use FCM for remote notifications

We recommend using upgrade to FCM!

There are ii types of FCM messages y'all tin select from:

  • Notification Messages, which simplify notification treatment as well as are high priority past times default.
  • Data Messages, for when y'all desire to handgrip the FCM messages inside the customer app.

You tin gear upward the priority to either blog post on Firebase Blog.

FCM is optimized to operate amongst Android powerfulness administration Moar Power inwards P as well as the future".

To notify or not?

All of the notifications that y'all shipping should hold out well-structured as well as actionable, every bit good every bit furnish timely as well as relevant information to your users. We recommend that y'all follow these notification guidelines, as well as avoid spamming your users. No 1 wants to hold out distracted past times irrelevant or poorly-structured notifications. If your app behaves similar this, your users may block the notifications or fifty-fifty uninstall your app.

The When non to utilization a notification department of the Material Design documentation for notifications highlights cases where y'all should non shipping your user a notification. For example, a mutual utilization instance for a normal priority FCM Data Message is to tell the app when there's content cook for sync, which requires no user interaction. The sync should compass quietly inwards the background, amongst no demand for a notification, as well as y'all tin utilization the WorkManager1 or JobScheduler API to schedule the sync.

Post a notification first

If y'all are sending remote notifications, y'all should e'er postal service the notification every bit presently every bit possible upon receiving the FCM message. Adding whatsoever additional network requests earlier posting a notification volition Pb to delayed notifications for some of your users. When non handled properly, the notifications mightiness non hold out seen at all, come across the "avoid background service" department below.


⚠️ Avoid adding whatsoever additional network requests earlier posting a notification

Also dice on inwards heed that, depending on the the world of the device, user actions, as well as app behavior, 1 or many powerfulness saving features could hold out restricting your app's background work. As a result, your app's jobs as well as alarms mightiness hold out delayed, as well as its powerfulness to access the network mightiness hold out restricted.

For all of these reasons, to ensure timely delivery of the notification, y'all should e'er demo the notification promptly when the FCM message is received, earlier whatsoever other operate similar network fetch or scheduling jobs.

FCM message payload is your friend

To postal service a notification upon the receipt of an FCM message, y'all should include all the information needed for the notification inwards the FCM message payload.

The same applies to information sync--we recommend that your app shipping every bit much information every bit possible inwards the FCM payload and, if needed, charge the residual of the information when the app opens. On a well-performing network, there's a adept jeopardy that the information volition hold out synced past times the fourth dimension the user opens the app thence the spinner won't hold out shown to the user. If network connectivity is non good, a notification volition hold out sent to the user amongst the content inwards the FCM payload to inform the user inwards a timely manner. The user tin as well as thence opened upward the app to charge all the data.

You tin besides encrypt FCM messages end-to-end using libraries similar Capillary. The icon below shows a full general menses of how to handgrip FCM messages.

Need to a greater extent than data?

As convenient every bit FCM message payload is, it comes amongst a 4KB maximum limit. If y'all demand to shipping a rich notification amongst an icon attachment, or y'all desire to improve your user sense past times keeping your app inwards sync amongst media content, y'all may demand to a greater extent than than the 4KB payload limit. For this, nosotros recommend using FCM messages inwards combination amongst the WorkManager 1 or JobScheduler API.

If y'all demand to postal service a rich notification, nosotros recommend posting the notification first, amongst some of the content inwards the FCM message. Then schedule a chore to fetch the residual of the content. Once the chore is finished, update the notification if it is withal active. For example, y'all tin include a thumbnail or preview of the content inwards the FCM payload as well as postal service it inwards the notification first. Then schedule a chore to fetch the ease of the media files. Be aware that if you've scheduled jobs from the FCM message handler, it is possible that when the user launches the app, the scheduled chore won't have got finished yet. You should handgrip this instance gracefully.

In short, utilization the information inwards the FCM message payload to postal service a notification as well as dice on your app content updated first. If y'all withal demand to a greater extent than data, as well as thence schedule jobs amongst APIs similar WorkManager 1 or JobScheduler API.

Avoid background services

One mutual pitfall is using a background service to fetch information inwards the FCM message handler, since background service volition hold out stopped past times the organization per recent changes to Google Play Policy (Starting belatedly 2018, Google Play volition require a minimum target API bird ).

Android nine Pie volition besides impose background execution limits when battery saver is on. Starting a background service volition Pb to IllegalStateException from a normal priority FCM message. High priority messages do grant y'all a curt whitelist window that allows y'all to start a background service. However, starting a background service amongst a network telephone call back volition seat the service at risk of getting terminated past times the system, because the curt execution window is solely intended to hold out used for posting a notification.

You should avoid using background services only utilization WorkManager 1 or JobScheduler API instead to perform operations inwards the background.

Power & message priority

Android six Marshmallow introduced Doze. FCM is optimized to operate amongst Doze, as well as y'all tin utilization high priority FCM messages to notify your users immediately. In Doze mode, normal priority messages are deferred to a maintenance window. This enables the organization to relieve battery when a device is idle, only withal ensure users have time-critical notifications. Consider an instant messaging app that sends users messages from friends or incoming telephone calls or a domicile monitoring app sends users alert notifications. These are some of the acceptable examples where y'all tin utilization high priority FCM messages.

In addition, Android nine Pie introduced App Standby Buckets as well as App Restrictions.

The tabular array below shows how diverse power-management features bear upon message delivery behaviors.

High priority message delivery Normal priority message delivery
App inwards Foreground Immediate, unless app is restricted (see below) Immediate, unless app is restricted (see below)
App inwards Background
Device inwards Doze (M+) as well as Doze "on the go" (N+) Immediate Deferred until maintenance window
App Standby Buckets (P+) May hold out restricted No restriction
App Restrictions (P+) All messages dropped (see below) All messages dropped (see below)
Battery Saver No restriction No restriction


★ Note: Starting Jan 2019, App Restrictions (in Battery Setting) volition include restrictions on FCM messages. You tin discovery out if your app is inwards the restricted the world amongst the isBackgroundRestricted API. Once your app is inwards the restricted state, no FCM messages volition hold out delivered to the app at all. This volition apply to both high as well as normal priority FCM messages as well as when app is inwards either foreground or background.

App Standby Buckets impose unlike levels of restrictions based on the app's standby bucket. Based on which bucket your app belongs to, in that place mightiness hold out a cap for the expose of high priority messages y'all are allowed to shipping per day. Once y'all attain the cap, whatsoever subsequent high priority messages volition hold out downgraded to normal priority. See to a greater extent than details inwards the power administration restrictions.

High priority FCM messages are designed to shipping remote notifications or trigger actions that involve user interactions. As long every bit y'all e'er utilization high priority messages for these purposes, your high priority messages volition hold out delivered forthwith as well as remote notifications volition hold out displayed without delay. In addition, when a notification from a high priority message causes a user to opened upward your app, the app gets promoted to the active bucket, which exempts it from FCM caps. The illustration below shows an instant messaging app moving to the active bucket afterwards the user taps on a notification triggered past times a high priority FCM message.

However, if y'all utilization high priority messages to shipping notifications to the blocked notification channels or tasks which do non involve user interactions, y'all volition run the risk of wasting the high priority messages allocated inwards your app's bucket. Once reaching the cap, y'all won't hold out able to shipping urgent notifications anymore.

In summary, y'all should solely utilization high priority FCM messages to deliver immediate, time-critical notifications to users. Doing thence volition ensure these messages as well as subsequent high priority messages attain your users without getting downgraded. You should utilization normal priority messages to trigger events that do non require immediate execution, such every bit a notification that is non time-sensitive or a information sync inwards the background.

Test amongst Android 9!

We highly recommend that y'all blog.

Thank y'all for helping motion the ecosystem forward, making ameliorate Android apps, as well as saving users' batteries!

Acknowledgements: This weblog posts is inwards articulation collaboration amongst FCM as well as Android teams.

1 WorkManager is the recommended solution for background processing in 1 lawsuit it's stable.