[This locate 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 correct your important focus area. When I connected Google, I bounced every over the place, ofttimes joking that I had heptad 20% projects. One project I kept reaching backwards to was Android. I idolized its open nature, gift me access to do whatever I wanted, including opening my garage door when I approached my concern on my motorcycle. I rattling desired it to follow but I worried most one thing: It wasnt always caretaker smooth. Animations would sometimes falter and UI elements werent always directly susceptible to input. It was pretty manifest that things were sometimes happening on the wrong thread.
As a onerous SMS user, one of my 20% projects during the Cupcake (Android 1.5) release was speeding up the Messaging app and making it see smoother. I got the app to a bright land and then continued bouncing between another 20% projects. When the Donut (Android 1.6) release came out, I noticed that a few of my Messaging optimizations had been unexpectedly broken. I was depressing for a bit but then I realized what Android rattling needed was always-on, built-in, general action monitoring.
I connected the Android aggroup full-time meet over a year ago and spent a aggregation of happening work Froyo action issues, in portion debugging ANRs (those galling dialogs you intend when an covering stalls its important threads Looper). Debugging ANRs with the tools at hand was agonized and boring. There wasnt enough arranging to encounter the causes, especially when multiple processes were participating (doing Binder or ContentResolver dealings to Services or ContentProviders in another processes). There had to be a meliorate artefact to road downbound interval hiccups and ANRs...
Enter StrictMode
I see 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 penalty is if you violate the policy. Implementation-wise, this contract is simply a thread-local integer 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 manus around most of the places that hit the round (in java.io.*, android.database.sqlite.*, etc) and meshwork (java.net.*) which check the underway threads policy, reacting as youve asked.
StrictModes coercive conception 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 any number of processes.
Nobody wants to be slow
You strength know every the places where your app does round I/O, but do you know every the places where the grouping services and providers do? I dont. Im learning, but its a aggregation of code. Were continually working to clarify action implications in the SDK docs, but I commonly rely on StrictMode to support catch calls that inadvertently hit the disk.
Background on disks on phones
Wait, whats wrong with touch the disk? Android devices are every running winkle memory, right? Thats same a super-fast SSD with no moving parts? I shouldnt have to care? Unfortunately, you do.
You cant depend on the winkle components or filesystems used in most Android devices to be consistently fast. The YAFFS filesystem used on whatever Android devices, for instance, has a global hair around every its operations. Only one 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 still occasionally suffer when the country turning place decides to substance collect and do whatever andante internal winkle cancel operations. (For whatever beatific geeky scenery reading, see lwn.net/Articles/353411)
The take-away is that the round (or filesystem) on mobile devices is commonly fast, but the 90th percentile latencies are ofttimes quite poor. Also, most filesystems andante downbound quite a bit 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 impact their animations by callbacks on the important thread.
If you poverty to separate an aliveness at 60 fps and an input circumstance comes in (also on the important thread), you have 16 ms to separate your cipher reacting to that input event. If you verify individual than 16 ms, perhaps by composition to disk, youve now stuttered your animation. Disk reads are ofttimes better, but they crapper also verify individual than 16 ms, especially on YAFFS if youre inactivity for the filesystem hair thats held by a impact in the middle 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 release 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 smooth below.)
Enabling StrictMode
The advisable 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 covering or components onCreate():
open vacuum onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); } super.onCreate(); }Or, simply:
open vacuum onCreate() { if (DEVELOPER_MODE) { StrictMode.enableDefaults(); } super.onCreate(); }That latter modify was specifically additional so you crapper direct pre-Gingerbread API versions but still easily enable StrictMode using alikeness or another techniques. For instance, you could be targeting Donut (Android 1.6) but still ingest StrictMode if youre investigating on a Gingerbread figure or emulator, as long as you ingest enough Reflection to call StrictMode.enableDefaults().
Watching StrictMode
If youre using penaltyLog(), the default, meet separate adb logcat and watch the terminal output. Any violations module be logged to your console, slightly rate-limited for duplicate 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 addition to Thread and java.util.concurrent.*, check discover whatever of the Android APIs such as Handler, AsyncTask, AsyncQueryHandler, and IntentService.
Our Experience
During Android utilization we have a newborn dogfood physique apiece period that the whole aggroup uses. Throughout the utilization of Gingerbread we ordered up our regular dogfood builds to enable StrictMode logging and upload every found violations for analysis. Every hour a MapReduce job runs and produces an mutual inform of every the circumstance loop stalls, their arrange traces (including cross-process ones), their interval percentiles, which processes/packages they materialize in, etc.
Using the accumulation from StrictMode we fixed hundreds of sensitiveness bugs and aliveness glitches every crossways the board. We prefabricated action optimizations in the Android core (e.g. grouping services and providers) so every apps on the grouping module benefit, as substantially as sterilisation 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 certain 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 return value. (It turns discover almost nobody ever checks it.) You crapper modify ingest alikeness to conditionally ingest apply() vs. commit() depending on the users papers version.
Googlers who switched from Froyo to Gingerbread without sight every the baby steps between were shocked at how such more susceptible the grouping became. Our friends on the Chrome aggroup then fresh additional something similar. Of course, StrictMode cant verify every the credit. The newborn concurrent substance holder in Gingerbread also greatly reduces interval hiccups.
The Future
The StrictMode API and its capabilities module continue to expand. We have whatever beatific clog lined up for StrictMode in Honeycomb but let us know 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