[This locate is by Brad Fitzpatrick, an Android Software Engineer who worries unreasonably most responsiveness.Tim Bray]
Back Story
One enthusiastic abstract most Google is 20% time: outlay 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 seven 20% projects. One project I kept coming backwards to was Android. I loved its open nature, giving me admittance to do whatever I wanted, including opening my garage entranceway when I approached my house on my motorcycle. I rattling desired it to follow but I worried most digit thing: It wasnt ever caretaker smooth. Animations would sometimes stutter and UI elements werent ever directly responsive to input. It was pretty obvious that things were sometimes happening on the criminal thread.
As a onerous 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 detected that a few of my Messaging optimizations had been accidentally broken. I was sad for a taste 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 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 assistance was agonized and boring. There wasnt enough instrumentation to find the causes, especially when binary processes were participating (doing Binder or ContentResolver dealings to Services or ContentProviders in another processes). There had to be a meliorate artefact to track downbound latency 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 violate the policy. Implementation-wise, this contract is only a thread-local sort 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 impact the round (in java.io.*, android.database.sqlite.*, etc) and meshwork (java.net.*) which analyse the underway threads policy, reacting as youve asked.
StrictModes powerful 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 sort 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 clarify action implications in the SDK docs, but I commonly rely on StrictMode to help grownup calls that inadvertently impact 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 activeness crapper be in-flight crossways the entire device. Even a simple stat activeness crapper verify quite a while if you are unlucky. Other devices with more traditional country device-based filesystems ease occasionally suffer when the country turning layer decides to garbage collect 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 mobile devices is commonly fast, but the 90th percentile 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 life easier most of the time, but its also something you requirement to be certain 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 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 writing to disk, youve now stuttered your animation. Disk reads are ofttimes better, but they crapper also verify longer than 16 ms, especially on YAFFS if youre inactivity for the filesystem hair thats held by a impact 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 fatal error, unless your app is targeting an API version 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 being uncreased below.)
Enabling StrictMode
The recommended artefact to ingest StrictMode is to turn it on during development, see from it, and turn 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 form was specifically additional 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 investigating on a Gingerbread figure or emulator, as daylong as you ingest enough Reflection to call StrictMode.enableDefaults().
Watching StrictMode
If youre using penaltyLog(), the default, meet separate adb logcat and analyse the tangency 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 cursive to the DropBoxManager, where you crapper select them later withadb bomb dumpsys dropbox data_app_strictmode --print
Tips on being 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 utilization we hit a newborn dogfood physique each 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 interactive report of every the circumstance wrap stalls, their arrange traces (including cross-process ones), their latency percentiles, which processes/packages they appear 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 heaps 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 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 papers 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 additional something similar. Of course, StrictMode cant verify every the credit. The newborn concurrent garbage collector in Gingerbread also greatly reduces latency hiccups.
The Future
The StrictMode API and its capabilities module move to expand. We hit whatever beatific clog unsmooth up for StrictMode in Honeycomb but let us undergo what else youd same to see! Ill be answering questions on stackoverflow.com for questions tagged strictmode. Thanks!
Thanks
basyar.com
Tidak ada komentar:
Posting Komentar