[This post is by Brad Fitzpatrick, an Android Software Engineer who worries unreasonably most responsiveness.Tim Bray]
Back Story
One great thing most Google is 20% time: spending 20% of your happening working on projects right your important pore area. When I joined Google, I bounced every over the place, ofttimes joking that I had heptad 20% projects. One project I kept coming back to was Android. I idolized its open nature, gift me admittance to do whatever I wanted, including inaugural my garage entranceway when I approached my house on my motorcycle. I really desired it to follow but I worried most digit thing: It wasnt always caretaker smooth. Animations would sometimes falter and UI elements werent always immediately responsive to input. It was pretty obvious that things were sometimes happening 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 happy land and then continuing peppy between another 20% projects. When the Donut (Android 1.6) promulgation came out, I noticed that a whatever of my Messaging optimizations had been accidentally broken. I was sad for a taste but then I realized what Android really needed was always-on, built-in, general action monitoring.
I joined 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 covering stalls its important threads Looper). Debugging ANRs with the tools at hand was agonized and boring. There wasnt sufficiency 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 track down latency hiccups and ANRs...
Enter StrictMode
I wager you were doing 120 ms in a 16 ms zone...
StrictMode is a new 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 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: exhibit 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 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 unitedly crossways any 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 usually rely on StrictMode to support grownup calls that unknowingly 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 hair around every its operations. Only digit round operation crapper be in-flight crossways the whole device. Even a simple stat operation crapper verify quite a patch if you are unlucky. Other devices with more traditional country device-based filesystems ease occasionally suffer when the country rotation place decides to substance amass and do whatever andante interior winkle erase operations. (For whatever beatific geeky background reading, wager lwn.net/Articles/353411)
The take-away is that the round (or filesystem) on ambulatory devices is usually fast, but the 90th score latencies are ofttimes quite poor. Also, most filesystems andante down quite a taste as they intend more full. (See slides from Google I/O Zippy Android apps talk, linked off 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 certain 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 code reacting to that signaling event. If you verify individual than 16 ms, perhaps by writing 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 waiting for the filesystem hair 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 primed 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 turn it on during development, learn from it, and turn it off before you board your app.
For example, in your covering or components onCreate():
public vacuum onCreate() { if (DEVELOPER_MODE) { StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() .detectDiskReads() .detectDiskWrites() .detectNetwork() .penaltyLog() .build()); } super.onCreate(); }Or, simply:
public vacuum onCreate() { if (DEVELOPER_MODE) { StrictMode.enableDefaults(); } super.onCreate(); }That latter modify was specifically added so you crapper target 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 testing on a Gingerbread device or emulator, as daylong as you ingest sufficiency 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, turn on penaltyDropbox() and theyll be written to the DropBoxManager, where you crapper extract them after withadb bomb dumpsys dropbox data_app_strictmode --print
Tips on existence smooth
In constituent to Thread and java.util.concurrent.*, check out whatever of the Android APIs much as Handler, AsyncTask, AsyncQueryHandler, and IntentService.
Our Experience
During Android utilization we hit a new dogfood physique each day that the whole aggroup uses. Throughout the utilization of Gingerbread we ordered up our regular dogfood builds to enable StrictMode logging and upload every institute violations for analysis. Every distance a MapReduce employ runs and produces an mutual inform of every the circumstance loop stalls, their arrange traces (including cross-process ones), their latency percentiles, which processes/packages they materialize in, etc.
Using the data from StrictMode we immobile hundreds of responsiveness 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 fixing up tons of app-specific issues (in both AOSP apps and Google apps). Even if youre using Froyo today, the past updates to GMail, Google Maps, and YouTube every benefited from StrictMode data collection gathered on Gingerbread devices.
Where we couldnt automatically pace up the system, we instead added APIs to attain certain patterns easier to do efficiently. For example, there is a new method SharedPreferences.Editor.apply(), which you should be using instead of commit() if you dont requirement commit()s convey value. (It turns out nearly nobody ever checks it.) You crapper modify 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 child steps between were shocked at how much more responsive the grouping became. Our friends on the Chrome aggroup then fresh added something similar. Of course, StrictMode cant verify every the credit. The new concurrent substance collector in Gingerbread also greatly reduces latency hiccups.
The Future
The StrictMode API and its capabilities module move to expand. We hit whatever beatific stuff unsmooth up for StrictMode in Honeycomb but let 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