Senin, 13 Desember 2010

New Gingerbread API: StrictMode

Jika anda baru pertama kali berkunjung ke blog ini, Silakan kasih Komentar untuk artikel yang anda baca.

[This post is by Brad Fitzpatrick, an Android Software Engineer who worries unreasonably most responsiveness.Tim Bray]

Back Story

One enthusiastic thing most Google is 20% time: spending 20% of your happening working on projects right your important focus area. When I connected Google, I bounced every over the place, ofttimes joking that I had heptad 20% projects. One send I kept coming backwards to was Android. I loved its unstoppered nature, giving me access to do whatever I wanted, including opening my garage door when I approached my house on my motorcycle. I rattling desired it to succeed but I worried most digit thing: It wasnt always caretaker smooth. Animations would sometimes falter and UI elements werent always directly responsive to input. It was pretty obvious that things were sometimes circumstance on the criminal thread.

As a heavy SMS user, digit of my 20% projects during the Cupcake (Android 1.5) promulgation was speeding up the Messaging app and making it feel smoother. I got the app to a bright state and then continued peppy between another 20% projects. When the Donut (Android 1.6) promulgation came out, I detected that a whatever of my Messaging optimizations had been accidentally broken. I was depressing for a taste but then I realized what Android rattling needed was always-on, built-in, pervasive action monitoring.

I connected the Android aggroup full-time meet over a assemblage ago and spent a aggregation of happening investigating Froyo action issues, in portion debugging ANRs (those galling dialogs you intend when an application stalls its important threads Looper). Debugging ANRs with the tools at hand was agonized and boring. There wasnt sufficiency instrumentation to find the causes, especially when multiple processes were involved (doing Binder or ContentResolver dealings to Services or ContentProviders in another processes). There had to be a meliorate artefact to track downbound interval hiccups and ANRs...

Enter StrictMode

I wager you were doing 120 ms in a 16 ms zone...

StrictMode is a newborn API in Gingerbread which primarily lets you ordered a contract on a arrange declaring what youre not allowed to do on that thread, and what the penalisation is if you break the policy. Implementation-wise, this contract is only a thread-local number bitmask.

By choice everything is allowed and it wont intend in your artefact unless you poverty it to. The flags you crapper enable in the arrange contract include:

  • detect round writes

  • detect round reads

  • detect meshwork usage

  • on a violation: log

  • on a violation: crash

  • on a violation: dropbox

  • on a violation: show an galling dialog

In addition, StrictMode has most a dozen hooks around most of the places that hit the round (in java.io.*, android.database.sqlite.*, etc) and meshwork (java.net.*) which analyse the underway threads policy, reacting as youve asked.

StrictModes coercive part is that the per-thread policies are propagated whenever Binder IPC calls are prefabricated to another Services or Providers, and arrange traces are stitched together crossways whatever number of processes.

Nobody wants to be slow

You might undergo every the places where your app does round I/O, but do you undergo every the places where the grouping services and providers do? I dont. Im learning, but its a aggregation of code. Were continually working to explain action implications in the SDK docs, but I commonly rely on StrictMode to help grownup calls that inadvertently hit the disk.

Background on disks on phones

Wait, whats criminal with hitting the disk? Android devices are every streaming winkle memory, right? Thats same a super-fast SSD with no agitated parts? I shouldnt hit to care? Unfortunately, you do.

You cant depend on the winkle components or filesystems utilised in most Android devices to be consistently fast. The YAFFS filesystem utilised on whatever Android devices, for instance, has a orbicular lock around every its operations. Only digit round activeness crapper be in-flight crossways the entire device. Even a ultimate stat activeness crapper verify quite a while if you are unlucky. Other devices with more tralatitious country device-based filesystems ease occasionally undergo when the country rotation place decides to garbage amass and do whatever andante internal winkle cancel operations. (For whatever beatific geeky scenery reading, wager lwn.net/Articles/353411)

The take-away is that the round (or filesystem) on ambulatory devices is commonly fast, but the 90th score latencies are ofttimes quite poor. Also, most filesystems andante downbound quite a taste as they intend more full. (See slides from Google I/O Zippy Android apps talk, linked soured code.google.com/p/zippy-android)

The important Thread

Android callbacks and lifecycle events every typically happen on the important arrange (aka UI thread). This makes chronicle easier most of the time, but its also something you requirement to be careful of because every animations, scrolls, and flings process their animations by callbacks on the important thread.

If you poverty to separate an aliveness at 60 fps and an signaling circumstance comes in (also on the important thread), you hit 16 ms to separate your cipher reacting to that signaling event. If you verify longer than 16 ms, perhaps by composition to disk, youve today stuttered your animation. Disk reads are ofttimes better, but they crapper also verify longer than 16 ms, especially on YAFFS if youre waiting for the filesystem lock thats held by a process in the region of a write.

The meshwork is especially andante and inconsistent, so you should never do meshwork requests on your important thread. In fact, in the upcoming Honeycomb promulgation weve prefabricated meshwork requests on the important arrange a mortal error, unless your app is targeting an API edition before Honeycomb. So if you poverty to intend ready for the Honeycomb SDK, attain sure youre never doing meshwork requests on your UI thread. (see Tips on existence uncreased below.)

Enabling StrictMode

The recommended artefact to ingest StrictMode is to invoke it on during development, see from it, and invoke it soured before you ship your app.

For example, in your application or components onCreate():

public void onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); } super.onCreate(); }

Or, simply:

public void onCreate() { if (DEVELOPER_MODE) { StrictMode.enableDefaults(); } super.onCreate(); }

That latter form was specifically additional so you crapper direct pre-Gingerbread API versions but ease easily enable StrictMode using alikeness or another techniques. For instance, you could be targeting Donut (Android 1.6) but ease ingest StrictMode if youre investigating on a Gingerbread figure or emulator, as long as you ingest sufficiency Reflection to call StrictMode.enableDefaults().

Watching StrictMode

If youre using penaltyLog(), the default, meet separate adb logcat and analyse the tangency output. Any violations will be logged to your console, slightly rate-limited for replicate elimination.

If you poverty to intend fancier, invoke on penaltyDropbox() and theyll be cursive to the DropBoxManager, where you crapper select them later withadb bomb dumpsys dropbox data_app_strictmode --print

Tips on existence smooth

In constituent to Thread and java.util.concurrent.*, analyse discover whatever of the Android APIs such as Handler, AsyncTask, AsyncQueryHandler, and IntentService.

Our Experience

During Android development we hit a newborn dogfood build apiece period that the whole aggroup uses. Throughout the development of Gingerbread we ordered up our regular dogfood builds to enable StrictMode logging and upload every institute violations for analysis. Every hour a MapReduce job runs and produces an mutual report of every the circumstance wrap stalls, their arrange traces (including cross-process ones), their interval percentiles, which processes/packages they appear in, etc.

Using the accumulation from StrictMode we immobile hundreds of sensitiveness bugs and aliveness glitches every crossways the board. We prefabricated action optimizations in the Android set (e.g. grouping services and providers) so every apps on the grouping will benefit, as well as fixing up tons of app-specific issues (in both AOSP apps and Google apps). Even if youre using Froyo today, the recent updates to GMail, Google Maps, and YouTube every benefited from StrictMode accumulation assemblage gathered on Gingerbread devices.

Where we couldnt automatically speed up the system, we instead additional APIs to attain destined patterns easier to do efficiently. For example, there is a newborn method SharedPreferences.Editor.apply(), which you should be using instead of commit() if you dont requirement commit()s convey value. (It turns discover almost nobody ever checks it.) You crapper even ingest alikeness to conditionally ingest apply() vs. commit() depending on the users platform version.

Googlers who switched from Froyo to Gingerbread without seeing every the baby steps between were shocked at how such more responsive the grouping became. Our friends on the Chrome aggroup then recently additional something similar. Of course, StrictMode cant verify every the credit. The newborn concurrent garbage holder in Gingerbread also greatly reduces interval hiccups.

The Future

The StrictMode API and its capabilities will continue to expand. We hit whatever beatific stuff unsmooth up for StrictMode in Honeycomb but permit us undergo what added youd same to see! Ill be responsive questions on stackoverflow.com for questions tagged strictmode. Thanks!


Thanks
basyar.com

Tidak ada komentar:

Posting Komentar